From 35afe8257cc9f8484ee238d8687f70ff4c83780f Mon Sep 17 00:00:00 2001 From: Alex Dima Date: Wed, 8 Aug 2018 15:32:31 +0200 Subject: [PATCH] Update to typescript 3.0.1 --- package-lock.json | 30 +- package.json | 4 +- scripts/importTypescript.js | 26 +- src/lib/lib-es6-ts.ts | 2 +- src/lib/lib-ts.ts | 2 +- src/lib/typescriptServices-amd.js | 63982 ++++++++++++++++------------ src/lib/typescriptServices.d.ts | 1867 +- src/lib/typescriptServices.js | 63982 ++++++++++++++++------------ src/tsWorker.ts | 4 +- 9 files changed, 73779 insertions(+), 56120 deletions(-) diff --git a/package-lock.json b/package-lock.json index 821f9ea4..e121fe1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -168,7 +168,15 @@ "integrity": "sha512-7kUx8dtd5qVNVgUARBRhnM8oftPglYwlINfigC4yGUiuzqtIN22u1tly8umiOCIPR0eFiBLjt6aN23oZh2QJgg==", "dev": true, "requires": { - "typescript": "2.8.1" + "typescript": "2.9.2" + }, + "dependencies": { + "typescript": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz", + "integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==", + "dev": true + } } }, "ms": { @@ -214,25 +222,25 @@ } }, "typescript": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-2.8.1.tgz", - "integrity": "sha512-Ao/f6d/4EPLq0YwzsQz8iXflezpTkQzqAyenTiw4kCUGr1uPiFLC3+fZ+gMZz6eeI/qdRUqvC+HxIJzUAzEFdg==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.0.1.tgz", + "integrity": "sha512-zQIMOmC+372pC/CCVLqnQ0zSBiY7HHodU7mpQdjiZddek4GMj31I3dUJ7gAs9o65X7mnRma6OokOkc6f9jjfBg==", "dev": true }, "uglify-js": { - "version": "3.3.14", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.3.14.tgz", - "integrity": "sha512-OY8VPQU25q09gQRbC+Ekk3xgEVBmYFEfVcgS47ksjTiNht2LmLlUkWutyi38ZsDSToJHwbe76kDGwmD226Z2Fg==", + "version": "3.4.6", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.6.tgz", + "integrity": "sha512-O1D7L6WcOzS1qW2ehopEm4cWm5yA6bQBozlks8jO8ODxYCy4zv+bR/la4Lwp01tpkYGNonnpXvUpYtrvSu8Yzg==", "dev": true, "requires": { - "commander": "2.14.1", + "commander": "2.16.0", "source-map": "0.6.1" }, "dependencies": { "commander": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/commander/-/commander-2.14.1.tgz", - "integrity": "sha512-+YR16o3rK53SmWHU3rEM3tPAh2rwb1yPcQX5irVn7mb0gXbwuCCrnkbV5+PBfETdfg1vui07nM6PCG1zndcjQw==", + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.16.0.tgz", + "integrity": "sha512-sVXqklSaotK9at437sFlFpyOcJonxe0yST/AG9DkQKUdIE6IqGIMv4SfAQSKaJbSdVEJYItASCrBiVQHq1HQew==", "dev": true } } diff --git a/package.json b/package.json index 4e827f8c..b6898108 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "monaco-editor-core": "0.12.0", "monaco-plugin-helpers": "^1.0.2", "requirejs": "^2.3.5", - "typescript": "2.8.1", - "uglify-js": "^3.3.14" + "typescript": "3.0.1", + "uglify-js": "^3.4.6" } } diff --git a/scripts/importTypescript.js b/scripts/importTypescript.js index 5ef0bafe..e9b90bc7 100644 --- a/scripts/importTypescript.js +++ b/scripts/importTypescript.js @@ -67,9 +67,8 @@ export = ts; */ function importLibDeclarationFile(name) { var dstName = name.replace(/\.d\.ts$/, '').replace(/\./g, '-') + '-ts'; - var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, name); - var contents = fs.readFileSync(srcPath).toString(); + var contents = resolveLibFile(null, name); var dstPath = path.join(TYPESCRIPT_LIB_DESTINATION, dstName + '.ts'); fs.writeFileSync(dstPath, @@ -82,6 +81,29 @@ export const contents = "${escapeText(contents)}"; `); } +function resolveLibFile(name, filename) { + var srcPath; + if (filename) { + srcPath = path.join(TYPESCRIPT_LIB_SOURCE, filename); + } else { + srcPath = path.join(TYPESCRIPT_LIB_SOURCE, `lib.${name}.d.ts`); + } + + var contents = fs.readFileSync(srcPath).toString(); + var lines = contents.split(/\r\n|\r|\n/); + var result = []; + for (let i = 0; i < lines.length; i++) { + let m = lines[i].match(/\/\/\/\s*\n\n\n/////////////////////////////\n/// ECMAScript APIs\n/////////////////////////////\n\ndeclare const NaN: number;\ndeclare const Infinity: number;\n\n/**\n * Evaluates JavaScript code and executes it.\n * @param x A String value that contains valid JavaScript code.\n */\ndeclare function eval(x: string): any;\n\n/**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\ndeclare function parseInt(s: string, radix?: number): number;\n\n/**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\ndeclare function parseFloat(string: string): number;\n\n/**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\n * @param number A numeric value.\n */\ndeclare function isNaN(number: number): boolean;\n\n/**\n * Determines whether a supplied number is finite.\n * @param number Any numeric value.\n */\ndeclare function isFinite(number: number): boolean;\n\n/**\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\n * @param encodedURI A value representing an encoded URI.\n */\ndeclare function decodeURI(encodedURI: string): string;\n\n/**\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\n * @param encodedURIComponent A value representing an encoded URI component.\n */\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\n\n/**\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\n * @param uri A value representing an encoded URI.\n */\ndeclare function encodeURI(uri: string): string;\n\n/**\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\n * @param uriComponent A value representing an encoded URI component.\n */\ndeclare function encodeURIComponent(uriComponent: string): string;\n\n/**\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\n * @param string A string value\n */\ndeclare function escape(string: string): string;\n\n/**\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\n * @param string A string value\n */\ndeclare function unescape(string: string): string;\n\ninterface PropertyDescriptor {\n configurable?: boolean;\n enumerable?: boolean;\n value?: any;\n writable?: boolean;\n get?(): any;\n set?(v: any): void;\n}\n\ninterface PropertyDescriptorMap {\n [s: string]: PropertyDescriptor;\n}\n\ninterface Object {\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\n constructor: Function;\n\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns a date converted to a string using the current locale. */\n toLocaleString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): Object;\n\n /**\n * Determines whether an object has a property with the specified name.\n * @param v A property name.\n */\n hasOwnProperty(v: string): boolean;\n\n /**\n * Determines whether an object exists in another object's prototype chain.\n * @param v Another object whose prototype chain is to be checked.\n */\n isPrototypeOf(v: Object): boolean;\n\n /**\n * Determines whether a specified property is enumerable.\n * @param v A property name.\n */\n propertyIsEnumerable(v: string): boolean;\n}\n\ninterface ObjectConstructor {\n new(value?: any): Object;\n (): any;\n (value: any): any;\n\n /** A reference to the prototype for a class of objects. */\n readonly prototype: Object;\n\n /**\n * Returns the prototype of an object.\n * @param o The object that references the prototype.\n */\n getPrototypeOf(o: any): any;\n\n /**\n * Gets the own property descriptor of the specified object.\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\n * @param o Object that contains the property.\n * @param p Name of the property.\n */\n getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined;\n\n /**\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\n * @param o Object that contains the own properties.\n */\n getOwnPropertyNames(o: any): string[];\n\n /**\n * Creates an object that has the specified prototype or that has null prototype.\n * @param o Object to use as a prototype. May be null.\n */\n create(o: object | null): any;\n\n /**\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\n * @param o Object to use as a prototype. May be null\n * @param properties JavaScript object that contains one or more property descriptors.\n */\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Adds a property to an object, or modifies attributes of an existing property.\n * @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.\n * @param p The property name.\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\n */\n defineProperty(o: any, p: string, attributes: PropertyDescriptor & ThisType): any;\n\n /**\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\n */\n defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n seal(o: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(a: T[]): ReadonlyArray;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(f: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(o: T): Readonly;\n\n /**\n * Prevents the addition of new properties to an object.\n * @param o Object to make non-extensible.\n */\n preventExtensions(o: T): T;\n\n /**\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isSealed(o: any): boolean;\n\n /**\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isFrozen(o: any): boolean;\n\n /**\n * Returns a value that indicates whether new properties can be added to an object.\n * @param o Object to test.\n */\n isExtensible(o: any): boolean;\n\n /**\n * Returns the names of the enumerable properties and methods of an object.\n * @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.\n */\n keys(o: {}): string[];\n}\n\n/**\n * Provides functionality common to all JavaScript objects.\n */\ndeclare const Object: ObjectConstructor;\n\n/**\n * Creates a new function.\n */\ninterface Function {\n /**\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\n * @param thisArg The object to be used as the this object.\n * @param argArray A set of arguments to be passed to the function.\n */\n apply(this: Function, thisArg: any, argArray?: any): any;\n\n /**\n * Calls a method of an object, substituting another object for the current object.\n * @param thisArg The object to be used as the current object.\n * @param argArray A list of arguments to be passed to the method.\n */\n call(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /**\n * For a given function, creates a bound function that has the same body as the original function.\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\n * @param thisArg An object to which the this keyword can refer inside the new function.\n * @param argArray A list of arguments to be passed to the new function.\n */\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /** Returns a string representation of a function. */\n toString(): string;\n\n prototype: any;\n readonly length: number;\n\n // Non-standard extensions\n arguments: any;\n caller: Function;\n}\n\ninterface FunctionConstructor {\n /**\n * Creates a new function.\n * @param args A list of arguments the function accepts.\n */\n new(...args: string[]): Function;\n (...args: string[]): Function;\n readonly prototype: Function;\n}\n\ndeclare const Function: FunctionConstructor;\n\ninterface IArguments {\n [index: number]: any;\n length: number;\n callee: Function;\n}\n\ninterface String {\n /** Returns a string representation of a string. */\n toString(): string;\n\n /**\n * Returns the character at the specified index.\n * @param pos The zero-based index of the desired character.\n */\n charAt(pos: number): string;\n\n /**\n * Returns the Unicode value of the character at the specified location.\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\n */\n charCodeAt(index: number): number;\n\n /**\n * Returns a string that contains the concatenation of two or more strings.\n * @param strings The strings to append to the end of the string.\n */\n concat(...strings: string[]): string;\n\n /**\n * Returns the position of the first occurrence of a substring.\n * @param searchString The substring to search for in the string\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\n */\n indexOf(searchString: string, position?: number): number;\n\n /**\n * Returns the last occurrence of a substring in the string.\n * @param searchString The substring to search for.\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\n */\n lastIndexOf(searchString: string, position?: number): number;\n\n /**\n * Determines whether two strings are equivalent in the current locale.\n * @param that String to compare to target string\n */\n localeCompare(that: string): number;\n\n /**\n * Matches a string with a regular expression, and returns an array containing the results of that search.\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\n */\n match(regexp: string | RegExp): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: string | RegExp, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param regexp The regular expression pattern and applicable flags.\n */\n search(regexp: string | RegExp): number;\n\n /**\n * Returns a section of a string.\n * @param start The index to the beginning of the specified portion of stringObj.\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\n * If this value is not specified, the substring continues to the end of stringObj.\n */\n slice(start?: number, end?: number): string;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(separator: string | RegExp, limit?: number): string[];\n\n /**\n * Returns the substring at the specified location within a String object.\n * @param start The zero-based index number indicating the beginning of the substring.\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\n * If end is omitted, the characters from start through the end of the original string are returned.\n */\n substring(start: number, end?: number): string;\n\n /** Converts all the alphabetic characters in a string to lowercase. */\n toLowerCase(): string;\n\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\n toLocaleLowerCase(): string;\n\n /** Converts all the alphabetic characters in a string to uppercase. */\n toUpperCase(): string;\n\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\n toLocaleUpperCase(): string;\n\n /** Removes the leading and trailing white space and line terminator characters from a string. */\n trim(): string;\n\n /** Returns the length of a String object. */\n readonly length: number;\n\n // IE extensions\n /**\n * Gets a substring beginning at the specified location and having the specified length.\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\n * @param length The number of characters to include in the returned substring.\n */\n substr(from: number, length?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): string;\n\n readonly [index: number]: string;\n}\n\ninterface StringConstructor {\n new(value?: any): String;\n (value?: any): string;\n readonly prototype: String;\n fromCharCode(...codes: number[]): string;\n}\n\n/**\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\n */\ndeclare const String: StringConstructor;\n\ninterface Boolean {\n /** Returns the primitive value of the specified object. */\n valueOf(): boolean;\n}\n\ninterface BooleanConstructor {\n new(value?: any): Boolean;\n (value?: any): boolean;\n readonly prototype: Boolean;\n}\n\ndeclare const Boolean: BooleanConstructor;\n\ninterface Number {\n /**\n * Returns a string representation of an object.\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\n */\n toString(radix?: number): string;\n\n /**\n * Returns a string representing a number in fixed-point notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toFixed(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented in exponential notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toExponential(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\n */\n toPrecision(precision?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): number;\n}\n\ninterface NumberConstructor {\n new(value?: any): Number;\n (value?: any): number;\n readonly prototype: Number;\n\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\n readonly MAX_VALUE: number;\n\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\n readonly MIN_VALUE: number;\n\n /**\n * A value that is not a number.\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\n */\n readonly NaN: number;\n\n /**\n * A value that is less than the largest negative number that can be represented in JavaScript.\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\n */\n readonly NEGATIVE_INFINITY: number;\n\n /**\n * A value greater than the largest number that can be represented in JavaScript.\n * JavaScript displays POSITIVE_INFINITY values as infinity.\n */\n readonly POSITIVE_INFINITY: number;\n}\n\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\ndeclare const Number: NumberConstructor;\n\ninterface TemplateStringsArray extends ReadonlyArray {\n readonly raw: ReadonlyArray;\n}\n\ninterface Math {\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\n readonly E: number;\n /** The natural logarithm of 10. */\n readonly LN10: number;\n /** The natural logarithm of 2. */\n readonly LN2: number;\n /** The base-2 logarithm of e. */\n readonly LOG2E: number;\n /** The base-10 logarithm of e. */\n readonly LOG10E: number;\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\n readonly PI: number;\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\n readonly SQRT1_2: number;\n /** The square root of 2. */\n readonly SQRT2: number;\n /**\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\n * For example, the absolute value of -5 is the same as the absolute value of 5.\n * @param x A numeric expression for which the absolute value is needed.\n */\n abs(x: number): number;\n /**\n * Returns the arc cosine (or inverse cosine) of a number.\n * @param x A numeric expression.\n */\n acos(x: number): number;\n /**\n * Returns the arcsine of a number.\n * @param x A numeric expression.\n */\n asin(x: number): number;\n /**\n * Returns the arctangent of a number.\n * @param x A numeric expression for which the arctangent is needed.\n */\n atan(x: number): number;\n /**\n * Returns the angle (in radians) from the X axis to a point.\n * @param y A numeric expression representing the cartesian y-coordinate.\n * @param x A numeric expression representing the cartesian x-coordinate.\n */\n atan2(y: number, x: number): number;\n /**\n * Returns the smallest integer greater than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n ceil(x: number): number;\n /**\n * Returns the cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cos(x: number): number;\n /**\n * Returns e (the base of natural logarithms) raised to a power.\n * @param x A numeric expression representing the power of e.\n */\n exp(x: number): number;\n /**\n * Returns the greatest integer less than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n floor(x: number): number;\n /**\n * Returns the natural logarithm (base e) of a number.\n * @param x A numeric expression.\n */\n log(x: number): number;\n /**\n * Returns the larger of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n max(...values: number[]): number;\n /**\n * Returns the smaller of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n min(...values: number[]): number;\n /**\n * Returns the value of a base expression taken to a specified power.\n * @param x The base value of the expression.\n * @param y The exponent value of the expression.\n */\n pow(x: number, y: number): number;\n /** Returns a pseudorandom number between 0 and 1. */\n random(): number;\n /**\n * Returns a supplied numeric expression rounded to the nearest number.\n * @param x The value to be rounded to the nearest number.\n */\n round(x: number): number;\n /**\n * Returns the sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sin(x: number): number;\n /**\n * Returns the square root of a number.\n * @param x A numeric expression.\n */\n sqrt(x: number): number;\n /**\n * Returns the tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tan(x: number): number;\n}\n/** An intrinsic object that provides basic mathematics functionality and constants. */\ndeclare const Math: Math;\n\n/** Enables basic storage and retrieval of dates and times. */\ninterface Date {\n /** Returns a string representation of a date. The format of the string depends on the locale. */\n toString(): string;\n /** Returns a date as a string value. */\n toDateString(): string;\n /** Returns a time as a string value. */\n toTimeString(): string;\n /** Returns a value as a string value appropriate to the host environment's current locale. */\n toLocaleString(): string;\n /** Returns a date as a string value appropriate to the host environment's current locale. */\n toLocaleDateString(): string;\n /** Returns a time as a string value appropriate to the host environment's current locale. */\n toLocaleTimeString(): string;\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\n valueOf(): number;\n /** Gets the time value in milliseconds. */\n getTime(): number;\n /** Gets the year, using local time. */\n getFullYear(): number;\n /** Gets the year using Universal Coordinated Time (UTC). */\n getUTCFullYear(): number;\n /** Gets the month, using local time. */\n getMonth(): number;\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\n getUTCMonth(): number;\n /** Gets the day-of-the-month, using local time. */\n getDate(): number;\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\n getUTCDate(): number;\n /** Gets the day of the week, using local time. */\n getDay(): number;\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\n getUTCDay(): number;\n /** Gets the hours in a date, using local time. */\n getHours(): number;\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\n getUTCHours(): number;\n /** Gets the minutes of a Date object, using local time. */\n getMinutes(): number;\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\n getUTCMinutes(): number;\n /** Gets the seconds of a Date object, using local time. */\n getSeconds(): number;\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCSeconds(): number;\n /** Gets the milliseconds of a Date, using local time. */\n getMilliseconds(): number;\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCMilliseconds(): number;\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\n getTimezoneOffset(): number;\n /**\n * Sets the date and time value in the Date object.\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\n */\n setTime(time: number): number;\n /**\n * Sets the milliseconds value in the Date object using local time.\n * @param ms A numeric value equal to the millisecond value.\n */\n setMilliseconds(ms: number): number;\n /**\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\n * @param ms A numeric value equal to the millisecond value.\n */\n setUTCMilliseconds(ms: number): number;\n\n /**\n * Sets the seconds value in the Date object using local time.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setSeconds(sec: number, ms?: number): number;\n /**\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCSeconds(sec: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using local time.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the hour value in the Date object using local time.\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the numeric day-of-the-month value of the Date object using local time.\n * @param date A numeric value equal to the day of the month.\n */\n setDate(date: number): number;\n /**\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\n * @param date A numeric value equal to the day of the month.\n */\n setUTCDate(date: number): number;\n /**\n * Sets the month value in the Date object using local time.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\n */\n setMonth(month: number, date?: number): number;\n /**\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\n */\n setUTCMonth(month: number, date?: number): number;\n /**\n * Sets the year of the Date object using local time.\n * @param year A numeric value for the year.\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\n * @param date A numeric value equal for the day of the month.\n */\n setFullYear(year: number, month?: number, date?: number): number;\n /**\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\n * @param year A numeric value equal to the year.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\n * @param date A numeric value equal to the day of the month.\n */\n setUTCFullYear(year: number, month?: number, date?: number): number;\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\n toUTCString(): string;\n /** Returns a date as a string value in ISO format. */\n toISOString(): string;\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\n toJSON(key?: any): string;\n}\n\ninterface DateConstructor {\n new(): Date;\n new(value: number): Date;\n new(value: string): Date;\n new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;\n (): string;\n readonly prototype: Date;\n /**\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\n * @param s A date string\n */\n parse(s: string): number;\n /**\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\n * @param month The month as an number between 0 and 11 (January to December).\n * @param date The date as an number between 1 and 31.\n * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.\n * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.\n * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.\n * @param ms An number from 0 to 999 that specifies the milliseconds.\n */\n UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;\n now(): number;\n}\n\ndeclare const Date: DateConstructor;\n\ninterface RegExpMatchArray extends Array {\n index?: number;\n input?: string;\n}\n\ninterface RegExpExecArray extends Array {\n index: number;\n input: string;\n}\n\ninterface RegExp {\n /**\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\n * @param string The String object or string literal on which to perform the search.\n */\n exec(string: string): RegExpExecArray | null;\n\n /**\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\n * @param string String on which to perform the search.\n */\n test(string: string): boolean;\n\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\n readonly source: string;\n\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\n readonly global: boolean;\n\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\n readonly ignoreCase: boolean;\n\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\n readonly multiline: boolean;\n\n lastIndex: number;\n\n // Non-standard extensions\n compile(): this;\n}\n\ninterface RegExpConstructor {\n new(pattern: RegExp | string): RegExp;\n new(pattern: string, flags?: string): RegExp;\n (pattern: RegExp | string): RegExp;\n (pattern: string, flags?: string): RegExp;\n readonly prototype: RegExp;\n\n // Non-standard extensions\n $1: string;\n $2: string;\n $3: string;\n $4: string;\n $5: string;\n $6: string;\n $7: string;\n $8: string;\n $9: string;\n lastMatch: string;\n}\n\ndeclare const RegExp: RegExpConstructor;\n\ninterface Error {\n name: string;\n message: string;\n stack?: string;\n}\n\ninterface ErrorConstructor {\n new(message?: string): Error;\n (message?: string): Error;\n readonly prototype: Error;\n}\n\ndeclare const Error: ErrorConstructor;\n\ninterface EvalError extends Error {\n}\n\ninterface EvalErrorConstructor {\n new(message?: string): EvalError;\n (message?: string): EvalError;\n readonly prototype: EvalError;\n}\n\ndeclare const EvalError: EvalErrorConstructor;\n\ninterface RangeError extends Error {\n}\n\ninterface RangeErrorConstructor {\n new(message?: string): RangeError;\n (message?: string): RangeError;\n readonly prototype: RangeError;\n}\n\ndeclare const RangeError: RangeErrorConstructor;\n\ninterface ReferenceError extends Error {\n}\n\ninterface ReferenceErrorConstructor {\n new(message?: string): ReferenceError;\n (message?: string): ReferenceError;\n readonly prototype: ReferenceError;\n}\n\ndeclare const ReferenceError: ReferenceErrorConstructor;\n\ninterface SyntaxError extends Error {\n}\n\ninterface SyntaxErrorConstructor {\n new(message?: string): SyntaxError;\n (message?: string): SyntaxError;\n readonly prototype: SyntaxError;\n}\n\ndeclare const SyntaxError: SyntaxErrorConstructor;\n\ninterface TypeError extends Error {\n}\n\ninterface TypeErrorConstructor {\n new(message?: string): TypeError;\n (message?: string): TypeError;\n readonly prototype: TypeError;\n}\n\ndeclare const TypeError: TypeErrorConstructor;\n\ninterface URIError extends Error {\n}\n\ninterface URIErrorConstructor {\n new(message?: string): URIError;\n (message?: string): URIError;\n readonly prototype: URIError;\n}\n\ndeclare const URIError: URIErrorConstructor;\n\ninterface JSON {\n /**\n * Converts a JavaScript Object Notation (JSON) string into an object.\n * @param text A valid JSON string.\n * @param reviver A function that transforms the results. This function is called for each member of the object.\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\n */\n parse(text: string, reviver?: (key: any, value: any) => any): any;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer A function that transforms the results.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\n}\n\n/**\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\n */\ndeclare const JSON: JSON;\n\n\n/////////////////////////////\n/// ECMAScript Array API (specially handled by compiler)\n/////////////////////////////\n\ninterface ReadonlyArray {\n /**\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n readonly length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n\n readonly [n: number]: T;\n}\n\ninterface ConcatArray {\n readonly length: number;\n readonly [n: number]: T;\n join(separator?: string): string;\n slice(start?: number, end?: number): T[];\n}\n\ninterface Array {\n /**\n * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Appends new elements to an array, and returns the new length of the array.\n * @param items New elements of the Array.\n */\n push(...items: T[]): number;\n /**\n * Removes the last element from an array and returns it.\n */\n pop(): T | undefined;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Reverses the elements in an Array.\n */\n reverse(): T[];\n /**\n * Removes the first element from an array and returns it.\n */\n shift(): T | undefined;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: T, b: T) => number): this;\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n */\n splice(start: number, deleteCount?: number): T[];\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the array in place of the deleted elements.\n */\n splice(start: number, deleteCount: number, ...items: T[]): T[];\n /**\n * Inserts new elements at the start of an array.\n * @param items Elements to insert at the start of the Array.\n */\n unshift(...items: T[]): number;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n\n [n: number]: T;\n}\n\ninterface ArrayConstructor {\n new(arrayLength?: number): any[];\n new (arrayLength: number): T[];\n new (...items: T[]): T[];\n (arrayLength?: number): any[];\n (arrayLength: number): T[];\n (...items: T[]): T[];\n isArray(arg: any): arg is Array;\n readonly prototype: Array;\n}\n\ndeclare const Array: ArrayConstructor;\n\ninterface TypedPropertyDescriptor {\n enumerable?: boolean;\n configurable?: boolean;\n writable?: boolean;\n value?: T;\n get?: () => T;\n set?: (value: T) => void;\n}\n\ndeclare type ClassDecorator = (target: TFunction) => TFunction | void;\ndeclare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;\ndeclare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;\ndeclare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;\n\ndeclare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike;\n\ninterface PromiseLike {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike;\n}\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface Promise {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise;\n\n /**\n * Attaches a callback for only the rejection of the Promise.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of the callback.\n */\n catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise;\n}\n\ninterface ArrayLike {\n readonly length: number;\n readonly [n: number]: T;\n}\n\n/**\n * Make all properties in T optional\n */\ntype Partial = {\n [P in keyof T]?: T[P];\n};\n\n/**\n * Make all properties in T required\n */\ntype Required = {\n [P in keyof T]-?: T[P];\n};\n\n/**\n * Make all properties in T readonly\n */\ntype Readonly = {\n readonly [P in keyof T]: T[P];\n};\n\n/**\n * From T pick a set of properties K\n */\ntype Pick = {\n [P in K]: T[P];\n};\n\n/**\n * Construct a type with a set of properties K of type T\n */\ntype Record = {\n [P in K]: T;\n};\n\n/**\n * Exclude from T those types that are assignable to U\n */\ntype Exclude = T extends U ? never : T;\n\n/**\n * Extract from T those types that are assignable to U\n */\ntype Extract = T extends U ? T : never;\n\n/**\n * Exclude null and undefined from T\n */\ntype NonNullable = T extends null | undefined ? never : T;\n\n/**\n * Obtain the return type of a function type\n */\ntype ReturnType any> = T extends (...args: any[]) => infer R ? R : any;\n\n/**\n * Obtain the return type of a constructor function type\n */\ntype InstanceType any> = T extends new (...args: any[]) => infer R ? R : any;\n\n/**\n * Marker for contextual 'this' type\n */\ninterface ThisType { }\n\n/**\n * Represents a raw buffer of binary data, which is used to store data for the\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\n * but can be passed to a typed array or DataView Object to interpret the raw\n * buffer as needed.\n */\ninterface ArrayBuffer {\n /**\n * Read-only. The length of the ArrayBuffer (in bytes).\n */\n readonly byteLength: number;\n\n /**\n * Returns a section of an ArrayBuffer.\n */\n slice(begin: number, end?: number): ArrayBuffer;\n}\n\n/**\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\n */\ninterface ArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\n\ninterface ArrayBufferConstructor {\n readonly prototype: ArrayBuffer;\n new(byteLength: number): ArrayBuffer;\n isView(arg: any): arg is ArrayBufferView;\n}\ndeclare const ArrayBuffer: ArrayBufferConstructor;\n\ninterface ArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\ninterface DataView {\n readonly buffer: ArrayBuffer;\n readonly byteLength: number;\n readonly byteOffset: number;\n /**\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt8(byteOffset: number): number;\n\n /**\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt16(byteOffset: number, littleEndian?: boolean): number;\n /**\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint8(byteOffset: number): number;\n\n /**\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint16(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Stores an Float32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Float64 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setInt8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Int16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setUint8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Uint16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\n}\n\ninterface DataViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;\n}\ndeclare const DataView: DataViewConstructor;\n\n/**\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Int8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\ninterface Int8ArrayConstructor {\n readonly prototype: Int8Array;\n new(length: number): Int8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n\n\n}\ndeclare const Int8Array: Int8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ArrayConstructor {\n readonly prototype: Uint8Array;\n new(length: number): Uint8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n\n}\ndeclare const Uint8Array: Uint8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\n * If the requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8ClampedArray {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8ClampedArray;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8ClampedArray;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8ClampedArray;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ClampedArrayConstructor {\n readonly prototype: Uint8ClampedArray;\n new(length: number): Uint8ClampedArray;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8ClampedArray;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\ndeclare const Uint8ClampedArray: Uint8ClampedArrayConstructor;\n\n/**\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int16ArrayConstructor {\n readonly prototype: Int16Array;\n new(length: number): Int16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n\n\n}\ndeclare const Int16Array: Int16ArrayConstructor;\n\n/**\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint16ArrayConstructor {\n readonly prototype: Uint16Array;\n new(length: number): Uint16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n\n\n}\ndeclare const Uint16Array: Uint16ArrayConstructor;\n/**\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int32ArrayConstructor {\n readonly prototype: Int32Array;\n new(length: number): Int32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n\n}\ndeclare const Int32Array: Int32ArrayConstructor;\n\n/**\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint32ArrayConstructor {\n readonly prototype: Uint32Array;\n new(length: number): Uint32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n\n}\ndeclare const Uint32Array: Uint32ArrayConstructor;\n\n/**\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\n * of bytes could not be allocated an exception is raised.\n */\ninterface Float32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float32ArrayConstructor {\n readonly prototype: Float32Array;\n new(length: number): Float32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n\n\n}\ndeclare const Float32Array: Float32ArrayConstructor;\n\n/**\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Float64Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float64Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float64Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float64Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float64ArrayConstructor {\n readonly prototype: Float64Array;\n new(length: number): Float64Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n\n}\ndeclare const Float64Array: Float64ArrayConstructor;\n\n/////////////////////////////\n/// ECMAScript Internationalization API\n/////////////////////////////\n\ndeclare namespace Intl {\n interface CollatorOptions {\n usage?: string;\n localeMatcher?: string;\n numeric?: boolean;\n caseFirst?: string;\n sensitivity?: string;\n ignorePunctuation?: boolean;\n }\n\n interface ResolvedCollatorOptions {\n locale: string;\n usage: string;\n sensitivity: string;\n ignorePunctuation: boolean;\n collation: string;\n caseFirst: string;\n numeric: boolean;\n }\n\n interface Collator {\n compare(x: string, y: string): number;\n resolvedOptions(): ResolvedCollatorOptions;\n }\n var Collator: {\n new(locales?: string | string[], options?: CollatorOptions): Collator;\n (locales?: string | string[], options?: CollatorOptions): Collator;\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\n };\n\n interface NumberFormatOptions {\n localeMatcher?: string;\n style?: string;\n currency?: string;\n currencyDisplay?: string;\n useGrouping?: boolean;\n minimumIntegerDigits?: number;\n minimumFractionDigits?: number;\n maximumFractionDigits?: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n }\n\n interface ResolvedNumberFormatOptions {\n locale: string;\n numberingSystem: string;\n style: string;\n currency?: string;\n currencyDisplay?: string;\n minimumIntegerDigits: number;\n minimumFractionDigits: number;\n maximumFractionDigits: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n useGrouping: boolean;\n }\n\n interface NumberFormat {\n format(value: number): string;\n resolvedOptions(): ResolvedNumberFormatOptions;\n }\n var NumberFormat: {\n new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\n };\n\n interface DateTimeFormatOptions {\n localeMatcher?: string;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n formatMatcher?: string;\n hour12?: boolean;\n timeZone?: string;\n }\n\n interface ResolvedDateTimeFormatOptions {\n locale: string;\n calendar: string;\n numberingSystem: string;\n timeZone: string;\n hour12?: boolean;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n }\n\n interface DateTimeFormat {\n format(date?: Date | number): string;\n resolvedOptions(): ResolvedDateTimeFormatOptions;\n }\n var DateTimeFormat: {\n new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\n };\n}\n\ninterface String {\n /**\n * Determines whether two strings are equivalent in the current or specified locale.\n * @param that String to compare to target string\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\n */\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\n}\n\ninterface Number {\n /**\n * Converts a number to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\n}\n\ninterface Date {\n /**\n * Converts a date and time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n /**\n * Converts a date to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n\n /**\n * Converts a time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n}\n\n\ndeclare type PropertyKey = string | number | symbol;\n\ninterface Array {\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;\n find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: T, start?: number, end?: number): this;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n}\n\ninterface ArrayConstructor {\n /**\n * Creates an array from an array-like object.\n * @param arrayLike An array-like object to convert to an array.\n */\n from(arrayLike: ArrayLike): T[];\n\n /**\n * Creates an array from an iterable object.\n * @param arrayLike An array-like object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[];\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: T[]): T[];\n}\n\ninterface DateConstructor {\n new (value: number | string | Date): Date;\n}\n\ninterface Function {\n /**\n * Returns the name of the function. Function names are read-only and can not be changed.\n */\n readonly name: string;\n}\n\ninterface Math {\n /**\n * Returns the number of leading zero bits in the 32-bit binary representation of a number.\n * @param x A numeric expression.\n */\n clz32(x: number): number;\n\n /**\n * Returns the result of 32-bit multiplication of two numbers.\n * @param x First number\n * @param y Second number\n */\n imul(x: number, y: number): number;\n\n /**\n * Returns the sign of the x, indicating whether x is positive, negative or zero.\n * @param x The numeric expression to test\n */\n sign(x: number): number;\n\n /**\n * Returns the base 10 logarithm of a number.\n * @param x A numeric expression.\n */\n log10(x: number): number;\n\n /**\n * Returns the base 2 logarithm of a number.\n * @param x A numeric expression.\n */\n log2(x: number): number;\n\n /**\n * Returns the natural logarithm of 1 + x.\n * @param x A numeric expression.\n */\n log1p(x: number): number;\n\n /**\n * Returns the result of (e^x - 1), which is an implementation-dependent approximation to\n * subtracting 1 from the exponential function of x (e raised to the power of x, where e\n * is the base of the natural logarithms).\n * @param x A numeric expression.\n */\n expm1(x: number): number;\n\n /**\n * Returns the hyperbolic cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cosh(x: number): number;\n\n /**\n * Returns the hyperbolic sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sinh(x: number): number;\n\n /**\n * Returns the hyperbolic tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tanh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n acosh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n asinh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n atanh(x: number): number;\n\n /**\n * Returns the square root of the sum of squares of its arguments.\n * @param values Values to compute the square root for.\n * If no arguments are passed, the result is +0.\n * If there is only one argument, the result is the absolute value.\n * If any argument is +Infinity or -Infinity, the result is +Infinity.\n * If any argument is NaN, the result is NaN.\n * If all arguments are either +0 or −0, the result is +0.\n */\n hypot(...values: number[]): number;\n\n /**\n * Returns the integral part of the a numeric expression, x, removing any fractional digits.\n * If x is already an integer, the result is x.\n * @param x A numeric expression.\n */\n trunc(x: number): number;\n\n /**\n * Returns the nearest single precision float representation of a number.\n * @param x A numeric expression.\n */\n fround(x: number): number;\n\n /**\n * Returns an implementation-dependent approximation to the cube root of number.\n * @param x A numeric expression.\n */\n cbrt(x: number): number;\n}\n\ninterface NumberConstructor {\n /**\n * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1\n * that is representable as a Number value, which is approximately:\n * 2.2204460492503130808472633361816 x 10‍−‍16.\n */\n readonly EPSILON: number;\n\n /**\n * Returns true if passed value is finite.\n * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a\n * number. Only finite values of the type number, result in true.\n * @param number A numeric value.\n */\n isFinite(number: number): boolean;\n\n /**\n * Returns true if the value passed is an integer, false otherwise.\n * @param number A numeric value.\n */\n isInteger(number: number): boolean;\n\n /**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a\n * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter\n * to a number. Only values of the type number, that are also NaN, result in true.\n * @param number A numeric value.\n */\n isNaN(number: number): boolean;\n\n /**\n * Returns true if the value passed is a safe integer.\n * @param number A numeric value.\n */\n isSafeInteger(number: number): boolean;\n\n /**\n * The value of the largest integer n such that n and n + 1 are both exactly representable as\n * a Number value.\n * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.\n */\n readonly MAX_SAFE_INTEGER: number;\n\n /**\n * The value of the smallest integer n such that n and n − 1 are both exactly representable as\n * a Number value.\n * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).\n */\n readonly MIN_SAFE_INTEGER: number;\n\n /**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\n parseFloat(string: string): number;\n\n /**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\n parseInt(string: string, radix?: number): number;\n}\n\ninterface Object {\n /**\n * Determines whether an object has a property with the specified name.\n * @param v A property name.\n */\n hasOwnProperty(v: PropertyKey): boolean;\n\n /**\n * Determines whether a specified property is enumerable.\n * @param v A property name.\n */\n propertyIsEnumerable(v: PropertyKey): boolean;\n}\n\ninterface ObjectConstructor {\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source The source object from which to copy properties.\n */\n assign(target: T, source: U): T & U;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source1 The first source object from which to copy properties.\n * @param source2 The second source object from which to copy properties.\n */\n assign(target: T, source1: U, source2: V): T & U & V;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source1 The first source object from which to copy properties.\n * @param source2 The second source object from which to copy properties.\n * @param source3 The third source object from which to copy properties.\n */\n assign(target: T, source1: U, source2: V, source3: W): T & U & V & W;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param sources One or more source objects from which to copy properties\n */\n assign(target: object, ...sources: any[]): any;\n\n /**\n * Returns an array of all symbol properties found directly on object o.\n * @param o Object to retrieve the symbols from.\n */\n getOwnPropertySymbols(o: any): symbol[];\n\n /**\n * Returns true if the values are the same value, false otherwise.\n * @param value1 The first value.\n * @param value2 The second value.\n */\n is(value1: any, value2: any): boolean;\n\n /**\n * Sets the prototype of a specified object o to object proto or null. Returns the object o.\n * @param o The object to change its prototype.\n * @param proto The value of the new prototype or null.\n */\n setPrototypeOf(o: any, proto: object | null): any;\n\n /**\n * Gets the own property descriptor of the specified object.\n * An own property descriptor is one that is defined directly on the object and is not\n * inherited from the object's prototype.\n * @param o Object that contains the property.\n * @param p Name of the property.\n */\n getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor | undefined;\n\n /**\n * Adds a property to an object, or modifies attributes of an existing property.\n * @param o Object on which to add or modify the property. This can be a native JavaScript\n * object (that is, a user-defined object or a built in object) or a DOM object.\n * @param p The property name.\n * @param attributes Descriptor for the property. It can be for a data property or an accessor\n * property.\n */\n defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;\n}\n\ninterface ReadonlyArray {\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined;\n find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number;\n}\n\ninterface RegExp {\n /**\n * Returns a string indicating the flags of the regular expression in question. This field is read-only.\n * The characters in this string are sequenced and concatenated in the following order:\n *\n * - \"g\" for global\n * - \"i\" for ignoreCase\n * - \"m\" for multiline\n * - \"u\" for unicode\n * - \"y\" for sticky\n *\n * If no flags are set, the value is the empty string.\n */\n readonly flags: string;\n\n /**\n * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular\n * expression. Default is false. Read-only.\n */\n readonly sticky: boolean;\n\n /**\n * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular\n * expression. Default is false. Read-only.\n */\n readonly unicode: boolean;\n}\n\ninterface RegExpConstructor {\n new (pattern: RegExp, flags?: string): RegExp;\n (pattern: RegExp, flags?: string): RegExp;\n}\n\ninterface String {\n /**\n * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point\n * value of the UTF-16 encoded code point starting at the string element at position pos in\n * the String resulting from converting this object to a String.\n * If there is no element at that position, the result is undefined.\n * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.\n */\n codePointAt(pos: number): number | undefined;\n\n /**\n * Returns true if searchString appears as a substring of the result of converting this\n * object to a String, at one or more positions that are\n * greater than or equal to position; otherwise, returns false.\n * @param searchString search string\n * @param position If position is undefined, 0 is assumed, so as to search all of the String.\n */\n includes(searchString: string, position?: number): boolean;\n\n /**\n * Returns true if the sequence of elements of searchString converted to a String is the\n * same as the corresponding elements of this object (converted to a String) starting at\n * endPosition – length(this). Otherwise returns false.\n */\n endsWith(searchString: string, endPosition?: number): boolean;\n\n /**\n * Returns the String value result of normalizing the string into the normalization form\n * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.\n * @param form Applicable values: \"NFC\", \"NFD\", \"NFKC\", or \"NFKD\", If not specified default\n * is \"NFC\"\n */\n normalize(form: \"NFC\" | \"NFD\" | \"NFKC\" | \"NFKD\"): string;\n\n /**\n * Returns the String value result of normalizing the string into the normalization form\n * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.\n * @param form Applicable values: \"NFC\", \"NFD\", \"NFKC\", or \"NFKD\", If not specified default\n * is \"NFC\"\n */\n normalize(form?: string): string;\n\n /**\n * Returns a String value that is made from count copies appended together. If count is 0,\n * the empty string is returned.\n * @param count number of copies to append\n */\n repeat(count: number): string;\n\n /**\n * Returns true if the sequence of elements of searchString converted to a String is the\n * same as the corresponding elements of this object (converted to a String) starting at\n * position. Otherwise returns false.\n */\n startsWith(searchString: string, position?: number): boolean;\n\n /**\n * Returns an HTML anchor element and sets the name attribute to the text value\n * @param name\n */\n anchor(name: string): string;\n\n /** Returns a HTML element */\n big(): string;\n\n /** Returns a HTML element */\n blink(): string;\n\n /** Returns a HTML element */\n bold(): string;\n\n /** Returns a HTML element */\n fixed(): string;\n\n /** Returns a HTML element and sets the color attribute value */\n fontcolor(color: string): string;\n\n /** Returns a HTML element and sets the size attribute value */\n fontsize(size: number): string;\n\n /** Returns a HTML element and sets the size attribute value */\n fontsize(size: string): string;\n\n /** Returns an HTML element */\n italics(): string;\n\n /** Returns an HTML element and sets the href attribute value */\n link(url: string): string;\n\n /** Returns a HTML element */\n small(): string;\n\n /** Returns a HTML element */\n strike(): string;\n\n /** Returns a HTML element */\n sub(): string;\n\n /** Returns a HTML element */\n sup(): string;\n}\n\ninterface StringConstructor {\n /**\n * Return the String value whose elements are, in order, the elements in the List elements.\n * If length is 0, the empty string is returned.\n */\n fromCodePoint(...codePoints: number[]): string;\n\n /**\n * String.raw is intended for use as a tag function of a Tagged Template String. When called\n * as such the first argument will be a well formed template call site object and the rest\n * parameter will contain the substitution values.\n * @param template A well-formed template string call site representation.\n * @param substitutions A set of substitution values.\n */\n raw(template: TemplateStringsArray, ...substitutions: any[]): string;\n}\n\n\ninterface Map {\n clear(): void;\n delete(key: K): boolean;\n forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void;\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): this;\n readonly size: number;\n}\n\ninterface MapConstructor {\n new (): Map;\n new (entries?: ReadonlyArray<[K, V]>): Map;\n readonly prototype: Map;\n}\ndeclare var Map: MapConstructor;\n\ninterface ReadonlyMap {\n forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void;\n get(key: K): V | undefined;\n has(key: K): boolean;\n readonly size: number;\n}\n\ninterface WeakMap {\n delete(key: K): boolean;\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): this;\n}\n\ninterface WeakMapConstructor {\n new (): WeakMap;\n new (entries?: ReadonlyArray<[K, V]>): WeakMap;\n readonly prototype: WeakMap;\n}\ndeclare var WeakMap: WeakMapConstructor;\n\ninterface Set {\n add(value: T): this;\n clear(): void;\n delete(value: T): boolean;\n forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void;\n has(value: T): boolean;\n readonly size: number;\n}\n\ninterface SetConstructor {\n new (): Set;\n new (values?: ReadonlyArray): Set;\n readonly prototype: Set;\n}\ndeclare var Set: SetConstructor;\n\ninterface ReadonlySet {\n forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void;\n has(value: T): boolean;\n readonly size: number;\n}\n\ninterface WeakSet {\n add(value: T): this;\n delete(value: T): boolean;\n has(value: T): boolean;\n}\n\ninterface WeakSetConstructor {\n new (): WeakSet;\n new (values?: ReadonlyArray): WeakSet;\n readonly prototype: WeakSet;\n}\ndeclare var WeakSet: WeakSetConstructor;\n\n\ninterface Generator extends Iterator { }\n\ninterface GeneratorFunction {\n /**\n * Creates a new Generator object.\n * @param args A list of arguments the function accepts.\n */\n new (...args: any[]): Generator;\n /**\n * Creates a new Generator object.\n * @param args A list of arguments the function accepts.\n */\n (...args: any[]): Generator;\n /**\n * The length of the arguments.\n */\n readonly length: number;\n /**\n * Returns the name of the function.\n */\n readonly name: string;\n /**\n * A reference to the prototype.\n */\n readonly prototype: Generator;\n}\n\ninterface GeneratorFunctionConstructor {\n /**\n * Creates a new Generator function.\n * @param args A list of arguments the function accepts.\n */\n new (...args: string[]): GeneratorFunction;\n /**\n * Creates a new Generator function.\n * @param args A list of arguments the function accepts.\n */\n (...args: string[]): GeneratorFunction;\n /**\n * The length of the arguments.\n */\n readonly length: number;\n /**\n * Returns the name of the function.\n */\n readonly name: string;\n /**\n * A reference to the prototype.\n */\n readonly prototype: GeneratorFunction;\n}\n\n\n/// \n\ninterface SymbolConstructor {\n /**\n * A method that returns the default iterator for an object. Called by the semantics of the\n * for-of statement.\n */\n readonly iterator: symbol;\n}\n\ninterface IteratorResult {\n done: boolean;\n value: T;\n}\n\ninterface Iterator {\n next(value?: any): IteratorResult;\n return?(value?: any): IteratorResult;\n throw?(e?: any): IteratorResult;\n}\n\ninterface Iterable {\n [Symbol.iterator](): Iterator;\n}\n\ninterface IterableIterator extends Iterator {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Array {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, T]>;\n\n /**\n * Returns an iterable of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface ArrayConstructor {\n /**\n * Creates an array from an iterable object.\n * @param iterable An iterable object to convert to an array.\n */\n from(iterable: Iterable | ArrayLike): T[];\n\n /**\n * Creates an array from an iterable object.\n * @param iterable An iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[];\n}\n\ninterface ReadonlyArray {\n /** Iterator of values in the array. */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, T]>;\n\n /**\n * Returns an iterable of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface IArguments {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Map {\n /** Returns an iterable of entries in the map. */\n [Symbol.iterator](): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the map.\n */\n entries(): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of keys in the map\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the map\n */\n values(): IterableIterator;\n}\n\ninterface ReadonlyMap {\n /** Returns an iterable of entries in the map. */\n [Symbol.iterator](): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the map.\n */\n entries(): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of keys in the map\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the map\n */\n values(): IterableIterator;\n}\n\ninterface MapConstructor {\n new (iterable: Iterable<[K, V]>): Map;\n}\n\ninterface WeakMap { }\n\ninterface WeakMapConstructor {\n new (iterable: Iterable<[K, V]>): WeakMap;\n}\n\ninterface Set {\n /** Iterates over values in the set. */\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an iterable of [v,v] pairs for every value `v` in the set.\n */\n entries(): IterableIterator<[T, T]>;\n /**\n * Despite its name, returns an iterable of the values in the set,\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the set.\n */\n values(): IterableIterator;\n}\n\ninterface ReadonlySet {\n /** Iterates over values in the set. */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of [v,v] pairs for every value `v` in the set.\n */\n entries(): IterableIterator<[T, T]>;\n\n /**\n * Despite its name, returns an iterable of the values in the set,\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the set.\n */\n values(): IterableIterator;\n}\n\ninterface SetConstructor {\n new (iterable: Iterable): Set;\n}\n\ninterface WeakSet { }\n\ninterface WeakSetConstructor {\n new (iterable: Iterable): WeakSet;\n}\n\ninterface Promise { }\n\ninterface PromiseConstructor {\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: Iterable>): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: Iterable>): Promise;\n}\n\ndeclare namespace Reflect {\n function enumerate(target: object): IterableIterator;\n}\n\ninterface String {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Int8Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int8ArrayConstructor {\n new (elements: Iterable): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n}\n\ninterface Uint8Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint8ArrayConstructor {\n new (elements: Iterable): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n}\n\ninterface Uint8ClampedArray {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint8ClampedArrayConstructor {\n new (elements: Iterable): Uint8ClampedArray;\n\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\n\ninterface Int16Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int16ArrayConstructor {\n new (elements: Iterable): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n}\n\ninterface Uint16Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint16ArrayConstructor {\n new (elements: Iterable): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n}\n\ninterface Int32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int32ArrayConstructor {\n new (elements: Iterable): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n}\n\ninterface Uint32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint32ArrayConstructor {\n new (elements: Iterable): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n}\n\ninterface Float32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Float32ArrayConstructor {\n new (elements: Iterable): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n}\n\ninterface Float64Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Float64ArrayConstructor {\n new (elements: Iterable): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n}\n\n\ninterface PromiseConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Promise;\n\n /**\n * Creates a new Promise.\n * @param executor A callback used to initialize the promise. This callback is passed two arguments:\n * a resolve callback used resolve the promise with a value or the result of another promise,\n * and a reject callback used to reject the promise with a provided reason or error.\n */\n new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: (T | PromiseLike)[]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: (T | PromiseLike)[]): Promise;\n\n /**\n * Creates a new rejected promise for the provided reason.\n * @param reason The reason the promise was rejected.\n * @returns A new rejected Promise.\n */\n reject(reason: any): Promise;\n\n /**\n * Creates a new rejected promise for the provided reason.\n * @param reason The reason the promise was rejected.\n * @returns A new rejected Promise.\n */\n reject(reason: any): Promise;\n\n /**\n * Creates a new resolved promise for the provided value.\n * @param value A promise.\n * @returns A promise whose internal state matches the provided promise.\n */\n resolve(value: T | PromiseLike): Promise;\n\n /**\n * Creates a new resolved promise .\n * @returns A resolved promise.\n */\n resolve(): Promise;\n}\n\ndeclare var Promise: PromiseConstructor;\n\ninterface ProxyHandler {\n getPrototypeOf? (target: T): object | null;\n setPrototypeOf? (target: T, v: any): boolean;\n isExtensible? (target: T): boolean;\n preventExtensions? (target: T): boolean;\n getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined;\n has? (target: T, p: PropertyKey): boolean;\n get? (target: T, p: PropertyKey, receiver: any): any;\n set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;\n deleteProperty? (target: T, p: PropertyKey): boolean;\n defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;\n enumerate? (target: T): PropertyKey[];\n ownKeys? (target: T): PropertyKey[];\n apply? (target: T, thisArg: any, argArray?: any): any;\n construct? (target: T, argArray: any, newTarget?: any): object;\n}\n\ninterface ProxyConstructor {\n revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; };\n new (target: T, handler: ProxyHandler): T;\n}\ndeclare var Proxy: ProxyConstructor;\n\n\ndeclare namespace Reflect {\n function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any;\n function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any;\n function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;\n function deleteProperty(target: object, propertyKey: PropertyKey): boolean;\n function get(target: object, propertyKey: PropertyKey, receiver?: any): any;\n function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined;\n function getPrototypeOf(target: object): object;\n function has(target: object, propertyKey: PropertyKey): boolean;\n function isExtensible(target: object): boolean;\n function ownKeys(target: object): PropertyKey[];\n function preventExtensions(target: object): boolean;\n function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean;\n function setPrototypeOf(target: object, proto: any): boolean;\n}\n\n\ninterface Symbol {\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): symbol;\n}\n\ninterface SymbolConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Symbol;\n\n /**\n * Returns a new unique Symbol value.\n * @param description Description of the new Symbol object.\n */\n (description?: string | number): symbol;\n\n /**\n * Returns a Symbol object from the global symbol registry matching the given key if found.\n * Otherwise, returns a new symbol with this key.\n * @param key key to search for.\n */\n for(key: string): symbol;\n\n /**\n * Returns a key from the global symbol registry matching the given Symbol if found.\n * Otherwise, returns a undefined.\n * @param sym Symbol to find the key for.\n */\n keyFor(sym: symbol): string | undefined;\n}\n\ndeclare var Symbol: SymbolConstructor;\n\n/// \n\ninterface SymbolConstructor {\n /**\n * A method that determines if a constructor object recognizes an object as one of the\n * constructor’s instances. Called by the semantics of the instanceof operator.\n */\n readonly hasInstance: symbol;\n\n /**\n * A Boolean value that if true indicates that an object should flatten to its array elements\n * by Array.prototype.concat.\n */\n readonly isConcatSpreadable: symbol;\n\n /**\n * A regular expression method that matches the regular expression against a string. Called\n * by the String.prototype.match method.\n */\n readonly match: symbol;\n\n /**\n * A regular expression method that replaces matched substrings of a string. Called by the\n * String.prototype.replace method.\n */\n readonly replace: symbol;\n\n /**\n * A regular expression method that returns the index within a string that matches the\n * regular expression. Called by the String.prototype.search method.\n */\n readonly search: symbol;\n\n /**\n * A function valued property that is the constructor function that is used to create\n * derived objects.\n */\n readonly species: symbol;\n\n /**\n * A regular expression method that splits a string at the indices that match the regular\n * expression. Called by the String.prototype.split method.\n */\n readonly split: symbol;\n\n /**\n * A method that converts an object to a corresponding primitive value.\n * Called by the ToPrimitive abstract operation.\n */\n readonly toPrimitive: symbol;\n\n /**\n * A String value that is used in the creation of the default string description of an object.\n * Called by the built-in method Object.prototype.toString.\n */\n readonly toStringTag: symbol;\n\n /**\n * An Object whose own property names are property names that are excluded from the 'with'\n * environment bindings of the associated objects.\n */\n readonly unscopables: symbol;\n}\n\ninterface Symbol {\n readonly [Symbol.toStringTag]: \"Symbol\";\n}\n\ninterface Array {\n /**\n * Returns an object whose properties have the value 'true'\n * when they will be absent when used in a 'with' statement.\n */\n [Symbol.unscopables](): {\n copyWithin: boolean;\n entries: boolean;\n fill: boolean;\n find: boolean;\n findIndex: boolean;\n keys: boolean;\n values: boolean;\n };\n}\n\ninterface Date {\n /**\n * Converts a Date object to a string.\n */\n [Symbol.toPrimitive](hint: \"default\"): string;\n /**\n * Converts a Date object to a string.\n */\n [Symbol.toPrimitive](hint: \"string\"): string;\n /**\n * Converts a Date object to a number.\n */\n [Symbol.toPrimitive](hint: \"number\"): number;\n /**\n * Converts a Date object to a string or number.\n *\n * @param hint The strings \"number\", \"string\", or \"default\" to specify what primitive to return.\n *\n * @throws {TypeError} If 'hint' was given something other than \"number\", \"string\", or \"default\".\n * @returns A number if 'hint' was \"number\", a string if 'hint' was \"string\" or \"default\".\n */\n [Symbol.toPrimitive](hint: string): string | number;\n}\n\ninterface Map {\n readonly [Symbol.toStringTag]: \"Map\";\n}\n\ninterface WeakMap {\n readonly [Symbol.toStringTag]: \"WeakMap\";\n}\n\ninterface Set {\n readonly [Symbol.toStringTag]: \"Set\";\n}\n\ninterface WeakSet {\n readonly [Symbol.toStringTag]: \"WeakSet\";\n}\n\ninterface JSON {\n readonly [Symbol.toStringTag]: \"JSON\";\n}\n\ninterface Function {\n /**\n * Determines whether the given value inherits from this function if this function was used\n * as a constructor function.\n *\n * A constructor function can control which objects are recognized as its instances by\n * 'instanceof' by overriding this method.\n */\n [Symbol.hasInstance](value: any): boolean;\n}\n\ninterface GeneratorFunction {\n readonly [Symbol.toStringTag]: \"GeneratorFunction\";\n}\n\ninterface Math {\n readonly [Symbol.toStringTag]: \"Math\";\n}\n\ninterface Promise {\n readonly [Symbol.toStringTag]: \"Promise\";\n}\n\ninterface PromiseConstructor {\n readonly [Symbol.species]: PromiseConstructor;\n}\n\ninterface RegExp {\n /**\n * Matches a string with this regular expression, and returns an array containing the results of\n * that search.\n * @param string A string to search within.\n */\n [Symbol.match](string: string): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using this regular expression.\n * @param string A String object or string literal whose contents matching against\n * this regular expression will be replaced\n * @param replaceValue A String object or string literal containing the text to replace for every\n * successful match of this regular expression.\n */\n [Symbol.replace](string: string, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using this regular expression.\n * @param string A String object or string literal whose contents matching against\n * this regular expression will be replaced\n * @param replacer A function that returns the replacement text.\n */\n [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the position beginning first substring match in a regular expression search\n * using this regular expression.\n *\n * @param string The string to search within.\n */\n [Symbol.search](string: string): number;\n\n /**\n * Returns an array of substrings that were delimited by strings in the original input that\n * match against this regular expression.\n *\n * If the regular expression contains capturing parentheses, then each time this\n * regular expression matches, the results (including any undefined results) of the\n * capturing parentheses are spliced.\n *\n * @param string string value to split\n * @param limit if not undefined, the output array is truncated so that it contains no more\n * than 'limit' elements.\n */\n [Symbol.split](string: string, limit?: number): string[];\n}\n\ninterface RegExpConstructor {\n readonly [Symbol.species]: RegExpConstructor;\n}\n\ninterface String {\n /**\n * Matches a string an object that supports being matched against, and returns an array containing the results of that search.\n * @param matcher An object that supports being matched against.\n */\n match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using an object that supports replacement within a string.\n * @param searchValue A object can search for and replace matches within a string.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using an object that supports replacement within a string.\n * @param searchValue A object can search for and replace matches within a string.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param searcher An object which supports searching within a string.\n */\n search(searcher: { [Symbol.search](string: string): number; }): number;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param splitter An object that can split a string.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];\n}\n\ninterface ArrayBuffer {\n readonly [Symbol.toStringTag]: \"ArrayBuffer\";\n}\n\ninterface DataView {\n readonly [Symbol.toStringTag]: \"DataView\";\n}\n\ninterface Int8Array {\n readonly [Symbol.toStringTag]: \"Int8Array\";\n}\n\ninterface Uint8Array {\n readonly [Symbol.toStringTag]: \"UInt8Array\";\n}\n\ninterface Uint8ClampedArray {\n readonly [Symbol.toStringTag]: \"Uint8ClampedArray\";\n}\n\ninterface Int16Array {\n readonly [Symbol.toStringTag]: \"Int16Array\";\n}\n\ninterface Uint16Array {\n readonly [Symbol.toStringTag]: \"Uint16Array\";\n}\n\ninterface Int32Array {\n readonly [Symbol.toStringTag]: \"Int32Array\";\n}\n\ninterface Uint32Array {\n readonly [Symbol.toStringTag]: \"Uint32Array\";\n}\n\ninterface Float32Array {\n readonly [Symbol.toStringTag]: \"Float32Array\";\n}\n\ninterface Float64Array {\n readonly [Symbol.toStringTag]: \"Float64Array\";\n}\n\ninterface ArrayConstructor {\n readonly [Symbol.species]: ArrayConstructor;\n}\ninterface MapConstructor {\n readonly [Symbol.species]: MapConstructor;\n}\ninterface SetConstructor {\n readonly [Symbol.species]: SetConstructor;\n}\ninterface ArrayBufferConstructor {\n readonly [Symbol.species]: ArrayBufferConstructor;\n}\n\n/////////////////////////////\n/// DOM APIs\n/////////////////////////////\n\ninterface Account {\n displayName: string;\n id: string;\n imageURL?: string;\n name?: string;\n rpDisplayName: string;\n}\n\ninterface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\ninterface AesCbcParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface AesCtrParams extends Algorithm {\n counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n length: number;\n}\n\ninterface AesDerivedKeyParams extends Algorithm {\n length: number;\n}\n\ninterface AesGcmParams extends Algorithm {\n additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n tagLength?: number;\n}\n\ninterface AesKeyAlgorithm extends KeyAlgorithm {\n length: number;\n}\n\ninterface AesKeyGenParams extends Algorithm {\n length: number;\n}\n\ninterface Algorithm {\n name: string;\n}\n\ninterface AnalyserOptions extends AudioNodeOptions {\n fftSize?: number;\n maxDecibels?: number;\n minDecibels?: number;\n smoothingTimeConstant?: number;\n}\n\ninterface AnimationEventInit extends EventInit {\n animationName?: string;\n elapsedTime?: number;\n}\n\ninterface AssertionOptions {\n allowList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface AudioBufferOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface AudioBufferSourceOptions {\n buffer?: AudioBuffer | null;\n detune?: number;\n loop?: boolean;\n loopEnd?: number;\n loopStart?: number;\n playbackRate?: number;\n}\n\ninterface AudioContextInfo {\n currentTime?: number;\n sampleRate?: number;\n}\n\ninterface AudioContextOptions {\n latencyHint?: AudioContextLatencyCategory | number;\n sampleRate?: number;\n}\n\ninterface AudioNodeOptions {\n channelCount?: number;\n channelCountMode?: ChannelCountMode;\n channelInterpretation?: ChannelInterpretation;\n}\n\ninterface AudioParamDescriptor {\n defaultValue?: number;\n maxValue?: number;\n minValue?: number;\n name?: string;\n}\n\ninterface AudioProcessingEventInit extends EventInit {\n inputBuffer: AudioBuffer;\n outputBuffer: AudioBuffer;\n playbackTime: number;\n}\n\ninterface AudioTimestamp {\n contextTime?: number;\n performanceTime?: number;\n}\n\ninterface BiquadFilterOptions extends AudioNodeOptions {\n Q?: number;\n detune?: number;\n frequency?: number;\n gain?: number;\n type?: BiquadFilterType;\n}\n\ninterface ByteLengthChunk {\n byteLength?: number;\n}\n\ninterface CacheQueryOptions {\n cacheName?: string;\n ignoreMethod?: boolean;\n ignoreSearch?: boolean;\n ignoreVary?: boolean;\n}\n\ninterface ChannelMergerOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n}\n\ninterface ChannelSplitterOptions extends AudioNodeOptions {\n numberOfOutputs?: number;\n}\n\ninterface ClientData {\n challenge: string;\n extensions?: WebAuthnExtensions;\n hashAlg: string | Algorithm;\n origin: string;\n rpId: string;\n tokenBinding?: string;\n}\n\ninterface ClientQueryOptions {\n includeReserved?: boolean;\n includeUncontrolled?: boolean;\n type?: ClientTypes;\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number;\n reason?: string;\n wasClean?: boolean;\n}\n\ninterface CompositionEventInit extends UIEventInit {\n data?: string;\n}\n\ninterface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface ConstantSourceOptions {\n offset?: number;\n}\n\ninterface ConstrainBooleanParameters {\n exact?: boolean;\n ideal?: boolean;\n}\n\ninterface ConstrainDOMStringParameters {\n exact?: string | string[];\n ideal?: string | string[];\n}\n\ninterface ConstrainDoubleRange extends DoubleRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainLongRange extends LongRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainVideoFacingModeParameters {\n exact?: VideoFacingModeEnum | VideoFacingModeEnum[];\n ideal?: VideoFacingModeEnum | VideoFacingModeEnum[];\n}\n\ninterface ConvolverOptions extends AudioNodeOptions {\n buffer?: AudioBuffer | null;\n disableNormalization?: boolean;\n}\n\ninterface CustomEventInit extends EventInit {\n detail?: T;\n}\n\ninterface DOMRectInit {\n height?: number;\n width?: number;\n x?: number;\n y?: number;\n}\n\ninterface DelayOptions extends AudioNodeOptions {\n delayTime?: number;\n maxDelayTime?: number;\n}\n\ninterface DeviceAccelerationDict {\n x?: number | null;\n y?: number | null;\n z?: number | null;\n}\n\ninterface DeviceLightEventInit extends EventInit {\n value?: number;\n}\n\ninterface DeviceMotionEventInit extends EventInit {\n acceleration?: DeviceAccelerationDict | null;\n accelerationIncludingGravity?: DeviceAccelerationDict | null;\n interval?: number | null;\n rotationRate?: DeviceRotationRateDict | null;\n}\n\ninterface DeviceOrientationEventInit extends EventInit {\n absolute?: boolean;\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DeviceRotationRateDict {\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DoubleRange {\n max?: number;\n min?: number;\n}\n\ninterface DynamicsCompressorOptions extends AudioNodeOptions {\n attack?: number;\n knee?: number;\n ratio?: number;\n release?: number;\n threshold?: number;\n}\n\ninterface EcKeyAlgorithm extends KeyAlgorithm {\n namedCurve: string;\n}\n\ninterface EcKeyGenParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcKeyImportParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcdhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface EcdsaParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface ErrorEventInit extends EventInit {\n colno?: number;\n error?: any;\n filename?: string;\n lineno?: number;\n message?: string;\n}\n\ninterface EventInit {\n bubbles?: boolean;\n cancelable?: boolean;\n scoped?: boolean;\n}\n\ninterface EventListenerOptions {\n capture?: boolean;\n}\n\ninterface EventModifierInit extends UIEventInit {\n altKey?: boolean;\n ctrlKey?: boolean;\n metaKey?: boolean;\n modifierAltGraph?: boolean;\n modifierCapsLock?: boolean;\n modifierFn?: boolean;\n modifierFnLock?: boolean;\n modifierHyper?: boolean;\n modifierNumLock?: boolean;\n modifierOS?: boolean;\n modifierScrollLock?: boolean;\n modifierSuper?: boolean;\n modifierSymbol?: boolean;\n modifierSymbolLock?: boolean;\n shiftKey?: boolean;\n}\n\ninterface ExceptionInformation {\n domain?: string | null;\n}\n\ninterface ExtendableEventInit extends EventInit {\n}\n\ninterface ExtendableMessageEventInit extends ExtendableEventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: object | ServiceWorker | MessagePort | null;\n}\n\ninterface FetchEventInit extends ExtendableEventInit {\n clientId?: string;\n request: Request;\n reservedClientId?: string;\n targetClientId?: string;\n}\n\ninterface FocusEventInit extends UIEventInit {\n relatedTarget?: EventTarget | null;\n}\n\ninterface FocusNavigationEventInit extends EventInit {\n navigationReason?: string | null;\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface FocusNavigationOrigin {\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface GainOptions extends AudioNodeOptions {\n gain?: number;\n}\n\ninterface GamepadEventInit extends EventInit {\n gamepad?: Gamepad;\n}\n\ninterface GetNotificationOptions {\n tag?: string;\n}\n\ninterface HashChangeEventInit extends EventInit {\n newURL?: string;\n oldURL?: string;\n}\n\ninterface HkdfParams extends Algorithm {\n hash: string | Algorithm;\n info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface HmacImportParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface HmacKeyAlgorithm extends KeyAlgorithm {\n hash: KeyAlgorithm;\n length: number;\n}\n\ninterface HmacKeyGenParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface IDBIndexParameters {\n multiEntry?: boolean;\n unique?: boolean;\n}\n\ninterface IDBObjectStoreParameters {\n autoIncrement?: boolean;\n keyPath?: string | string[];\n}\n\ninterface IIRFilterOptions extends AudioNodeOptions {\n feedback: number[];\n feedforward: number[];\n}\n\ninterface IntersectionObserverEntryInit {\n boundingClientRect: DOMRectInit;\n intersectionRect: DOMRectInit;\n isIntersecting: boolean;\n rootBounds: DOMRectInit;\n target: Element;\n time: number;\n}\n\ninterface IntersectionObserverInit {\n root?: Element | null;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\ninterface JsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\ninterface KeyAlgorithm {\n name: string;\n}\n\ninterface KeyboardEventInit extends EventModifierInit {\n code?: string;\n key?: string;\n location?: number;\n repeat?: boolean;\n}\n\ninterface LongRange {\n max?: number;\n min?: number;\n}\n\ninterface MSAccountInfo {\n accountImageUri?: string;\n accountName?: string;\n rpDisplayName: string;\n userDisplayName: string;\n userId?: string;\n}\n\ninterface MSAudioLocalClientEvent extends MSLocalClientEventBase {\n cpuInsufficientEventRatio?: number;\n deviceCaptureNotFunctioningEventRatio?: number;\n deviceClippingEventRatio?: number;\n deviceEchoEventRatio?: number;\n deviceGlitchesEventRatio?: number;\n deviceHalfDuplexAECEventRatio?: number;\n deviceHowlingEventCount?: number;\n deviceLowSNREventRatio?: number;\n deviceLowSpeechLevelEventRatio?: number;\n deviceMultipleEndpointsEventCount?: number;\n deviceNearEndToEchoRatioEventRatio?: number;\n deviceRenderMuteEventRatio?: number;\n deviceRenderNotFunctioningEventRatio?: number;\n deviceRenderZeroVolumeEventRatio?: number;\n networkDelayEventRatio?: number;\n networkSendQualityEventRatio?: number;\n}\n\ninterface MSAudioRecvPayload extends MSPayloadBase {\n burstLossLength1?: number;\n burstLossLength2?: number;\n burstLossLength3?: number;\n burstLossLength4?: number;\n burstLossLength5?: number;\n burstLossLength6?: number;\n burstLossLength7?: number;\n burstLossLength8OrHigher?: number;\n fecRecvDistance1?: number;\n fecRecvDistance2?: number;\n fecRecvDistance3?: number;\n packetReorderDepthAvg?: number;\n packetReorderDepthMax?: number;\n packetReorderRatio?: number;\n ratioCompressedSamplesAvg?: number;\n ratioConcealedSamplesAvg?: number;\n ratioStretchedSamplesAvg?: number;\n samplingRate?: number;\n signal?: MSAudioRecvSignal;\n}\n\ninterface MSAudioRecvSignal {\n initialSignalLevelRMS?: number;\n recvNoiseLevelCh1?: number;\n recvSignalLevelCh1?: number;\n renderLoopbackSignalLevel?: number;\n renderNoiseLevel?: number;\n renderSignalLevel?: number;\n}\n\ninterface MSAudioSendPayload extends MSPayloadBase {\n audioFECUsed?: boolean;\n samplingRate?: number;\n sendMutePercent?: number;\n signal?: MSAudioSendSignal;\n}\n\ninterface MSAudioSendSignal {\n noiseLevel?: number;\n sendNoiseLevelCh1?: number;\n sendSignalLevelCh1?: number;\n}\n\ninterface MSConnectivity {\n iceType?: MSIceType;\n iceWarningFlags?: MSIceWarningFlags;\n relayAddress?: MSRelayAddress;\n}\n\ninterface MSCredentialFilter {\n accept?: MSCredentialSpec[];\n}\n\ninterface MSCredentialParameters {\n type?: MSCredentialType;\n}\n\ninterface MSCredentialSpec {\n id?: string;\n type: MSCredentialType;\n}\n\ninterface MSDCCEventInit extends EventInit {\n maxFr?: number;\n maxFs?: number;\n}\n\ninterface MSDSHEventInit extends EventInit {\n sources?: number[];\n timestamp?: number;\n}\n\ninterface MSDelay {\n roundTrip?: number;\n roundTripMax?: number;\n}\n\ninterface MSDescription extends RTCStats {\n connectivity?: MSConnectivity;\n deviceDevName?: string;\n localAddr?: MSIPAddressInfo;\n networkconnectivity?: MSNetworkConnectivityInfo;\n reflexiveLocalIPAddr?: MSIPAddressInfo;\n remoteAddr?: MSIPAddressInfo;\n transport?: RTCIceProtocol;\n}\n\ninterface MSFIDOCredentialParameters extends MSCredentialParameters {\n algorithm?: string | Algorithm;\n authenticators?: string[];\n}\n\ninterface MSIPAddressInfo {\n ipAddr?: string;\n manufacturerMacAddrMask?: string;\n port?: number;\n}\n\ninterface MSIceWarningFlags {\n allocationMessageIntegrityFailed?: boolean;\n alternateServerReceived?: boolean;\n connCheckMessageIntegrityFailed?: boolean;\n connCheckOtherError?: boolean;\n fipsAllocationFailure?: boolean;\n multipleRelayServersAttempted?: boolean;\n noRelayServersConfigured?: boolean;\n portRangeExhausted?: boolean;\n pseudoTLSFailure?: boolean;\n tcpNatConnectivityFailed?: boolean;\n tcpRelayConnectivityFailed?: boolean;\n turnAuthUnknownUsernameError?: boolean;\n turnTcpAllocateFailed?: boolean;\n turnTcpSendFailed?: boolean;\n turnTcpTimedOut?: boolean;\n turnTurnTcpConnectivityFailed?: boolean;\n turnUdpAllocateFailed?: boolean;\n turnUdpSendFailed?: boolean;\n udpLocalConnectivityFailed?: boolean;\n udpNatConnectivityFailed?: boolean;\n udpRelayConnectivityFailed?: boolean;\n useCandidateChecksFailed?: boolean;\n}\n\ninterface MSJitter {\n interArrival?: number;\n interArrivalMax?: number;\n interArrivalSD?: number;\n}\n\ninterface MSLocalClientEventBase extends RTCStats {\n networkBandwidthLowEventRatio?: number;\n networkReceiveQualityEventRatio?: number;\n}\n\ninterface MSNetwork extends RTCStats {\n delay?: MSDelay;\n jitter?: MSJitter;\n packetLoss?: MSPacketLoss;\n utilization?: MSUtilization;\n}\n\ninterface MSNetworkConnectivityInfo {\n linkspeed?: number;\n networkConnectionDetails?: string;\n vpn?: boolean;\n}\n\ninterface MSNetworkInterfaceType {\n interfaceTypeEthernet?: boolean;\n interfaceTypePPP?: boolean;\n interfaceTypeTunnel?: boolean;\n interfaceTypeWWAN?: boolean;\n interfaceTypeWireless?: boolean;\n}\n\ninterface MSOutboundNetwork extends MSNetwork {\n appliedBandwidthLimit?: number;\n}\n\ninterface MSPacketLoss {\n lossRate?: number;\n lossRateMax?: number;\n}\n\ninterface MSPayloadBase extends RTCStats {\n payloadDescription?: string;\n}\n\ninterface MSPortRange {\n max?: number;\n min?: number;\n}\n\ninterface MSRelayAddress {\n port?: number;\n relayAddress?: string;\n}\n\ninterface MSSignatureParameters {\n userPrompt?: string;\n}\n\ninterface MSTransportDiagnosticsStats extends RTCStats {\n allocationTimeInMs?: number;\n baseAddress?: string;\n baseInterface?: MSNetworkInterfaceType;\n iceRole?: RTCIceRole;\n iceWarningFlags?: MSIceWarningFlags;\n interfaces?: MSNetworkInterfaceType;\n localAddrType?: MSIceAddrType;\n localAddress?: string;\n localInterface?: MSNetworkInterfaceType;\n localMR?: string;\n localMRTCPPort?: number;\n localSite?: string;\n msRtcEngineVersion?: string;\n networkName?: string;\n numConsentReqReceived?: number;\n numConsentReqSent?: number;\n numConsentRespReceived?: number;\n numConsentRespSent?: number;\n portRangeMax?: number;\n portRangeMin?: number;\n protocol?: RTCIceProtocol;\n remoteAddrType?: MSIceAddrType;\n remoteAddress?: string;\n remoteMR?: string;\n remoteMRTCPPort?: number;\n remoteSite?: string;\n rtpRtcpMux?: boolean;\n stunVer?: number;\n}\n\ninterface MSUtilization {\n bandwidthEstimation?: number;\n bandwidthEstimationAvg?: number;\n bandwidthEstimationMax?: number;\n bandwidthEstimationMin?: number;\n bandwidthEstimationStdDev?: number;\n packets?: number;\n}\n\ninterface MSVideoPayload extends MSPayloadBase {\n durationSeconds?: number;\n resolution?: string;\n videoBitRateAvg?: number;\n videoBitRateMax?: number;\n videoFrameRateAvg?: number;\n videoPacketLossRate?: number;\n}\n\ninterface MSVideoRecvPayload extends MSVideoPayload {\n lowBitRateCallPercent?: number;\n lowFrameRateCallPercent?: number;\n recvBitRateAverage?: number;\n recvBitRateMaximum?: number;\n recvCodecType?: string;\n recvFpsHarmonicAverage?: number;\n recvFrameRateAverage?: number;\n recvNumResSwitches?: number;\n recvReorderBufferMaxSuccessfullyOrderedExtent?: number;\n recvReorderBufferMaxSuccessfullyOrderedLateTime?: number;\n recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number;\n recvReorderBufferPacketsDroppedDueToTimeout?: number;\n recvReorderBufferReorderedPackets?: number;\n recvResolutionHeight?: number;\n recvResolutionWidth?: number;\n recvVideoStreamsMax?: number;\n recvVideoStreamsMin?: number;\n recvVideoStreamsMode?: number;\n reorderBufferTotalPackets?: number;\n videoFrameLossRate?: number;\n videoPostFECPLR?: number;\n videoResolutions?: MSVideoResolutionDistribution;\n}\n\ninterface MSVideoResolutionDistribution {\n cifQuality?: number;\n h1080Quality?: number;\n h1440Quality?: number;\n h2160Quality?: number;\n h720Quality?: number;\n vgaQuality?: number;\n}\n\ninterface MSVideoSendPayload extends MSVideoPayload {\n sendBitRateAverage?: number;\n sendBitRateMaximum?: number;\n sendFrameRateAverage?: number;\n sendResolutionHeight?: number;\n sendResolutionWidth?: number;\n sendVideoStreamsMax?: number;\n}\n\ninterface MediaElementAudioSourceOptions {\n mediaElement: HTMLMediaElement;\n}\n\ninterface MediaEncryptedEventInit extends EventInit {\n initData?: ArrayBuffer | null;\n initDataType?: string;\n}\n\ninterface MediaKeyMessageEventInit extends EventInit {\n message?: ArrayBuffer | null;\n messageType?: MediaKeyMessageType;\n}\n\ninterface MediaKeySystemConfiguration {\n audioCapabilities?: MediaKeySystemMediaCapability[];\n distinctiveIdentifier?: MediaKeysRequirement;\n initDataTypes?: string[];\n persistentState?: MediaKeysRequirement;\n videoCapabilities?: MediaKeySystemMediaCapability[];\n}\n\ninterface MediaKeySystemMediaCapability {\n contentType?: string;\n robustness?: string;\n}\n\ninterface MediaStreamConstraints {\n audio?: boolean | MediaTrackConstraints;\n video?: boolean | MediaTrackConstraints;\n}\n\ninterface MediaStreamErrorEventInit extends EventInit {\n error?: MediaStreamError | null;\n}\n\ninterface MediaStreamEventInit extends EventInit {\n stream?: MediaStream;\n}\n\ninterface MediaStreamTrackEventInit extends EventInit {\n track?: MediaStreamTrack | null;\n}\n\ninterface MediaTrackCapabilities {\n aspectRatio?: number | DoubleRange;\n deviceId?: string;\n echoCancellation?: boolean[];\n facingMode?: string;\n frameRate?: number | DoubleRange;\n groupId?: string;\n height?: number | LongRange;\n sampleRate?: number | LongRange;\n sampleSize?: number | LongRange;\n volume?: number | DoubleRange;\n width?: number | LongRange;\n}\n\ninterface MediaTrackConstraintSet {\n aspectRatio?: number | ConstrainDoubleRange;\n channelCount?: number | ConstrainLongRange;\n deviceId?: string | string[] | ConstrainDOMStringParameters;\n displaySurface?: string | string[] | ConstrainDOMStringParameters;\n echoCancellation?: boolean | ConstrainBooleanParameters;\n facingMode?: string | string[] | ConstrainDOMStringParameters;\n frameRate?: number | ConstrainDoubleRange;\n groupId?: string | string[] | ConstrainDOMStringParameters;\n height?: number | ConstrainLongRange;\n latency?: number | ConstrainDoubleRange;\n logicalSurface?: boolean | ConstrainBooleanParameters;\n sampleRate?: number | ConstrainLongRange;\n sampleSize?: number | ConstrainLongRange;\n volume?: number | ConstrainDoubleRange;\n width?: number | ConstrainLongRange;\n}\n\ninterface MediaTrackConstraints extends MediaTrackConstraintSet {\n advanced?: MediaTrackConstraintSet[];\n}\n\ninterface MediaTrackSettings {\n aspectRatio?: number;\n deviceId?: string;\n echoCancellation?: boolean;\n facingMode?: string;\n frameRate?: number;\n groupId?: string;\n height?: number;\n sampleRate?: number;\n sampleSize?: number;\n volume?: number;\n width?: number;\n}\n\ninterface MediaTrackSupportedConstraints {\n aspectRatio?: boolean;\n deviceId?: boolean;\n echoCancellation?: boolean;\n facingMode?: boolean;\n frameRate?: boolean;\n groupId?: boolean;\n height?: boolean;\n sampleRate?: boolean;\n sampleSize?: boolean;\n volume?: boolean;\n width?: boolean;\n}\n\ninterface MessageEventInit extends EventInit {\n channel?: string;\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: Window | null;\n}\n\ninterface MouseEventInit extends EventModifierInit {\n button?: number;\n buttons?: number;\n clientX?: number;\n clientY?: number;\n relatedTarget?: EventTarget | null;\n screenX?: number;\n screenY?: number;\n}\n\ninterface MsZoomToOptions {\n animate?: string;\n contentX?: number;\n contentY?: number;\n scaleFactor?: number;\n viewportX?: string | null;\n viewportY?: string | null;\n}\n\ninterface MutationObserverInit {\n attributeFilter?: string[];\n attributeOldValue?: boolean;\n attributes?: boolean;\n characterData?: boolean;\n characterDataOldValue?: boolean;\n childList?: boolean;\n subtree?: boolean;\n}\n\ninterface NotificationEventInit extends ExtendableEventInit {\n action?: string;\n notification: Notification;\n}\n\ninterface NotificationOptions {\n body?: string;\n data?: any;\n dir?: NotificationDirection;\n icon?: string;\n lang?: string;\n tag?: string;\n}\n\ninterface ObjectURLOptions {\n oneTimeOnly?: boolean;\n}\n\ninterface OfflineAudioCompletionEventInit extends EventInit {\n renderedBuffer: AudioBuffer;\n}\n\ninterface OscillatorOptions extends AudioNodeOptions {\n detune?: number;\n frequency?: number;\n periodicWave?: PeriodicWave;\n type?: OscillatorType;\n}\n\ninterface PannerOptions extends AudioNodeOptions {\n coneInnerAngle?: number;\n coneOuterAngle?: number;\n coneOuterGain?: number;\n distanceModel?: DistanceModelType;\n maxDistance?: number;\n orientationX?: number;\n orientationY?: number;\n orientationZ?: number;\n panningModel?: PanningModelType;\n positionX?: number;\n positionY?: number;\n positionZ?: number;\n refDistance?: number;\n rolloffFactor?: number;\n}\n\ninterface PaymentCurrencyAmount {\n currency: string;\n currencySystem?: string;\n value: string;\n}\n\ninterface PaymentDetailsBase {\n displayItems?: PaymentItem[];\n modifiers?: PaymentDetailsModifier[];\n shippingOptions?: PaymentShippingOption[];\n}\n\ninterface PaymentDetailsInit extends PaymentDetailsBase {\n id?: string;\n total: PaymentItem;\n}\n\ninterface PaymentDetailsModifier {\n additionalDisplayItems?: PaymentItem[];\n data?: any;\n supportedMethods: string | string[];\n total?: PaymentItem;\n}\n\ninterface PaymentDetailsUpdate extends PaymentDetailsBase {\n error?: string;\n total?: PaymentItem;\n}\n\ninterface PaymentItem {\n amount: PaymentCurrencyAmount;\n label: string;\n pending?: boolean;\n}\n\ninterface PaymentMethodData {\n data?: any;\n supportedMethods: string | string[];\n}\n\ninterface PaymentOptions {\n requestPayerEmail?: boolean;\n requestPayerName?: boolean;\n requestPayerPhone?: boolean;\n requestShipping?: boolean;\n shippingType?: string;\n}\n\ninterface PaymentRequestUpdateEventInit extends EventInit {\n}\n\ninterface PaymentShippingOption {\n amount: PaymentCurrencyAmount;\n id: string;\n label: string;\n selected?: boolean;\n}\n\ninterface Pbkdf2Params extends Algorithm {\n hash: string | Algorithm;\n iterations: number;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface PeriodicWaveConstraints {\n disableNormalization?: boolean;\n}\n\ninterface PeriodicWaveOptions extends PeriodicWaveConstraints {\n imag?: number[];\n real?: number[];\n}\n\ninterface PointerEventInit extends MouseEventInit {\n height?: number;\n isPrimary?: boolean;\n pointerId?: number;\n pointerType?: string;\n pressure?: number;\n tiltX?: number;\n tiltY?: number;\n width?: number;\n}\n\ninterface PopStateEventInit extends EventInit {\n state?: any;\n}\n\ninterface PositionOptions {\n enableHighAccuracy?: boolean;\n maximumAge?: number;\n timeout?: number;\n}\n\ninterface ProgressEventInit extends EventInit {\n lengthComputable?: boolean;\n loaded?: number;\n total?: number;\n}\n\ninterface PushEventInit extends ExtendableEventInit {\n data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null;\n}\n\ninterface PushSubscriptionChangeInit extends ExtendableEventInit {\n newSubscription?: PushSubscription;\n oldSubscription?: PushSubscription;\n}\n\ninterface PushSubscriptionOptionsInit {\n applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null;\n userVisibleOnly?: boolean;\n}\n\ninterface QueuingStrategy {\n highWaterMark?: number;\n size?: WritableStreamChunkCallback;\n}\n\ninterface RTCConfiguration {\n bundlePolicy?: RTCBundlePolicy;\n iceServers?: RTCIceServer[];\n iceTransportPolicy?: RTCIceTransportPolicy;\n peerIdentity?: string;\n}\n\ninterface RTCDTMFToneChangeEventInit extends EventInit {\n tone?: string;\n}\n\ninterface RTCDtlsFingerprint {\n algorithm?: string;\n value?: string;\n}\n\ninterface RTCDtlsParameters {\n fingerprints?: RTCDtlsFingerprint[];\n role?: RTCDtlsRole;\n}\n\ninterface RTCIceCandidateAttributes extends RTCStats {\n addressSourceUrl?: string;\n candidateType?: RTCStatsIceCandidateType;\n ipAddress?: string;\n portNumber?: number;\n priority?: number;\n transport?: string;\n}\n\ninterface RTCIceCandidateComplete {\n}\n\ninterface RTCIceCandidateDictionary {\n foundation?: string;\n ip?: string;\n msMTurnSessionId?: string;\n port?: number;\n priority?: number;\n protocol?: RTCIceProtocol;\n relatedAddress?: string;\n relatedPort?: number;\n tcpType?: RTCIceTcpCandidateType;\n type?: RTCIceCandidateType;\n}\n\ninterface RTCIceCandidateInit {\n candidate?: string;\n sdpMLineIndex?: number;\n sdpMid?: string;\n}\n\ninterface RTCIceCandidatePair {\n local?: RTCIceCandidateDictionary;\n remote?: RTCIceCandidateDictionary;\n}\n\ninterface RTCIceCandidatePairStats extends RTCStats {\n availableIncomingBitrate?: number;\n availableOutgoingBitrate?: number;\n bytesReceived?: number;\n bytesSent?: number;\n localCandidateId?: string;\n nominated?: boolean;\n priority?: number;\n readable?: boolean;\n remoteCandidateId?: string;\n roundTripTime?: number;\n state?: RTCStatsIceCandidatePairState;\n transportId?: string;\n writable?: boolean;\n}\n\ninterface RTCIceGatherOptions {\n gatherPolicy?: RTCIceGatherPolicy;\n iceservers?: RTCIceServer[];\n portRange?: MSPortRange;\n}\n\ninterface RTCIceParameters {\n iceLite?: boolean | null;\n password?: string;\n usernameFragment?: string;\n}\n\ninterface RTCIceServer {\n credential?: string | null;\n urls?: any;\n username?: string | null;\n}\n\ninterface RTCInboundRTPStreamStats extends RTCRTPStreamStats {\n bytesReceived?: number;\n fractionLost?: number;\n jitter?: number;\n packetsLost?: number;\n packetsReceived?: number;\n}\n\ninterface RTCMediaStreamTrackStats extends RTCStats {\n audioLevel?: number;\n echoReturnLoss?: number;\n echoReturnLossEnhancement?: number;\n frameHeight?: number;\n frameWidth?: number;\n framesCorrupted?: number;\n framesDecoded?: number;\n framesDropped?: number;\n framesPerSecond?: number;\n framesReceived?: number;\n framesSent?: number;\n remoteSource?: boolean;\n ssrcIds?: string[];\n trackIdentifier?: string;\n}\n\ninterface RTCOfferOptions {\n iceRestart?: boolean;\n offerToReceiveAudio?: number;\n offerToReceiveVideo?: number;\n voiceActivityDetection?: boolean;\n}\n\ninterface RTCOutboundRTPStreamStats extends RTCRTPStreamStats {\n bytesSent?: number;\n packetsSent?: number;\n roundTripTime?: number;\n targetBitrate?: number;\n}\n\ninterface RTCPeerConnectionIceEventInit extends EventInit {\n candidate?: RTCIceCandidate;\n}\n\ninterface RTCRTPStreamStats extends RTCStats {\n associateStatsId?: string;\n codecId?: string;\n firCount?: number;\n isRemote?: boolean;\n mediaTrackId?: string;\n mediaType?: string;\n nackCount?: number;\n pliCount?: number;\n sliCount?: number;\n ssrc?: string;\n transportId?: string;\n}\n\ninterface RTCRtcpFeedback {\n parameter?: string;\n type?: string;\n}\n\ninterface RTCRtcpParameters {\n cname?: string;\n mux?: boolean;\n reducedSize?: boolean;\n ssrc?: number;\n}\n\ninterface RTCRtpCapabilities {\n codecs?: RTCRtpCodecCapability[];\n fecMechanisms?: string[];\n headerExtensions?: RTCRtpHeaderExtension[];\n}\n\ninterface RTCRtpCodecCapability {\n clockRate?: number;\n kind?: string;\n maxSpatialLayers?: number;\n maxTemporalLayers?: number;\n maxptime?: number;\n name?: string;\n numChannels?: number;\n options?: any;\n parameters?: any;\n preferredPayloadType?: number;\n ptime?: number;\n rtcpFeedback?: RTCRtcpFeedback[];\n svcMultiStreamSupport?: boolean;\n}\n\ninterface RTCRtpCodecParameters {\n clockRate?: number;\n maxptime?: number;\n name?: string;\n numChannels?: number;\n parameters?: any;\n payloadType?: number;\n ptime?: number;\n rtcpFeedback?: RTCRtcpFeedback[];\n}\n\ninterface RTCRtpContributingSource {\n audioLevel?: number;\n csrc?: number;\n timestamp?: number;\n}\n\ninterface RTCRtpEncodingParameters {\n active?: boolean;\n codecPayloadType?: number;\n dependencyEncodingIds?: string[];\n encodingId?: string;\n fec?: RTCRtpFecParameters;\n framerateScale?: number;\n maxBitrate?: number;\n maxFramerate?: number;\n minQuality?: number;\n priority?: number;\n resolutionScale?: number;\n rtx?: RTCRtpRtxParameters;\n ssrc?: number;\n ssrcRange?: RTCSsrcRange;\n}\n\ninterface RTCRtpFecParameters {\n mechanism?: string;\n ssrc?: number;\n}\n\ninterface RTCRtpHeaderExtension {\n kind?: string;\n preferredEncrypt?: boolean;\n preferredId?: number;\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionParameters {\n encrypt?: boolean;\n id?: number;\n uri?: string;\n}\n\ninterface RTCRtpParameters {\n codecs?: RTCRtpCodecParameters[];\n degradationPreference?: RTCDegradationPreference;\n encodings?: RTCRtpEncodingParameters[];\n headerExtensions?: RTCRtpHeaderExtensionParameters[];\n muxId?: string;\n rtcp?: RTCRtcpParameters;\n}\n\ninterface RTCRtpRtxParameters {\n ssrc?: number;\n}\n\ninterface RTCRtpUnhandled {\n muxId?: string;\n payloadType?: number;\n ssrc?: number;\n}\n\ninterface RTCSessionDescriptionInit {\n sdp?: string;\n type?: RTCSdpType;\n}\n\ninterface RTCSrtpKeyParam {\n keyMethod?: string;\n keySalt?: string;\n lifetime?: string;\n mkiLength?: number;\n mkiValue?: number;\n}\n\ninterface RTCSrtpSdesParameters {\n cryptoSuite?: string;\n keyParams?: RTCSrtpKeyParam[];\n sessionParams?: string[];\n tag?: number;\n}\n\ninterface RTCSsrcRange {\n max?: number;\n min?: number;\n}\n\ninterface RTCStats {\n id?: string;\n msType?: MSStatsType;\n timestamp?: number;\n type?: RTCStatsType;\n}\n\ninterface RTCStatsReport {\n}\n\ninterface RTCTransportStats extends RTCStats {\n activeConnection?: boolean;\n bytesReceived?: number;\n bytesSent?: number;\n localCertificateId?: string;\n remoteCertificateId?: string;\n rtcpTransportStatsId?: string;\n selectedCandidatePairId?: string;\n}\n\ninterface RegistrationOptions {\n scope?: string;\n}\n\ninterface RequestInit {\n body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null;\n cache?: RequestCache;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n integrity?: string;\n keepalive?: boolean;\n method?: string;\n mode?: RequestMode;\n redirect?: RequestRedirect;\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n signal?: AbortSignal;\n window?: any;\n}\n\ninterface ResponseInit {\n headers?: HeadersInit;\n status?: number;\n statusText?: string;\n}\n\ninterface RsaHashedImportParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {\n hash: KeyAlgorithm;\n}\n\ninterface RsaHashedKeyGenParams extends RsaKeyGenParams {\n hash: string | Algorithm;\n}\n\ninterface RsaKeyAlgorithm extends KeyAlgorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaKeyGenParams extends Algorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaOaepParams extends Algorithm {\n label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface RsaOtherPrimesInfo {\n d?: string;\n r?: string;\n t?: string;\n}\n\ninterface RsaPssParams extends Algorithm {\n saltLength: number;\n}\n\ninterface ScopedCredentialDescriptor {\n id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n transports?: Transport[];\n type: ScopedCredentialType;\n}\n\ninterface ScopedCredentialOptions {\n excludeList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface ScopedCredentialParameters {\n algorithm: string | Algorithm;\n type: ScopedCredentialType;\n}\n\ninterface SecurityPolicyViolationEventInit extends EventInit {\n blockedURI?: string;\n columnNumber?: number;\n documentURI?: string;\n effectiveDirective?: string;\n lineNumber?: number;\n originalPolicy?: string;\n referrer?: string;\n sourceFile?: string;\n statusCode?: number;\n violatedDirective?: string;\n}\n\ninterface ServiceWorkerMessageEventInit extends EventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: ServiceWorker | MessagePort | null;\n}\n\ninterface SpeechSynthesisEventInit extends EventInit {\n charIndex?: number;\n charLength?: number;\n elapsedTime?: number;\n name?: string;\n utterance?: SpeechSynthesisUtterance | null;\n}\n\ninterface StereoPannerOptions extends AudioNodeOptions {\n pan?: number;\n}\n\ninterface StoreExceptionsInformation extends ExceptionInformation {\n detailURI?: string | null;\n explanationString?: string | null;\n siteName?: string | null;\n}\n\ninterface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface SyncEventInit extends ExtendableEventInit {\n lastChance?: boolean;\n tag: string;\n}\n\ninterface TextDecodeOptions {\n stream?: boolean;\n}\n\ninterface TextDecoderOptions {\n fatal?: boolean;\n ignoreBOM?: boolean;\n}\n\ninterface TrackEventInit extends EventInit {\n track?: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ninterface TransitionEventInit extends EventInit {\n elapsedTime?: number;\n propertyName?: string;\n}\n\ninterface UIEventInit extends EventInit {\n detail?: number;\n view?: Window | null;\n}\n\ninterface UnderlyingSink {\n abort?: WritableStreamErrorCallback;\n close?: WritableStreamDefaultControllerCallback;\n start: WritableStreamDefaultControllerCallback;\n write?: WritableStreamChunkCallback;\n}\n\ninterface VRDisplayEventInit extends EventInit {\n display: VRDisplay;\n reason?: VRDisplayEventReason;\n}\n\ninterface VRLayer {\n leftBounds?: number[] | null;\n rightBounds?: number[] | null;\n source?: HTMLCanvasElement | null;\n}\n\ninterface VRStageParameters {\n sittingToStandingTransform?: Float32Array;\n sizeX?: number;\n sizeY?: number;\n}\n\ninterface WaveShaperOptions extends AudioNodeOptions {\n curve?: number[];\n oversample?: OverSampleType;\n}\n\ninterface WebAuthnExtensions {\n}\n\ninterface WebGLContextAttributes {\n alpha?: boolean;\n antialias?: boolean;\n depth?: boolean;\n failIfMajorPerformanceCaveat?: boolean;\n premultipliedAlpha?: boolean;\n preserveDrawingBuffer?: boolean;\n stencil?: boolean;\n}\n\ninterface WebGLContextEventInit extends EventInit {\n statusMessage?: string;\n}\n\ninterface WheelEventInit extends MouseEventInit {\n deltaMode?: number;\n deltaX?: number;\n deltaY?: number;\n deltaZ?: number;\n}\n\ninterface EventListener {\n (evt: Event): void;\n}\n\ntype WebKitEntriesCallback = ((entries: WebKitEntry[]) => void) | { handleEvent(entries: WebKitEntry[]): void; };\n\ntype WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMError): void; };\n\ntype WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; };\n\ninterface ANGLE_instanced_arrays {\n drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void;\n drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void;\n vertexAttribDivisorANGLE(index: number, divisor: number): void;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n}\n\ndeclare var ANGLE_instanced_arrays: {\n prototype: ANGLE_instanced_arrays;\n new(): ANGLE_instanced_arrays;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n};\n\ninterface AbortController {\n readonly signal: AbortSignal;\n abort(): void;\n}\n\ndeclare var AbortController: {\n prototype: AbortController;\n new(): AbortController;\n};\n\ninterface AbortSignalEventMap {\n \"abort\": ProgressEvent;\n}\n\ninterface AbortSignal extends EventTarget {\n readonly aborted: boolean;\n onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AbortSignal: {\n prototype: AbortSignal;\n new(): AbortSignal;\n};\n\ninterface AbstractWorkerEventMap {\n \"error\": ErrorEvent;\n}\n\ninterface AbstractWorker {\n onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AesCfbParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCmacParams extends Algorithm {\n length: number;\n}\n\ninterface AnalyserNode extends AudioNode {\n fftSize: number;\n readonly frequencyBinCount: number;\n maxDecibels: number;\n minDecibels: number;\n smoothingTimeConstant: number;\n getByteFrequencyData(array: Uint8Array): void;\n getByteTimeDomainData(array: Uint8Array): void;\n getFloatFrequencyData(array: Float32Array): void;\n getFloatTimeDomainData(array: Float32Array): void;\n}\n\ndeclare var AnalyserNode: {\n prototype: AnalyserNode;\n new(): AnalyserNode;\n};\n\ninterface Animation {\n currentTime: number | null;\n effect: AnimationEffectReadOnly;\n readonly finished: Promise;\n id: string;\n readonly pending: boolean;\n readonly playState: \"idle\" | \"running\" | \"paused\" | \"finished\";\n playbackRate: number;\n readonly ready: Promise;\n startTime: number;\n timeline: AnimationTimeline;\n cancel(): void;\n finish(): void;\n oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any;\n onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any;\n pause(): void;\n play(): void;\n reverse(): void;\n}\n\ndeclare var Animation: {\n prototype: Animation;\n new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation;\n};\n\ninterface AnimationEffectReadOnly {\n readonly timing: number;\n getComputedTiming(): ComputedTimingProperties;\n}\n\ninterface AnimationEvent extends Event {\n readonly animationName: string;\n readonly elapsedTime: number;\n}\n\ndeclare var AnimationEvent: {\n prototype: AnimationEvent;\n new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent;\n};\n\ninterface AnimationKeyFrame {\n easing?: string | string[];\n offset?: number | null | (number | null)[];\n [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined;\n}\n\ninterface AnimationOptions {\n delay?: number;\n direction?: \"normal\" | \"reverse\" | \"alternate\" | \"alternate-reverse\";\n duration?: number;\n easing?: string;\n endDelay?: number;\n fill?: \"none\" | \"forwards\" | \"backwards\" | \"both\"| \"auto\";\n id?: string;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface AnimationPlaybackEvent extends Event {\n readonly currentTime: number | null;\n readonly timelineTime: number | null;\n}\n\ndeclare var AnimationPlaybackEvent: {\n prototype: AnimationPlaybackEvent;\n new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent;\n};\n\ninterface AnimationPlaybackEventInit extends EventInit {\n currentTime?: number | null;\n timelineTime?: number | null;\n}\n\ninterface AnimationTimeline {\n readonly currentTime: number | null;\n}\n\ninterface ApplicationCacheEventMap {\n \"cached\": Event;\n \"checking\": Event;\n \"downloading\": Event;\n \"error\": Event;\n \"noupdate\": Event;\n \"obsolete\": Event;\n \"progress\": ProgressEvent;\n \"updateready\": Event;\n}\n\ninterface ApplicationCache extends EventTarget {\n oncached: ((this: ApplicationCache, ev: Event) => any) | null;\n onchecking: ((this: ApplicationCache, ev: Event) => any) | null;\n ondownloading: ((this: ApplicationCache, ev: Event) => any) | null;\n onerror: ((this: ApplicationCache, ev: Event) => any) | null;\n onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null;\n onobsolete: ((this: ApplicationCache, ev: Event) => any) | null;\n onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null;\n onupdateready: ((this: ApplicationCache, ev: Event) => any) | null;\n readonly status: number;\n abort(): void;\n swapCache(): void;\n update(): void;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ApplicationCache: {\n prototype: ApplicationCache;\n new(): ApplicationCache;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n};\n\ninterface AssignedNodesOptions {\n flatten?: boolean;\n}\n\ninterface Attr extends Node {\n readonly name: string;\n readonly ownerElement: Element | null;\n readonly prefix: string | null;\n readonly specified: boolean;\n value: string;\n}\n\ndeclare var Attr: {\n prototype: Attr;\n new(): Attr;\n};\n\ninterface AudioBuffer {\n readonly duration: number;\n readonly length: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n getChannelData(channel: number): Float32Array;\n}\n\ndeclare var AudioBuffer: {\n prototype: AudioBuffer;\n new(): AudioBuffer;\n};\n\ninterface AudioBufferSourceNodeEventMap {\n \"ended\": Event;\n}\n\ninterface AudioBufferSourceNode extends AudioNode {\n buffer: AudioBuffer | null;\n readonly detune: AudioParam;\n loop: boolean;\n loopEnd: number;\n loopStart: number;\n onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null;\n readonly playbackRate: AudioParam;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioBufferSourceNode: {\n prototype: AudioBufferSourceNode;\n new(): AudioBufferSourceNode;\n};\n\ninterface AudioContextEventMap {\n \"statechange\": Event;\n}\n\ninterface AudioContextBase extends EventTarget {\n readonly currentTime: number;\n readonly destination: AudioDestinationNode;\n readonly listener: AudioListener;\n onstatechange: ((this: AudioContext, ev: Event) => any) | null;\n readonly sampleRate: number;\n readonly state: AudioContextState;\n close(): Promise;\n createAnalyser(): AnalyserNode;\n createBiquadFilter(): BiquadFilterNode;\n createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;\n createBufferSource(): AudioBufferSourceNode;\n createChannelMerger(numberOfInputs?: number): ChannelMergerNode;\n createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode;\n createConvolver(): ConvolverNode;\n createDelay(maxDelayTime?: number): DelayNode;\n createDynamicsCompressor(): DynamicsCompressorNode;\n createGain(): GainNode;\n createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode;\n createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;\n createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode;\n createOscillator(): OscillatorNode;\n createPanner(): PannerNode;\n createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave;\n createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;\n createStereoPanner(): StereoPannerNode;\n createWaveShaper(): WaveShaperNode;\n decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise;\n resume(): Promise;\n addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AudioContext extends AudioContextBase {\n suspend(): Promise;\n}\n\ndeclare var AudioContext: {\n prototype: AudioContext;\n new(): AudioContext;\n};\n\ninterface AudioDestinationNode extends AudioNode {\n readonly maxChannelCount: number;\n}\n\ndeclare var AudioDestinationNode: {\n prototype: AudioDestinationNode;\n new(): AudioDestinationNode;\n};\n\ninterface AudioListener {\n /** @deprecated */\n dopplerFactor: number;\n /** @deprecated */\n speedOfSound: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n /** @deprecated */\n setVelocity(x: number, y: number, z: number): void;\n}\n\ndeclare var AudioListener: {\n prototype: AudioListener;\n new(): AudioListener;\n};\n\ninterface AudioNode extends EventTarget {\n channelCount: number;\n channelCountMode: ChannelCountMode;\n channelInterpretation: ChannelInterpretation;\n readonly context: AudioContext;\n readonly numberOfInputs: number;\n readonly numberOfOutputs: number;\n connect(destination: AudioNode, output?: number, input?: number): AudioNode;\n connect(destination: AudioParam, output?: number): void;\n disconnect(): void;\n disconnect(output: number): void;\n disconnect(destination: AudioNode): void;\n disconnect(destination: AudioNode, output: number): void;\n disconnect(destination: AudioNode, output: number, input: number): void;\n disconnect(destination: AudioParam): void;\n disconnect(destination: AudioParam, output: number): void;\n}\n\ndeclare var AudioNode: {\n prototype: AudioNode;\n new(): AudioNode;\n};\n\ninterface AudioParam {\n readonly defaultValue: number;\n value: number;\n cancelScheduledValues(cancelTime: number): AudioParam;\n exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;\n linearRampToValueAtTime(value: number, endTime: number): AudioParam;\n setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam;\n setValueAtTime(value: number, startTime: number): AudioParam;\n setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam;\n}\n\ndeclare var AudioParam: {\n prototype: AudioParam;\n new(): AudioParam;\n};\n\ninterface AudioProcessingEvent extends Event {\n readonly inputBuffer: AudioBuffer;\n readonly outputBuffer: AudioBuffer;\n readonly playbackTime: number;\n}\n\ndeclare var AudioProcessingEvent: {\n prototype: AudioProcessingEvent;\n new(): AudioProcessingEvent;\n};\n\ninterface AudioTrack {\n enabled: boolean;\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var AudioTrack: {\n prototype: AudioTrack;\n new(): AudioTrack;\n};\n\ninterface AudioTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface AudioTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: AudioTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n getTrackById(id: string): AudioTrack | null;\n item(index: number): AudioTrack;\n addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: AudioTrack;\n}\n\ndeclare var AudioTrackList: {\n prototype: AudioTrackList;\n new(): AudioTrackList;\n};\n\ninterface BarProp {\n readonly visible: boolean;\n}\n\ndeclare var BarProp: {\n prototype: BarProp;\n new(): BarProp;\n};\n\ninterface BeforeUnloadEvent extends Event {\n returnValue: any;\n}\n\ndeclare var BeforeUnloadEvent: {\n prototype: BeforeUnloadEvent;\n new(): BeforeUnloadEvent;\n};\n\ninterface BhxBrowser {\n readonly lastError: DOMException;\n checkMatchesGlobExpression(pattern: string, value: string): boolean;\n checkMatchesUriExpression(pattern: string, value: string): boolean;\n clearLastError(): void;\n currentWindowId(): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n getExtensionId(): string;\n getThisAddress(): any;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericListenerHandler(eventHandler: Function): void;\n setLastError(parameters: string): void;\n webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void;\n}\n\ndeclare var BhxBrowser: {\n prototype: BhxBrowser;\n new(): BhxBrowser;\n};\n\ninterface BiquadFilterNode extends AudioNode {\n readonly Q: AudioParam;\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n readonly gain: AudioParam;\n type: BiquadFilterType;\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var BiquadFilterNode: {\n prototype: BiquadFilterNode;\n new(): BiquadFilterNode;\n};\n\ninterface Blob {\n readonly size: number;\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n slice(start?: number, end?: number, contentType?: string): Blob;\n}\n\ndeclare var Blob: {\n prototype: Blob;\n new (blobParts?: any[], options?: BlobPropertyBag): Blob;\n};\n\ninterface BlobPropertyBag {\n endings?: string;\n type?: string;\n}\n\ninterface Body {\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise;\n blob(): Promise;\n formData(): Promise;\n json(): Promise;\n text(): Promise;\n}\n\ninterface BroadcastChannel extends EventTarget {\n readonly name: string;\n onmessage: (ev: MessageEvent) => any;\n onmessageerror: (ev: MessageEvent) => any;\n addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n close(): void;\n postMessage(message: any): void;\n removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BroadcastChannel: {\n prototype: BroadcastChannel;\n new(name: string): BroadcastChannel;\n};\n\ninterface BroadcastChannelEventMap {\n message: MessageEvent;\n messageerror: MessageEvent;\n}\n\ninterface ByteLengthQueuingStrategy {\n highWaterMark: number;\n size(chunk?: any): number;\n}\n\ndeclare var ByteLengthQueuingStrategy: {\n prototype: ByteLengthQueuingStrategy;\n new(strategy: QueuingStrategy): ByteLengthQueuingStrategy;\n};\n\ninterface CDATASection extends Text {\n}\n\ndeclare var CDATASection: {\n prototype: CDATASection;\n new(): CDATASection;\n};\n\ninterface CSS {\n escape(value: string): string;\n supports(property: string, value?: string): boolean;\n}\ndeclare var CSS: CSS;\n\ninterface CSSConditionRule extends CSSGroupingRule {\n conditionText: string;\n}\n\ndeclare var CSSConditionRule: {\n prototype: CSSConditionRule;\n new(): CSSConditionRule;\n};\n\ninterface CSSFontFaceRule extends CSSRule {\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSFontFaceRule: {\n prototype: CSSFontFaceRule;\n new(): CSSFontFaceRule;\n};\n\ninterface CSSGroupingRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n deleteRule(index: number): void;\n insertRule(rule: string, index: number): number;\n}\n\ndeclare var CSSGroupingRule: {\n prototype: CSSGroupingRule;\n new(): CSSGroupingRule;\n};\n\ninterface CSSImportRule extends CSSRule {\n readonly href: string;\n readonly media: MediaList;\n readonly styleSheet: CSSStyleSheet;\n}\n\ndeclare var CSSImportRule: {\n prototype: CSSImportRule;\n new(): CSSImportRule;\n};\n\ninterface CSSKeyframeRule extends CSSRule {\n keyText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSKeyframeRule: {\n prototype: CSSKeyframeRule;\n new(): CSSKeyframeRule;\n};\n\ninterface CSSKeyframesRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n name: string;\n appendRule(rule: string): void;\n deleteRule(rule: string): void;\n findRule(rule: string): CSSKeyframeRule | null;\n}\n\ndeclare var CSSKeyframesRule: {\n prototype: CSSKeyframesRule;\n new(): CSSKeyframesRule;\n};\n\ninterface CSSMediaRule extends CSSConditionRule {\n readonly media: MediaList;\n}\n\ndeclare var CSSMediaRule: {\n prototype: CSSMediaRule;\n new(): CSSMediaRule;\n};\n\ninterface CSSNamespaceRule extends CSSRule {\n readonly namespaceURI: string;\n readonly prefix: string;\n}\n\ndeclare var CSSNamespaceRule: {\n prototype: CSSNamespaceRule;\n new(): CSSNamespaceRule;\n};\n\ninterface CSSPageRule extends CSSRule {\n readonly pseudoClass: string;\n readonly selector: string;\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSPageRule: {\n prototype: CSSPageRule;\n new(): CSSPageRule;\n};\n\ninterface CSSRule {\n cssText: string;\n readonly parentRule: CSSRule | null;\n readonly parentStyleSheet: CSSStyleSheet | null;\n readonly type: number;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n}\n\ndeclare var CSSRule: {\n prototype: CSSRule;\n new(): CSSRule;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n};\n\ninterface CSSRuleList {\n readonly length: number;\n item(index: number): CSSRule | null;\n [index: number]: CSSRule;\n}\n\ndeclare var CSSRuleList: {\n prototype: CSSRuleList;\n new(): CSSRuleList;\n};\n\ninterface CSSStyleDeclaration {\n alignContent: string | null;\n alignItems: string | null;\n alignSelf: string | null;\n alignmentBaseline: string | null;\n animation: string | null;\n animationDelay: string | null;\n animationDirection: string | null;\n animationDuration: string | null;\n animationFillMode: string | null;\n animationIterationCount: string | null;\n animationName: string | null;\n animationPlayState: string | null;\n animationTimingFunction: string | null;\n backfaceVisibility: string | null;\n background: string | null;\n backgroundAttachment: string | null;\n backgroundClip: string | null;\n backgroundColor: string | null;\n backgroundImage: string | null;\n backgroundOrigin: string | null;\n backgroundPosition: string | null;\n backgroundPositionX: string | null;\n backgroundPositionY: string | null;\n backgroundRepeat: string | null;\n backgroundSize: string | null;\n baselineShift: string | null;\n border: string | null;\n borderBottom: string | null;\n borderBottomColor: string | null;\n borderBottomLeftRadius: string | null;\n borderBottomRightRadius: string | null;\n borderBottomStyle: string | null;\n borderBottomWidth: string | null;\n borderCollapse: string | null;\n borderColor: string | null;\n borderImage: string | null;\n borderImageOutset: string | null;\n borderImageRepeat: string | null;\n borderImageSlice: string | null;\n borderImageSource: string | null;\n borderImageWidth: string | null;\n borderLeft: string | null;\n borderLeftColor: string | null;\n borderLeftStyle: string | null;\n borderLeftWidth: string | null;\n borderRadius: string | null;\n borderRight: string | null;\n borderRightColor: string | null;\n borderRightStyle: string | null;\n borderRightWidth: string | null;\n borderSpacing: string | null;\n borderStyle: string | null;\n borderTop: string | null;\n borderTopColor: string | null;\n borderTopLeftRadius: string | null;\n borderTopRightRadius: string | null;\n borderTopStyle: string | null;\n borderTopWidth: string | null;\n borderWidth: string | null;\n bottom: string | null;\n boxShadow: string | null;\n boxSizing: string | null;\n breakAfter: string | null;\n breakBefore: string | null;\n breakInside: string | null;\n captionSide: string | null;\n clear: string | null;\n clip: string | null;\n clipPath: string | null;\n clipRule: string | null;\n color: string | null;\n colorInterpolationFilters: string | null;\n columnCount: any;\n columnFill: string | null;\n columnGap: any;\n columnRule: string | null;\n columnRuleColor: any;\n columnRuleStyle: string | null;\n columnRuleWidth: any;\n columnSpan: string | null;\n columnWidth: any;\n columns: string | null;\n content: string | null;\n counterIncrement: string | null;\n counterReset: string | null;\n cssFloat: string | null;\n cssText: string;\n cursor: string | null;\n direction: string | null;\n display: string | null;\n dominantBaseline: string | null;\n emptyCells: string | null;\n enableBackground: string | null;\n fill: string | null;\n fillOpacity: string | null;\n fillRule: string | null;\n filter: string | null;\n flex: string | null;\n flexBasis: string | null;\n flexDirection: string | null;\n flexFlow: string | null;\n flexGrow: string | null;\n flexShrink: string | null;\n flexWrap: string | null;\n floodColor: string | null;\n floodOpacity: string | null;\n font: string | null;\n fontFamily: string | null;\n fontFeatureSettings: string | null;\n fontSize: string | null;\n fontSizeAdjust: string | null;\n fontStretch: string | null;\n fontStyle: string | null;\n fontVariant: string | null;\n fontWeight: string | null;\n gap: string | null;\n glyphOrientationHorizontal: string | null;\n glyphOrientationVertical: string | null;\n grid: string | null;\n gridArea: string | null;\n gridAutoColumns: string | null;\n gridAutoFlow: string | null;\n gridAutoRows: string | null;\n gridColumn: string | null;\n gridColumnEnd: string | null;\n gridColumnGap: string | null;\n gridColumnStart: string | null;\n gridGap: string | null;\n gridRow: string | null;\n gridRowEnd: string | null;\n gridRowGap: string | null;\n gridRowStart: string | null;\n gridTemplate: string | null;\n gridTemplateAreas: string | null;\n gridTemplateColumns: string | null;\n gridTemplateRows: string | null;\n height: string | null;\n imeMode: string | null;\n justifyContent: string | null;\n justifyItems: string | null;\n justifySelf: string | null;\n kerning: string | null;\n layoutGrid: string | null;\n layoutGridChar: string | null;\n layoutGridLine: string | null;\n layoutGridMode: string | null;\n layoutGridType: string | null;\n left: string | null;\n readonly length: number;\n letterSpacing: string | null;\n lightingColor: string | null;\n lineBreak: string | null;\n lineHeight: string | null;\n listStyle: string | null;\n listStyleImage: string | null;\n listStylePosition: string | null;\n listStyleType: string | null;\n margin: string | null;\n marginBottom: string | null;\n marginLeft: string | null;\n marginRight: string | null;\n marginTop: string | null;\n marker: string | null;\n markerEnd: string | null;\n markerMid: string | null;\n markerStart: string | null;\n mask: string | null;\n maskImage: string | null;\n maxHeight: string | null;\n maxWidth: string | null;\n minHeight: string | null;\n minWidth: string | null;\n msContentZoomChaining: string | null;\n msContentZoomLimit: string | null;\n msContentZoomLimitMax: any;\n msContentZoomLimitMin: any;\n msContentZoomSnap: string | null;\n msContentZoomSnapPoints: string | null;\n msContentZoomSnapType: string | null;\n msContentZooming: string | null;\n msFlowFrom: string | null;\n msFlowInto: string | null;\n msFontFeatureSettings: string | null;\n msGridColumn: any;\n msGridColumnAlign: string | null;\n msGridColumnSpan: any;\n msGridColumns: string | null;\n msGridRow: any;\n msGridRowAlign: string | null;\n msGridRowSpan: any;\n msGridRows: string | null;\n msHighContrastAdjust: string | null;\n msHyphenateLimitChars: string | null;\n msHyphenateLimitLines: any;\n msHyphenateLimitZone: any;\n msHyphens: string | null;\n msImeAlign: string | null;\n msOverflowStyle: string | null;\n msScrollChaining: string | null;\n msScrollLimit: string | null;\n msScrollLimitXMax: any;\n msScrollLimitXMin: any;\n msScrollLimitYMax: any;\n msScrollLimitYMin: any;\n msScrollRails: string | null;\n msScrollSnapPointsX: string | null;\n msScrollSnapPointsY: string | null;\n msScrollSnapType: string | null;\n msScrollSnapX: string | null;\n msScrollSnapY: string | null;\n msScrollTranslation: string | null;\n msTextCombineHorizontal: string | null;\n msTextSizeAdjust: any;\n msTouchAction: string | null;\n msTouchSelect: string | null;\n msUserSelect: string | null;\n msWrapFlow: string;\n msWrapMargin: any;\n msWrapThrough: string;\n objectFit: string | null;\n objectPosition: string | null;\n opacity: string | null;\n order: string | null;\n orphans: string | null;\n outline: string | null;\n outlineColor: string | null;\n outlineOffset: string | null;\n outlineStyle: string | null;\n outlineWidth: string | null;\n overflow: string | null;\n overflowX: string | null;\n overflowY: string | null;\n padding: string | null;\n paddingBottom: string | null;\n paddingLeft: string | null;\n paddingRight: string | null;\n paddingTop: string | null;\n pageBreakAfter: string | null;\n pageBreakBefore: string | null;\n pageBreakInside: string | null;\n readonly parentRule: CSSRule;\n penAction: string | null;\n perspective: string | null;\n perspectiveOrigin: string | null;\n pointerEvents: string | null;\n position: string | null;\n quotes: string | null;\n resize: string | null;\n right: string | null;\n rotate: string | null;\n rowGap: string | null;\n rubyAlign: string | null;\n rubyOverhang: string | null;\n rubyPosition: string | null;\n scale: string | null;\n stopColor: string | null;\n stopOpacity: string | null;\n stroke: string | null;\n strokeDasharray: string | null;\n strokeDashoffset: string | null;\n strokeLinecap: string | null;\n strokeLinejoin: string | null;\n strokeMiterlimit: string | null;\n strokeOpacity: string | null;\n strokeWidth: string | null;\n tableLayout: string | null;\n textAlign: string | null;\n textAlignLast: string | null;\n textAnchor: string | null;\n textCombineUpright: string | null;\n textDecoration: string | null;\n textIndent: string | null;\n textJustify: string | null;\n textKashida: string | null;\n textKashidaSpace: string | null;\n textOverflow: string | null;\n textShadow: string | null;\n textTransform: string | null;\n textUnderlinePosition: string | null;\n top: string | null;\n touchAction: string | null;\n transform: string | null;\n transformOrigin: string | null;\n transformStyle: string | null;\n transition: string | null;\n transitionDelay: string | null;\n transitionDuration: string | null;\n transitionProperty: string | null;\n transitionTimingFunction: string | null;\n translate: string | null;\n unicodeBidi: string | null;\n userSelect: string | null;\n verticalAlign: string | null;\n visibility: string | null;\n webkitAlignContent: string | null;\n webkitAlignItems: string | null;\n webkitAlignSelf: string | null;\n webkitAnimation: string | null;\n webkitAnimationDelay: string | null;\n webkitAnimationDirection: string | null;\n webkitAnimationDuration: string | null;\n webkitAnimationFillMode: string | null;\n webkitAnimationIterationCount: string | null;\n webkitAnimationName: string | null;\n webkitAnimationPlayState: string | null;\n webkitAnimationTimingFunction: string | null;\n webkitAppearance: string | null;\n webkitBackfaceVisibility: string | null;\n webkitBackgroundClip: string | null;\n webkitBackgroundOrigin: string | null;\n webkitBackgroundSize: string | null;\n webkitBorderBottomLeftRadius: string | null;\n webkitBorderBottomRightRadius: string | null;\n webkitBorderImage: string | null;\n webkitBorderRadius: string | null;\n webkitBorderTopLeftRadius: string | null;\n webkitBorderTopRightRadius: string | null;\n webkitBoxAlign: string | null;\n webkitBoxDirection: string | null;\n webkitBoxFlex: string | null;\n webkitBoxOrdinalGroup: string | null;\n webkitBoxOrient: string | null;\n webkitBoxPack: string | null;\n webkitBoxSizing: string | null;\n webkitColumnBreakAfter: string | null;\n webkitColumnBreakBefore: string | null;\n webkitColumnBreakInside: string | null;\n webkitColumnCount: any;\n webkitColumnGap: any;\n webkitColumnRule: string | null;\n webkitColumnRuleColor: any;\n webkitColumnRuleStyle: string | null;\n webkitColumnRuleWidth: any;\n webkitColumnSpan: string | null;\n webkitColumnWidth: any;\n webkitColumns: string | null;\n webkitFilter: string | null;\n webkitFlex: string | null;\n webkitFlexBasis: string | null;\n webkitFlexDirection: string | null;\n webkitFlexFlow: string | null;\n webkitFlexGrow: string | null;\n webkitFlexShrink: string | null;\n webkitFlexWrap: string | null;\n webkitJustifyContent: string | null;\n webkitOrder: string | null;\n webkitPerspective: string | null;\n webkitPerspectiveOrigin: string | null;\n webkitTapHighlightColor: string | null;\n webkitTextFillColor: string | null;\n webkitTextSizeAdjust: any;\n webkitTextStroke: string | null;\n webkitTextStrokeColor: string | null;\n webkitTextStrokeWidth: string | null;\n webkitTransform: string | null;\n webkitTransformOrigin: string | null;\n webkitTransformStyle: string | null;\n webkitTransition: string | null;\n webkitTransitionDelay: string | null;\n webkitTransitionDuration: string | null;\n webkitTransitionProperty: string | null;\n webkitTransitionTimingFunction: string | null;\n webkitUserModify: string | null;\n webkitUserSelect: string | null;\n webkitWritingMode: string | null;\n whiteSpace: string | null;\n widows: string | null;\n width: string | null;\n wordBreak: string | null;\n wordSpacing: string | null;\n wordWrap: string | null;\n writingMode: string | null;\n zIndex: string | null;\n zoom: string | null;\n getPropertyPriority(propertyName: string): string;\n getPropertyValue(propertyName: string): string;\n item(index: number): string;\n removeProperty(propertyName: string): string;\n setProperty(propertyName: string, value: string | null, priority?: string | null): void;\n [index: number]: string;\n}\n\ndeclare var CSSStyleDeclaration: {\n prototype: CSSStyleDeclaration;\n new(): CSSStyleDeclaration;\n};\n\ninterface CSSStyleRule extends CSSRule {\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSStyleRule: {\n prototype: CSSStyleRule;\n new(): CSSStyleRule;\n};\n\ninterface CSSStyleSheet extends StyleSheet {\n readonly cssRules: CSSRuleList;\n /** @deprecated */\n cssText: string;\n /** @deprecated */\n readonly id: string;\n /** @deprecated */\n readonly imports: StyleSheetList;\n /** @deprecated */\n readonly isAlternate: boolean;\n /** @deprecated */\n readonly isPrefAlternate: boolean;\n readonly ownerRule: CSSRule | null;\n /** @deprecated */\n readonly owningElement: Element;\n /** @deprecated */\n readonly pages: any;\n /** @deprecated */\n readonly readOnly: boolean;\n readonly rules: CSSRuleList;\n /** @deprecated */\n addImport(bstrURL: string, lIndex?: number): number;\n /** @deprecated */\n addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number;\n addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number;\n deleteRule(index?: number): void;\n insertRule(rule: string, index?: number): number;\n /** @deprecated */\n removeImport(lIndex: number): void;\n removeRule(lIndex: number): void;\n}\n\ndeclare var CSSStyleSheet: {\n prototype: CSSStyleSheet;\n new(): CSSStyleSheet;\n};\n\ninterface CSSSupportsRule extends CSSConditionRule {\n}\n\ndeclare var CSSSupportsRule: {\n prototype: CSSSupportsRule;\n new(): CSSSupportsRule;\n};\n\ninterface Cache {\n add(request: Request | string): Promise;\n addAll(requests: (Request | string)[]): Promise;\n delete(request: Request | string, options?: CacheQueryOptions): Promise;\n keys(request?: Request | string, options?: CacheQueryOptions): Promise;\n match(request: Request | string, options?: CacheQueryOptions): Promise;\n matchAll(request?: Request | string, options?: CacheQueryOptions): Promise;\n put(request: Request | string, response: Response): Promise;\n}\n\ndeclare var Cache: {\n prototype: Cache;\n new(): Cache;\n};\n\ninterface CacheStorage {\n delete(cacheName: string): Promise;\n has(cacheName: string): Promise;\n keys(): Promise;\n match(request: Request | string, options?: CacheQueryOptions): Promise;\n open(cacheName: string): Promise;\n}\n\ndeclare var CacheStorage: {\n prototype: CacheStorage;\n new(): CacheStorage;\n};\n\ninterface Canvas2DContextAttributes {\n alpha?: boolean;\n storage?: boolean;\n willReadFrequently?: boolean;\n [attribute: string]: boolean | string | undefined;\n}\n\ninterface CanvasGradient {\n addColorStop(offset: number, color: string): void;\n}\n\ndeclare var CanvasGradient: {\n prototype: CanvasGradient;\n new(): CanvasGradient;\n};\n\ninterface CanvasPathMethods {\n arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;\n bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;\n closePath(): void;\n ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n lineTo(x: number, y: number): void;\n moveTo(x: number, y: number): void;\n quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;\n rect(x: number, y: number, w: number, h: number): void;\n}\n\ninterface CanvasPattern {\n setTransform(matrix: SVGMatrix): void;\n}\n\ndeclare var CanvasPattern: {\n prototype: CanvasPattern;\n new(): CanvasPattern;\n};\n\ninterface CanvasRenderingContext2D extends CanvasPathMethods {\n readonly canvas: HTMLCanvasElement;\n fillStyle: string | CanvasGradient | CanvasPattern;\n font: string;\n globalAlpha: number;\n globalCompositeOperation: string;\n imageSmoothingEnabled: boolean;\n lineCap: string;\n lineDashOffset: number;\n lineJoin: string;\n lineWidth: number;\n miterLimit: number;\n mozImageSmoothingEnabled: boolean;\n msFillRule: CanvasFillRule;\n oImageSmoothingEnabled: boolean;\n shadowBlur: number;\n shadowColor: string;\n shadowOffsetX: number;\n shadowOffsetY: number;\n strokeStyle: string | CanvasGradient | CanvasPattern;\n textAlign: string;\n textBaseline: string;\n webkitImageSmoothingEnabled: boolean;\n beginPath(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n clip(fillRule?: CanvasFillRule): void;\n clip(path: Path2D, fillRule?: CanvasFillRule): void;\n createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;\n createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;\n drawFocusIfNeeded(element: Element): void;\n drawFocusIfNeeded(path: Path2D, element: Element): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void;\n fill(fillRule?: CanvasFillRule): void;\n fill(path: Path2D, fillRule?: CanvasFillRule): void;\n fillRect(x: number, y: number, w: number, h: number): void;\n fillText(text: string, x: number, y: number, maxWidth?: number): void;\n getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;\n getLineDash(): number[];\n isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n measureText(text: string): TextMetrics;\n putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void;\n restore(): void;\n rotate(angle: number): void;\n save(): void;\n scale(x: number, y: number): void;\n setLineDash(segments: number[]): void;\n setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n stroke(path?: Path2D): void;\n strokeRect(x: number, y: number, w: number, h: number): void;\n strokeText(text: string, x: number, y: number, maxWidth?: number): void;\n transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n translate(x: number, y: number): void;\n}\n\ndeclare var CanvasRenderingContext2D: {\n prototype: CanvasRenderingContext2D;\n new(): CanvasRenderingContext2D;\n};\n\ninterface ChannelMergerNode extends AudioNode {\n}\n\ndeclare var ChannelMergerNode: {\n prototype: ChannelMergerNode;\n new(): ChannelMergerNode;\n};\n\ninterface ChannelSplitterNode extends AudioNode {\n}\n\ndeclare var ChannelSplitterNode: {\n prototype: ChannelSplitterNode;\n new(): ChannelSplitterNode;\n};\n\ninterface CharacterData extends Node, ChildNode {\n data: string;\n readonly length: number;\n appendData(arg: string): void;\n deleteData(offset: number, count: number): void;\n insertData(offset: number, arg: string): void;\n replaceData(offset: number, count: number, arg: string): void;\n substringData(offset: number, count: number): string;\n}\n\ndeclare var CharacterData: {\n prototype: CharacterData;\n new(): CharacterData;\n};\n\ninterface ChildNode {\n remove(): void;\n}\n\ninterface ClientRect {\n bottom: number;\n readonly height: number;\n left: number;\n right: number;\n top: number;\n readonly width: number;\n}\n\ndeclare var ClientRect: {\n prototype: ClientRect;\n new(): ClientRect;\n};\n\ninterface ClientRectList {\n readonly length: number;\n item(index: number): ClientRect;\n [index: number]: ClientRect;\n}\n\ndeclare var ClientRectList: {\n prototype: ClientRectList;\n new(): ClientRectList;\n};\n\ninterface ClipboardEvent extends Event {\n readonly clipboardData: DataTransfer;\n}\n\ndeclare var ClipboardEvent: {\n prototype: ClipboardEvent;\n new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;\n};\n\ninterface ClipboardEventInit extends EventInit {\n data?: string;\n dataType?: string;\n}\n\ninterface CloseEvent extends Event {\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n /** @deprecated */\n initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;\n}\n\ndeclare var CloseEvent: {\n prototype: CloseEvent;\n new(type: string, eventInitDict?: CloseEventInit): CloseEvent;\n};\n\ninterface Comment extends CharacterData {\n text: string;\n}\n\ndeclare var Comment: {\n prototype: Comment;\n new(data?: string): Comment;\n};\n\ninterface CompositionEvent extends UIEvent {\n readonly data: string;\n readonly locale: string;\n initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void;\n}\n\ndeclare var CompositionEvent: {\n prototype: CompositionEvent;\n new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent;\n};\n\ninterface ComputedTimingProperties {\n activeDuration: number;\n currentIteration: number | null;\n endTime: number;\n localTime: number | null;\n progress: number | null;\n}\n\ninterface ConcatParams extends Algorithm {\n algorithmId: Uint8Array;\n hash?: string | Algorithm;\n partyUInfo: Uint8Array;\n partyVInfo: Uint8Array;\n privateInfo?: Uint8Array;\n publicInfo?: Uint8Array;\n}\n\ninterface Console {\n memory: any;\n assert(condition?: boolean, message?: string, ...data: any[]): void;\n clear(): void;\n count(label?: string): void;\n debug(message?: any, ...optionalParams: any[]): void;\n dir(value?: any, ...optionalParams: any[]): void;\n dirxml(value: any): void;\n error(message?: any, ...optionalParams: any[]): void;\n exception(message?: string, ...optionalParams: any[]): void;\n group(groupTitle?: string, ...optionalParams: any[]): void;\n groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;\n groupEnd(): void;\n info(message?: any, ...optionalParams: any[]): void;\n log(message?: any, ...optionalParams: any[]): void;\n markTimeline(label?: string): void;\n msIsIndependentlyComposed(element: Element): boolean;\n profile(reportName?: string): void;\n profileEnd(): void;\n select(element: Element): void;\n table(...tabularData: any[]): void;\n time(label?: string): void;\n timeEnd(label?: string): void;\n timeStamp(label?: string): void;\n timeline(label?: string): void;\n timelineEnd(label?: string): void;\n trace(message?: any, ...optionalParams: any[]): void;\n warn(message?: any, ...optionalParams: any[]): void;\n}\n\ndeclare var Console: {\n prototype: Console;\n new(): Console;\n};\n\ninterface ContentScriptGlobalScope extends EventTarget {\n readonly msContentScript: ExtensionScriptApis;\n readonly window: Window;\n}\n\ndeclare var ContentScriptGlobalScope: {\n prototype: ContentScriptGlobalScope;\n new(): ContentScriptGlobalScope;\n};\n\ninterface ConvolverNode extends AudioNode {\n buffer: AudioBuffer | null;\n normalize: boolean;\n}\n\ndeclare var ConvolverNode: {\n prototype: ConvolverNode;\n new(): ConvolverNode;\n};\n\ninterface Coordinates {\n readonly accuracy: number;\n readonly altitude: number | null;\n readonly altitudeAccuracy: number | null;\n readonly heading: number | null;\n readonly latitude: number;\n readonly longitude: number;\n readonly speed: number | null;\n}\n\ndeclare var Coordinates: {\n prototype: Coordinates;\n new(): Coordinates;\n};\n\ninterface CountQueuingStrategy {\n highWaterMark: number;\n size(): number;\n}\n\ndeclare var CountQueuingStrategy: {\n prototype: CountQueuingStrategy;\n new(strategy: QueuingStrategy): CountQueuingStrategy;\n};\n\ninterface Crypto {\n readonly subtle: SubtleCrypto;\n getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null;\n}\n\ndeclare var Crypto: {\n prototype: Crypto;\n new(): Crypto;\n};\n\ninterface CryptoKey {\n readonly algorithm: KeyAlgorithm;\n readonly extractable: boolean;\n readonly type: string;\n readonly usages: string[];\n}\n\ndeclare var CryptoKey: {\n prototype: CryptoKey;\n new(): CryptoKey;\n};\n\ninterface CryptoKeyPair {\n privateKey: CryptoKey;\n publicKey: CryptoKey;\n}\n\ndeclare var CryptoKeyPair: {\n prototype: CryptoKeyPair;\n new(): CryptoKeyPair;\n};\n\ninterface CustomElementRegistry {\n define(name: string, constructor: Function, options?: ElementDefinitionOptions): void;\n get(name: string): any;\n whenDefined(name: string): PromiseLike;\n}\n\ninterface CustomEvent extends Event {\n readonly detail: T;\n initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void;\n}\n\ndeclare var CustomEvent: {\n prototype: CustomEvent;\n new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent;\n};\n\ninterface DOMError {\n readonly name: string;\n toString(): string;\n}\n\ndeclare var DOMError: {\n prototype: DOMError;\n new(): DOMError;\n};\n\ninterface DOMException {\n readonly code: number;\n readonly message: string;\n readonly name: string;\n toString(): string;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly PARSE_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SERIALIZE_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n}\n\ndeclare var DOMException: {\n prototype: DOMException;\n new(message?: string, name?: string): DOMException;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly PARSE_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SERIALIZE_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n};\n\ninterface DOMImplementation {\n createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document;\n createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;\n createHTMLDocument(title?: string): Document;\n hasFeature(feature: string | null, version: string | null): boolean;\n}\n\ndeclare var DOMImplementation: {\n prototype: DOMImplementation;\n new(): DOMImplementation;\n};\n\ninterface DOML2DeprecatedColorProperty {\n color: string;\n}\n\ninterface DOML2DeprecatedSizeProperty {\n size: number;\n}\n\ninterface DOMParser {\n parseFromString(source: string, mimeType: string): Document;\n}\n\ndeclare var DOMParser: {\n prototype: DOMParser;\n new(): DOMParser;\n};\n\ninterface DOMRect extends DOMRectReadOnly {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var DOMRect: {\n prototype: DOMRect;\n new (x?: number, y?: number, width?: number, height?: number): DOMRect;\n fromRect(rectangle?: DOMRectInit): DOMRect;\n};\n\ninterface DOMRectList {\n readonly length: number;\n item(index: number): DOMRect | null;\n [index: number]: DOMRect;\n}\n\ninterface DOMRectReadOnly {\n readonly bottom: number;\n readonly height: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n}\n\ndeclare var DOMRectReadOnly: {\n prototype: DOMRectReadOnly;\n new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly;\n fromRect(rectangle?: DOMRectInit): DOMRectReadOnly;\n};\n\ninterface DOMSettableTokenList extends DOMTokenList {\n value: string;\n}\n\ndeclare var DOMSettableTokenList: {\n prototype: DOMSettableTokenList;\n new(): DOMSettableTokenList;\n};\n\ninterface DOMStringList {\n readonly length: number;\n contains(str: string): boolean;\n item(index: number): string | null;\n [index: number]: string;\n}\n\ndeclare var DOMStringList: {\n prototype: DOMStringList;\n new(): DOMStringList;\n};\n\ninterface DOMStringMap {\n [name: string]: string | undefined;\n}\n\ndeclare var DOMStringMap: {\n prototype: DOMStringMap;\n new(): DOMStringMap;\n};\n\ninterface DOMTokenList {\n readonly length: number;\n add(...tokens: string[]): void;\n contains(token: string): boolean;\n item(index: number): string | null;\n remove(...tokens: string[]): void;\n toString(): string;\n toggle(token: string, force?: boolean): boolean;\n [index: number]: string;\n}\n\ndeclare var DOMTokenList: {\n prototype: DOMTokenList;\n new(): DOMTokenList;\n};\n\ninterface DataCue extends TextTrackCue {\n data: ArrayBuffer;\n addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var DataCue: {\n prototype: DataCue;\n new(): DataCue;\n};\n\ninterface DataTransfer {\n dropEffect: string;\n effectAllowed: string;\n readonly files: FileList;\n readonly items: DataTransferItemList;\n readonly types: string[];\n clearData(format?: string): boolean;\n getData(format: string): string;\n setData(format: string, data: string): boolean;\n setDragImage(image: Element, x: number, y: number): void;\n}\n\ndeclare var DataTransfer: {\n prototype: DataTransfer;\n new(): DataTransfer;\n};\n\ninterface DataTransferItem {\n readonly kind: string;\n readonly type: string;\n getAsFile(): File | null;\n getAsString(_callback: FunctionStringCallback | null): void;\n webkitGetAsEntry(): any;\n}\n\ndeclare var DataTransferItem: {\n prototype: DataTransferItem;\n new(): DataTransferItem;\n};\n\ninterface DataTransferItemList {\n readonly length: number;\n add(data: File): DataTransferItem | null;\n add(data: string, type: string): DataTransferItem | null;\n clear(): void;\n item(index: number): DataTransferItem;\n remove(index: number): void;\n [name: number]: DataTransferItem;\n}\n\ndeclare var DataTransferItemList: {\n prototype: DataTransferItemList;\n new(): DataTransferItemList;\n};\n\ninterface DeferredPermissionRequest {\n readonly id: number;\n readonly type: MSWebViewPermissionType;\n readonly uri: string;\n allow(): void;\n deny(): void;\n}\n\ndeclare var DeferredPermissionRequest: {\n prototype: DeferredPermissionRequest;\n new(): DeferredPermissionRequest;\n};\n\ninterface DelayNode extends AudioNode {\n readonly delayTime: AudioParam;\n}\n\ndeclare var DelayNode: {\n prototype: DelayNode;\n new(): DelayNode;\n};\n\ninterface DeviceAcceleration {\n readonly x: number | null;\n readonly y: number | null;\n readonly z: number | null;\n}\n\ndeclare var DeviceAcceleration: {\n prototype: DeviceAcceleration;\n new(): DeviceAcceleration;\n};\n\ninterface DeviceLightEvent extends Event {\n readonly value: number;\n}\n\ndeclare var DeviceLightEvent: {\n prototype: DeviceLightEvent;\n new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;\n};\n\ninterface DeviceMotionEvent extends Event {\n readonly acceleration: DeviceAcceleration | null;\n readonly accelerationIncludingGravity: DeviceAcceleration | null;\n readonly interval: number | null;\n readonly rotationRate: DeviceRotationRate | null;\n initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void;\n}\n\ndeclare var DeviceMotionEvent: {\n prototype: DeviceMotionEvent;\n new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;\n};\n\ninterface DeviceOrientationEvent extends Event {\n readonly absolute: boolean;\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void;\n}\n\ndeclare var DeviceOrientationEvent: {\n prototype: DeviceOrientationEvent;\n new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;\n};\n\ninterface DeviceRotationRate {\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n}\n\ndeclare var DeviceRotationRate: {\n prototype: DeviceRotationRate;\n new(): DeviceRotationRate;\n};\n\ninterface DhImportKeyParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyAlgorithm extends KeyAlgorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface DhKeyGenParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DocumentEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforedeactivate\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"fullscreenchange\": Event;\n \"fullscreenerror\": Event;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSManipulationStateChanged\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"mssitemodejumplistitemremoved\": Event;\n \"msthumbnailclick\": Event;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"pointerlockchange\": Event;\n \"pointerlockerror\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectionchange\": Event;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"stop\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent {\n /**\n * Sets or gets the URL for the current document.\n */\n readonly URL: string;\n /**\n * Gets the URL for the document, stripped of any character encoding.\n */\n readonly URLUnencoded: string;\n /**\n * Gets the object that has the focus when the parent document has focus.\n */\n readonly activeElement: Element;\n /**\n * Sets or gets the color of all active links in the document.\n */\n alinkColor: string;\n /**\n * Returns a reference to the collection of elements contained by the object.\n */\n readonly all: HTMLAllCollection;\n /**\n * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order.\n */\n readonly anchors: HTMLCollectionOf;\n /**\n * Retrieves a collection of all applet objects in the document.\n */\n readonly applets: HTMLCollectionOf;\n /**\n * Deprecated. Sets or retrieves a value that indicates the background color behind the object.\n */\n bgColor: string;\n /**\n * Specifies the beginning and end of the document body.\n */\n body: HTMLElement;\n readonly characterSet: string;\n /**\n * Gets or sets the character set used to encode the object.\n */\n charset: string;\n /**\n * Gets a value that indicates whether standards-compliant mode is switched on for the object.\n */\n readonly compatMode: string;\n cookie: string;\n readonly currentScript: HTMLScriptElement | SVGScriptElement | null;\n readonly defaultView: Window;\n /**\n * Sets or gets a value that indicates whether the document can be edited.\n */\n designMode: string;\n /**\n * Sets or retrieves a value that indicates the reading order of the object.\n */\n dir: string;\n /**\n * Gets an object representing the document type declaration associated with the current document.\n */\n readonly doctype: DocumentType;\n /**\n * Gets a reference to the root node of the document.\n */\n readonly documentElement: HTMLElement;\n /**\n * Sets or gets the security domain of the document.\n */\n domain: string;\n /**\n * Retrieves a collection of all embed objects in the document.\n */\n readonly embeds: HTMLCollectionOf;\n /**\n * Sets or gets the foreground (text) color of the document.\n */\n fgColor: string;\n /**\n * Retrieves a collection, in source order, of all form objects in the document.\n */\n readonly forms: HTMLCollectionOf;\n readonly fullscreenElement: Element | null;\n readonly fullscreenEnabled: boolean;\n readonly head: HTMLHeadElement;\n readonly hidden: boolean;\n /**\n * Retrieves a collection, in source order, of img objects in the document.\n */\n readonly images: HTMLCollectionOf;\n /**\n * Gets the implementation object of the current document.\n */\n readonly implementation: DOMImplementation;\n /**\n * Returns the character encoding used to create the webpage that is loaded into the document object.\n */\n readonly inputEncoding: string | null;\n /**\n * Gets the date that the page was last modified, if the page supplies one.\n */\n readonly lastModified: string;\n /**\n * Sets or gets the color of the document links.\n */\n linkColor: string;\n /**\n * Retrieves a collection of all a objects that specify the href property and all area objects in the document.\n */\n readonly links: HTMLCollectionOf;\n /**\n * Contains information about the current URL.\n */\n location: Location;\n msCSSOMElementFloatMetrics: boolean;\n msCapsLockWarningOff: boolean;\n /**\n * Fires when the user aborts the download.\n * @param ev The event.\n */\n onabort: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the object is set as the active element.\n * @param ev The event.\n */\n onactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the object is set as the active element.\n * @param ev The event.\n */\n onbeforeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the activeElement is changed from the current object to another object in the parent document.\n * @param ev The event.\n */\n onbeforedeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the object loses the input focus.\n * @param ev The focus event.\n */\n onblur: ((this: Document, ev: FocusEvent) => any) | null;\n /**\n * Occurs when playback is possible, but would require further buffering.\n * @param ev The event.\n */\n oncanplay: ((this: Document, ev: Event) => any) | null;\n oncanplaythrough: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the contents of the object or selection have changed.\n * @param ev The event.\n */\n onchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the left mouse button on the object\n * @param ev The mouse event.\n */\n onclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user clicks the right mouse button in the client area, opening the context menu.\n * @param ev The mouse event.\n */\n oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null;\n /**\n * Fires when the user double-clicks the object.\n * @param ev The mouse event.\n */\n ondblclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the activeElement is changed from the current object to another object in the parent document.\n * @param ev The UI Event\n */\n ondeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires on the source object continuously during a drag operation.\n * @param ev The event.\n */\n ondrag: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user releases the mouse at the close of a drag operation.\n * @param ev The event.\n */\n ondragend: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element when the user drags the object to a valid drop target.\n * @param ev The drag event.\n */\n ondragenter: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.\n * @param ev The drag event.\n */\n ondragleave: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element continuously while the user drags the object over a valid drop target.\n * @param ev The event.\n */\n ondragover: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user starts to drag a text selection or selected object.\n * @param ev The event.\n */\n ondragstart: ((this: Document, ev: DragEvent) => any) | null;\n ondrop: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Occurs when the duration attribute is updated.\n * @param ev The event.\n */\n ondurationchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the media element is reset to its initial state.\n * @param ev The event.\n */\n onemptied: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the end of playback is reached.\n * @param ev The event\n */\n onended: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when an error occurs during object loading.\n * @param ev The event.\n */\n onerror: ((this: Document, ev: ErrorEvent) => any) | null;\n /**\n * Fires when the object receives focus.\n * @param ev The event.\n */\n onfocus: ((this: Document, ev: FocusEvent) => any) | null;\n onfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onfullscreenerror: ((this: Document, ev: Event) => any) | null;\n oninput: ((this: Document, ev: Event) => any) | null;\n oninvalid: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user presses a key.\n * @param ev The keyboard event\n */\n onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user presses an alphanumeric key.\n * @param ev The event.\n */\n onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user releases a key.\n * @param ev The keyboard event\n */\n onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires immediately after the browser loads the object.\n * @param ev The event.\n */\n onload: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when media data is loaded at the current playback position.\n * @param ev The event.\n */\n onloadeddata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the duration and dimensions of the media have been determined.\n * @param ev The event.\n */\n onloadedmetadata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when Internet Explorer begins looking for media data.\n * @param ev The event.\n */\n onloadstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the object with either mouse button.\n * @param ev The mouse event.\n */\n onmousedown: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse over the object.\n * @param ev The mouse event.\n */\n onmousemove: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer outside the boundaries of the object.\n * @param ev The mouse event.\n */\n onmouseout: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer into the object.\n * @param ev The mouse event.\n */\n onmouseover: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user releases a mouse button while the mouse is over the object.\n * @param ev The mouse event.\n */\n onmouseup: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the wheel button is rotated.\n * @param ev The mouse event\n */\n onmousewheel: ((this: Document, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: Document, ev: Event) => any) | null;\n onmsgesturechange: ((this: Document, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null;\n onmsgestureend: ((this: Document, ev: Event) => any) | null;\n onmsgesturehold: ((this: Document, ev: Event) => any) | null;\n onmsgesturestart: ((this: Document, ev: Event) => any) | null;\n onmsgesturetap: ((this: Document, ev: Event) => any) | null;\n onmsinertiastart: ((this: Document, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null;\n onmspointercancel: ((this: Document, ev: Event) => any) | null;\n onmspointerdown: ((this: Document, ev: Event) => any) | null;\n onmspointerenter: ((this: Document, ev: Event) => any) | null;\n onmspointerleave: ((this: Document, ev: Event) => any) | null;\n onmspointermove: ((this: Document, ev: Event) => any) | null;\n onmspointerout: ((this: Document, ev: Event) => any) | null;\n onmspointerover: ((this: Document, ev: Event) => any) | null;\n onmspointerup: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when an item is removed from a Jump List of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmsthumbnailclick: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback is paused.\n * @param ev The event.\n */\n onpause: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the play method is requested.\n * @param ev The event.\n */\n onplay: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the audio or video has started playing.\n * @param ev The event.\n */\n onplaying: ((this: Document, ev: Event) => any) | null;\n onpointerlockchange: ((this: Document, ev: Event) => any) | null;\n onpointerlockerror: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate progress while downloading media data.\n * @param ev The event.\n */\n onprogress: ((this: Document, ev: ProgressEvent) => any) | null;\n /**\n * Occurs when the playback rate is increased or decreased.\n * @param ev The event.\n */\n onratechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the state of the object has changed.\n * @param ev The event\n */\n onreadystatechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user resets a form.\n * @param ev The event.\n */\n onreset: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user repositions the scroll box in the scroll bar on the object.\n * @param ev The event.\n */\n onscroll: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Occurs when the seek operation ends.\n * @param ev The event.\n */\n onseeked: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the current playback position is moved.\n * @param ev The event.\n */\n onseeking: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the current selection changes.\n * @param ev The event.\n */\n onselect: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the selection state of a document changes.\n * @param ev The event.\n */\n onselectionchange: ((this: Document, ev: Event) => any) | null;\n onselectstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the download has stopped.\n * @param ev The event.\n */\n onstalled: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the Stop button or leaves the Web page.\n * @param ev The event.\n */\n onstop: ((this: Document, ev: Event) => any) | null;\n onsubmit: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs if the load operation has been intentionally halted.\n * @param ev The event.\n */\n onsuspend: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate the current playback position.\n * @param ev The event.\n */\n ontimeupdate: ((this: Document, ev: Event) => any) | null;\n ontouchcancel: ((this: Document, ev: Event) => any) | null;\n ontouchend: ((this: Document, ev: Event) => any) | null;\n ontouchmove: ((this: Document, ev: Event) => any) | null;\n ontouchstart: ((this: Document, ev: Event) => any) | null;\n onvisibilitychange: (this: Document, ev: Event) => any;\n /**\n * Occurs when the volume is changed, or playback is muted or unmuted.\n * @param ev The event.\n */\n onvolumechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback stops because the next frame of a video resource is not available.\n * @param ev The event.\n */\n onwaiting: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null;\n readonly plugins: HTMLCollectionOf;\n readonly pointerLockElement: Element;\n /**\n * Retrieves a value that indicates the current state of the object.\n */\n readonly readyState: string;\n /**\n * Gets the URL of the location that referred the user to the current page.\n */\n readonly referrer: string;\n /**\n * Gets the root svg element in the document hierarchy.\n */\n readonly rootElement: SVGSVGElement;\n /**\n * Retrieves a collection of all script objects in the document.\n */\n readonly scripts: HTMLCollectionOf;\n readonly scrollingElement: Element | null;\n /**\n * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document.\n */\n readonly styleSheets: StyleSheetList;\n /**\n * Contains the title of the document.\n */\n title: string;\n readonly visibilityState: VisibilityState;\n /**\n * Sets or gets the color of the links that the user has visited.\n */\n vlinkColor: string;\n readonly webkitCurrentFullScreenElement: Element | null;\n readonly webkitFullscreenElement: Element | null;\n readonly webkitFullscreenEnabled: boolean;\n readonly webkitIsFullScreen: boolean;\n readonly xmlEncoding: string | null;\n xmlStandalone: boolean;\n /**\n * Gets or sets the version attribute specified in the declaration of an XML document.\n */\n xmlVersion: string | null;\n adoptNode(source: T): T;\n captureEvents(): void;\n caretRangeFromPoint(x: number, y: number): Range;\n clear(): void;\n /**\n * Closes an output stream and forces the sent data to display.\n */\n close(): void;\n /**\n * Creates an attribute object with a specified name.\n * @param name String that sets the attribute object's name.\n */\n createAttribute(name: string): Attr;\n createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;\n createCDATASection(data: string): CDATASection;\n /**\n * Creates a comment object with the specified data.\n * @param data Sets the comment object's data.\n */\n createComment(data: string): Comment;\n /**\n * Creates a new document.\n */\n createDocumentFragment(): DocumentFragment;\n /**\n * Creates an instance of the element for the specified tag.\n * @param tagName The name of an element.\n */\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];\n createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", qualifiedName: string): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"a\"): SVGAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"circle\"): SVGCircleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"clipPath\"): SVGClipPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"componentTransferFunction\"): SVGComponentTransferFunctionElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"defs\"): SVGDefsElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"desc\"): SVGDescElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"ellipse\"): SVGEllipseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feBlend\"): SVGFEBlendElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feColorMatrix\"): SVGFEColorMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComponentTransfer\"): SVGFEComponentTransferElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComposite\"): SVGFECompositeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feConvolveMatrix\"): SVGFEConvolveMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDiffuseLighting\"): SVGFEDiffuseLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDisplacementMap\"): SVGFEDisplacementMapElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDistantLight\"): SVGFEDistantLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFlood\"): SVGFEFloodElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncA\"): SVGFEFuncAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncB\"): SVGFEFuncBElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncG\"): SVGFEFuncGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncR\"): SVGFEFuncRElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feGaussianBlur\"): SVGFEGaussianBlurElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feImage\"): SVGFEImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMerge\"): SVGFEMergeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMergeNode\"): SVGFEMergeNodeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMorphology\"): SVGFEMorphologyElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feOffset\"): SVGFEOffsetElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"fePointLight\"): SVGFEPointLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpecularLighting\"): SVGFESpecularLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpotLight\"): SVGFESpotLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTile\"): SVGFETileElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTurbulence\"): SVGFETurbulenceElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"filter\"): SVGFilterElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"foreignObject\"): SVGForeignObjectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"g\"): SVGGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"image\"): SVGImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"gradient\"): SVGGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"line\"): SVGLineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"linearGradient\"): SVGLinearGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"marker\"): SVGMarkerElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"mask\"): SVGMaskElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"path\"): SVGPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"metadata\"): SVGMetadataElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"pattern\"): SVGPatternElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polygon\"): SVGPolygonElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polyline\"): SVGPolylineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"radialGradient\"): SVGRadialGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"rect\"): SVGRectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"svg\"): SVGSVGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"script\"): SVGScriptElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"stop\"): SVGStopElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"style\"): SVGStyleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"switch\"): SVGSwitchElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"symbol\"): SVGSymbolElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"tspan\"): SVGTSpanElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textContent\"): SVGTextContentElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"text\"): SVGTextElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPath\"): SVGTextPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPositioning\"): SVGTextPositioningElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"title\"): SVGTitleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"use\"): SVGUseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"view\"): SVGViewElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: string): SVGElement;\n createElementNS(namespaceURI: string | null, qualifiedName: string): Element;\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver: Node): XPathNSResolver;\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list\n * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator;\n createProcessingInstruction(target: string, data: string): ProcessingInstruction;\n /**\n * Returns an empty range object that has both of its boundary points positioned at the beginning of the document.\n */\n createRange(): Range;\n /**\n * Creates a text string from the specified value.\n * @param data String that specifies the nodeValue property of the text node.\n */\n createTextNode(data: string): Text;\n createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch;\n createTouchList(...touches: Touch[]): TouchList;\n /**\n * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow.\n * @param filter A custom NodeFilter function to use.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker;\n /**\n * Returns the element for the specified x coordinate and the specified y coordinate.\n * @param x The x-offset\n * @param y The y-offset\n */\n elementFromPoint(x: number, y: number): Element;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n /**\n * Executes a command on the current document, current selection, or the given range.\n * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.\n * @param showUI Display the user interface, defaults to false.\n * @param value Value to assign.\n */\n execCommand(commandId: string, showUI?: boolean, value?: any): boolean;\n /**\n * Displays help information for the given command identifier.\n * @param commandId Displays help information for the given command identifier.\n */\n execCommandShowHelp(commandId: string): boolean;\n exitFullscreen(): void;\n exitPointerLock(): void;\n /**\n * Causes the element to receive the focus and executes the code specified by the onfocus event.\n */\n /** @deprecated */\n focus(): void;\n /**\n * Returns a reference to the first object with the specified value of the ID or NAME attribute.\n * @param elementId String that specifies the ID value. Case-insensitive.\n */\n getElementById(elementId: string): HTMLElement | null;\n getElementsByClassName(classNames: string): HTMLCollectionOf;\n /**\n * Gets a collection of objects based on the value of the NAME or ID attribute.\n * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.\n */\n getElementsByName(elementName: string): NodeListOf;\n /**\n * Retrieves a collection of objects based on the specified element name.\n * @param name Specifies the name of an element.\n */\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n /**\n * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.\n */\n getSelection(): Selection;\n /**\n * Gets a value indicating whether the object currently has focus.\n */\n hasFocus(): boolean;\n importNode(importedNode: T, deep: boolean): T;\n msElementsFromPoint(x: number, y: number): NodeListOf;\n msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf;\n /**\n * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method.\n * @param url Specifies a MIME type for the document.\n * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.\n * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, \"fullscreen=yes, toolbar=yes\"). The following values are supported.\n * @param replace Specifies whether the existing entry for the document is replaced in the history list.\n */\n open(url?: string, name?: string, features?: string, replace?: boolean): Document;\n /**\n * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.\n * @param commandId Specifies a command identifier.\n */\n queryCommandEnabled(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the specified command is in the indeterminate state.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandIndeterm(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates the current state of the command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandState(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the current command is supported on the current range.\n * @param commandId Specifies a command identifier.\n */\n queryCommandSupported(commandId: string): boolean;\n /**\n * Retrieves the string associated with a command.\n * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers.\n */\n queryCommandText(commandId: string): string;\n /**\n * Returns the current value of the document, range, or current selection for the given command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandValue(commandId: string): string;\n releaseEvents(): void;\n webkitCancelFullScreen(): void;\n webkitExitFullscreen(): void;\n /**\n * Writes one or more HTML expressions to a document in the specified window.\n * @param content Specifies the text and HTML tags to write.\n */\n write(...content: string[]): void;\n /**\n * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window.\n * @param content The text and HTML tags to write.\n */\n writeln(...content: string[]): void;\n addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Document: {\n prototype: Document;\n new(): Document;\n};\n\ninterface DocumentEvent {\n createEvent(eventInterface: \"AnimationEvent\"): AnimationEvent;\n createEvent(eventInterface: \"AnimationPlaybackEvent\"): AnimationPlaybackEvent;\n createEvent(eventInterface: \"AudioProcessingEvent\"): AudioProcessingEvent;\n createEvent(eventInterface: \"BeforeUnloadEvent\"): BeforeUnloadEvent;\n createEvent(eventInterface: \"ClipboardEvent\"): ClipboardEvent;\n createEvent(eventInterface: \"CloseEvent\"): CloseEvent;\n createEvent(eventInterface: \"CompositionEvent\"): CompositionEvent;\n createEvent(eventInterface: \"CustomEvent\"): CustomEvent;\n createEvent(eventInterface: \"DeviceLightEvent\"): DeviceLightEvent;\n createEvent(eventInterface: \"DeviceMotionEvent\"): DeviceMotionEvent;\n createEvent(eventInterface: \"DeviceOrientationEvent\"): DeviceOrientationEvent;\n createEvent(eventInterface: \"DragEvent\"): DragEvent;\n createEvent(eventInterface: \"ErrorEvent\"): ErrorEvent;\n createEvent(eventInterface: \"Event\"): Event;\n createEvent(eventInterface: \"Events\"): Event;\n createEvent(eventInterface: \"FocusEvent\"): FocusEvent;\n createEvent(eventInterface: \"FocusNavigationEvent\"): FocusNavigationEvent;\n createEvent(eventInterface: \"GamepadEvent\"): GamepadEvent;\n createEvent(eventInterface: \"HashChangeEvent\"): HashChangeEvent;\n createEvent(eventInterface: \"IDBVersionChangeEvent\"): IDBVersionChangeEvent;\n createEvent(eventInterface: \"KeyboardEvent\"): KeyboardEvent;\n createEvent(eventInterface: \"ListeningStateChangedEvent\"): ListeningStateChangedEvent;\n createEvent(eventInterface: \"MSDCCEvent\"): MSDCCEvent;\n createEvent(eventInterface: \"MSDSHEvent\"): MSDSHEvent;\n createEvent(eventInterface: \"MSMediaKeyMessageEvent\"): MSMediaKeyMessageEvent;\n createEvent(eventInterface: \"MSMediaKeyNeededEvent\"): MSMediaKeyNeededEvent;\n createEvent(eventInterface: \"MediaEncryptedEvent\"): MediaEncryptedEvent;\n createEvent(eventInterface: \"MediaKeyMessageEvent\"): MediaKeyMessageEvent;\n createEvent(eventInterface: \"MediaStreamErrorEvent\"): MediaStreamErrorEvent;\n createEvent(eventInterface: \"MediaStreamEvent\"): MediaStreamEvent;\n createEvent(eventInterface: \"MediaStreamTrackEvent\"): MediaStreamTrackEvent;\n createEvent(eventInterface: \"MessageEvent\"): MessageEvent;\n createEvent(eventInterface: \"MouseEvent\"): MouseEvent;\n createEvent(eventInterface: \"MouseEvents\"): MouseEvent;\n createEvent(eventInterface: \"MutationEvent\"): MutationEvent;\n createEvent(eventInterface: \"MutationEvents\"): MutationEvent;\n createEvent(eventInterface: \"OfflineAudioCompletionEvent\"): OfflineAudioCompletionEvent;\n createEvent(eventInterface: \"OverflowEvent\"): OverflowEvent;\n createEvent(eventInterface: \"PageTransitionEvent\"): PageTransitionEvent;\n createEvent(eventInterface: \"PaymentRequestUpdateEvent\"): PaymentRequestUpdateEvent;\n createEvent(eventInterface: \"PermissionRequestedEvent\"): PermissionRequestedEvent;\n createEvent(eventInterface: \"PointerEvent\"): PointerEvent;\n createEvent(eventInterface: \"PopStateEvent\"): PopStateEvent;\n createEvent(eventInterface: \"ProgressEvent\"): ProgressEvent;\n createEvent(eventInterface: \"PromiseRejectionEvent\"): PromiseRejectionEvent;\n createEvent(eventInterface: \"RTCDTMFToneChangeEvent\"): RTCDTMFToneChangeEvent;\n createEvent(eventInterface: \"RTCDtlsTransportStateChangedEvent\"): RTCDtlsTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCIceCandidatePairChangedEvent\"): RTCIceCandidatePairChangedEvent;\n createEvent(eventInterface: \"RTCIceGathererEvent\"): RTCIceGathererEvent;\n createEvent(eventInterface: \"RTCIceTransportStateChangedEvent\"): RTCIceTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceEvent\"): RTCPeerConnectionIceEvent;\n createEvent(eventInterface: \"RTCSsrcConflictEvent\"): RTCSsrcConflictEvent;\n createEvent(eventInterface: \"SVGZoomEvent\"): SVGZoomEvent;\n createEvent(eventInterface: \"SVGZoomEvents\"): SVGZoomEvent;\n createEvent(eventInterface: \"SecurityPolicyViolationEvent\"): SecurityPolicyViolationEvent;\n createEvent(eventInterface: \"ServiceWorkerMessageEvent\"): ServiceWorkerMessageEvent;\n createEvent(eventInterface: \"SpeechSynthesisEvent\"): SpeechSynthesisEvent;\n createEvent(eventInterface: \"StorageEvent\"): StorageEvent;\n createEvent(eventInterface: \"TextEvent\"): TextEvent;\n createEvent(eventInterface: \"TrackEvent\"): TrackEvent;\n createEvent(eventInterface: \"TransitionEvent\"): TransitionEvent;\n createEvent(eventInterface: \"UIEvent\"): UIEvent;\n createEvent(eventInterface: \"UIEvents\"): UIEvent;\n createEvent(eventInterface: \"VRDisplayEvent\"): VRDisplayEvent;\n createEvent(eventInterface: \"VRDisplayEvent \"): VRDisplayEvent ;\n createEvent(eventInterface: \"WebGLContextEvent\"): WebGLContextEvent;\n createEvent(eventInterface: \"WheelEvent\"): WheelEvent;\n createEvent(eventInterface: string): Event;\n}\n\ninterface DocumentFragment extends Node, ParentNode {\n getElementById(elementId: string): HTMLElement | null;\n}\n\ndeclare var DocumentFragment: {\n prototype: DocumentFragment;\n new(): DocumentFragment;\n};\n\ninterface DocumentOrShadowRoot {\n readonly activeElement: Element | null;\n readonly styleSheets: StyleSheetList;\n elementFromPoint(x: number, y: number): Element | null;\n elementsFromPoint(x: number, y: number): Element[];\n getSelection(): Selection | null;\n}\n\ninterface DocumentType extends Node, ChildNode {\n readonly entities: NamedNodeMap;\n readonly internalSubset: string | null;\n readonly name: string;\n readonly notations: NamedNodeMap;\n readonly publicId: string;\n readonly systemId: string;\n}\n\ndeclare var DocumentType: {\n prototype: DocumentType;\n new(): DocumentType;\n};\n\ninterface DragEvent extends MouseEvent {\n readonly dataTransfer: DataTransfer;\n initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void;\n msConvertURL(file: File, targetType: string, targetURL?: string): void;\n}\n\ndeclare var DragEvent: {\n prototype: DragEvent;\n new(type: \"drag\" | \"dragend\" | \"dragenter\" | \"dragexit\" | \"dragleave\" | \"dragover\" | \"dragstart\" | \"drop\", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent;\n};\n\ninterface DynamicsCompressorNode extends AudioNode {\n readonly attack: AudioParam;\n readonly knee: AudioParam;\n readonly ratio: AudioParam;\n readonly reduction: number;\n readonly release: AudioParam;\n readonly threshold: AudioParam;\n}\n\ndeclare var DynamicsCompressorNode: {\n prototype: DynamicsCompressorNode;\n new(): DynamicsCompressorNode;\n};\n\ninterface EXT_blend_minmax {\n readonly MAX_EXT: number;\n readonly MIN_EXT: number;\n}\n\ninterface EXT_frag_depth {\n}\n\ninterface EXT_sRGB {\n readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number;\n readonly SRGB8_ALPHA8_EXT: number;\n readonly SRGB_ALPHA_EXT: number;\n readonly SRGB_EXT: number;\n}\n\ninterface EXT_shader_texture_lod {\n}\n\ninterface EXT_texture_filter_anisotropic {\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n}\n\ndeclare var EXT_texture_filter_anisotropic: {\n prototype: EXT_texture_filter_anisotropic;\n new(): EXT_texture_filter_anisotropic;\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n};\n\ninterface ElementEventMap extends GlobalEventHandlersEventMap {\n \"ariarequest\": Event;\n \"command\": Event;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSGotPointerCapture\": Event;\n \"MSInertiaStart\": Event;\n \"MSLostPointerCapture\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly attributes: NamedNodeMap;\n readonly classList: DOMTokenList;\n className: string;\n readonly clientHeight: number;\n readonly clientLeft: number;\n readonly clientTop: number;\n readonly clientWidth: number;\n id: string;\n innerHTML: string;\n msContentZoomFactor: number;\n readonly msRegionOverflow: string;\n onariarequest: ((this: Element, ev: Event) => any) | null;\n oncommand: ((this: Element, ev: Event) => any) | null;\n ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null;\n onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null;\n onmsgesturechange: ((this: Element, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null;\n onmsgestureend: ((this: Element, ev: Event) => any) | null;\n onmsgesturehold: ((this: Element, ev: Event) => any) | null;\n onmsgesturestart: ((this: Element, ev: Event) => any) | null;\n onmsgesturetap: ((this: Element, ev: Event) => any) | null;\n onmsgotpointercapture: ((this: Element, ev: Event) => any) | null;\n onmsinertiastart: ((this: Element, ev: Event) => any) | null;\n onmslostpointercapture: ((this: Element, ev: Event) => any) | null;\n onmspointercancel: ((this: Element, ev: Event) => any) | null;\n onmspointerdown: ((this: Element, ev: Event) => any) | null;\n onmspointerenter: ((this: Element, ev: Event) => any) | null;\n onmspointerleave: ((this: Element, ev: Event) => any) | null;\n onmspointermove: ((this: Element, ev: Event) => any) | null;\n onmspointerout: ((this: Element, ev: Event) => any) | null;\n onmspointerover: ((this: Element, ev: Event) => any) | null;\n onmspointerup: ((this: Element, ev: Event) => any) | null;\n ontouchcancel: ((this: Element, ev: Event) => any) | null;\n ontouchend: ((this: Element, ev: Event) => any) | null;\n ontouchmove: ((this: Element, ev: Event) => any) | null;\n ontouchstart: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null;\n outerHTML: string;\n readonly prefix: string | null;\n readonly scrollHeight: number;\n scrollLeft: number;\n scrollTop: number;\n readonly scrollWidth: number;\n readonly shadowRoot: ShadowRoot | null;\n slot: string;\n readonly tagName: string;\n attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;\n closest(selector: K): HTMLElementTagNameMap[K] | null;\n closest(selector: K): SVGElementTagNameMap[K] | null;\n closest(selector: string): Element | null;\n getAttribute(qualifiedName: string): string | null;\n getAttributeNS(namespaceURI: string, localName: string): string;\n getAttributeNode(name: string): Attr | null;\n getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n getElementsByClassName(classNames: string): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n hasAttribute(name: string): boolean;\n hasAttributeNS(namespaceURI: string, localName: string): boolean;\n hasAttributes(): boolean;\n insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null;\n insertAdjacentHTML(where: InsertPosition, html: string): void;\n insertAdjacentText(where: InsertPosition, text: string): void;\n matches(selectors: string): boolean;\n msGetRegionContent(): any;\n msGetUntransformedBounds(): ClientRect;\n msMatchesSelector(selectors: string): boolean;\n msReleasePointerCapture(pointerId: number): void;\n msSetPointerCapture(pointerId: number): void;\n msZoomTo(args: MsZoomToOptions): void;\n releasePointerCapture(pointerId: number): void;\n removeAttribute(qualifiedName: string): void;\n removeAttributeNS(namespaceURI: string, localName: string): void;\n removeAttributeNode(oldAttr: Attr): Attr;\n requestFullscreen(): void;\n requestPointerLock(): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x: number, y: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x: number, y: number): void;\n scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x: number, y: number): void;\n setAttribute(qualifiedName: string, value: string): void;\n setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;\n setAttributeNode(newAttr: Attr): Attr;\n setAttributeNodeNS(newAttr: Attr): Attr;\n setPointerCapture(pointerId: number): void;\n webkitMatchesSelector(selectors: string): boolean;\n webkitRequestFullScreen(): void;\n webkitRequestFullscreen(): void;\n addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Element: {\n prototype: Element;\n new(): Element;\n};\n\ninterface ElementCSSInlineStyle {\n readonly style: CSSStyleDeclaration;\n}\n\ninterface ElementCreationOptions {\n is?: string;\n}\n\ninterface ElementDefinitionOptions {\n extends: string;\n}\n\ninterface ElementTraversal {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n readonly nextElementSibling: Element | null;\n readonly previousElementSibling: Element | null;\n}\n\ninterface ErrorEvent extends Event {\n readonly colno: number;\n readonly error: any;\n readonly filename: string;\n readonly lineno: number;\n readonly message: string;\n initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;\n}\n\ndeclare var ErrorEvent: {\n prototype: ErrorEvent;\n new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent;\n};\n\ninterface Event {\n readonly bubbles: boolean;\n cancelBubble: boolean;\n readonly cancelable: boolean;\n readonly currentTarget: EventTarget | null;\n readonly defaultPrevented: boolean;\n readonly eventPhase: number;\n readonly isTrusted: boolean;\n returnValue: boolean;\n readonly scoped: boolean;\n readonly srcElement: Element | null;\n readonly target: EventTarget | null;\n readonly timeStamp: number;\n readonly type: string;\n deepPath(): EventTarget[];\n initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;\n preventDefault(): void;\n stopImmediatePropagation(): void;\n stopPropagation(): void;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n}\n\ndeclare var Event: {\n prototype: Event;\n new(typeArg: string, eventInitDict?: EventInit): Event;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n};\n\ninterface EventListenerObject {\n handleEvent(evt: Event): void;\n}\n\ninterface EventSource extends EventTarget {\n readonly CLOSED: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n onerror: (evt: MessageEvent) => any;\n onmessage: (evt: MessageEvent) => any;\n onopen: (evt: MessageEvent) => any;\n readonly readyState: number;\n readonly url: string;\n readonly withCredentials: boolean;\n close(): void;\n}\n\ndeclare var EventSource: {\n prototype: EventSource;\n new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;\n};\n\ninterface EventSourceInit {\n readonly withCredentials: boolean;\n}\n\ninterface EventTarget {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;\n dispatchEvent(evt: Event): boolean;\n removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;\n}\n\ndeclare var EventTarget: {\n prototype: EventTarget;\n new(): EventTarget;\n};\n\ninterface ExtensionScriptApis {\n extensionIdToShortId(extensionId: string): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n genericWebRuntimeCallout(to: any, from: any, payload: string): void;\n getExtensionId(): string;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericPersistentCallbackHandler(callbackHandler: Function): void;\n registerWebRuntimeCallbackHandler(handler: Function): any;\n}\n\ndeclare var ExtensionScriptApis: {\n prototype: ExtensionScriptApis;\n new(): ExtensionScriptApis;\n};\n\ninterface External {\n}\n\ndeclare var External: {\n prototype: External;\n new(): External;\n};\n\ninterface File extends Blob {\n readonly lastModified: number;\n /** @deprecated */\n readonly lastModifiedDate: Date;\n readonly name: string;\n readonly webkitRelativePath: string;\n}\n\ndeclare var File: {\n prototype: File;\n new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;\n};\n\ninterface FileList {\n readonly length: number;\n item(index: number): File | null;\n [index: number]: File;\n}\n\ndeclare var FileList: {\n prototype: FileList;\n new(): FileList;\n};\n\ninterface FilePropertyBag extends BlobPropertyBag {\n lastModified?: number;\n}\n\ninterface FileReaderEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n}\n\ninterface FileReader extends EventTarget {\n readonly error: DOMException | null;\n onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onerror: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onload: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: any;\n abort(): void;\n readAsArrayBuffer(blob: Blob): void;\n readAsBinaryString(blob: Blob): void;\n readAsDataURL(blob: Blob): void;\n readAsText(blob: Blob, label?: string): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var FileReader: {\n prototype: FileReader;\n new(): FileReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface FocusEvent extends UIEvent {\n readonly relatedTarget: EventTarget;\n initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void;\n}\n\ndeclare var FocusEvent: {\n prototype: FocusEvent;\n new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent;\n};\n\ninterface FocusNavigationEvent extends Event {\n readonly navigationReason: NavigationReason;\n readonly originHeight: number;\n readonly originLeft: number;\n readonly originTop: number;\n readonly originWidth: number;\n requestFocus(): void;\n}\n\ndeclare var FocusNavigationEvent: {\n prototype: FocusNavigationEvent;\n new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent;\n};\n\ninterface FormData {\n append(name: string, value: string | Blob, fileName?: string): void;\n delete(name: string): void;\n get(name: string): FormDataEntryValue | null;\n getAll(name: string): FormDataEntryValue[];\n has(name: string): boolean;\n set(name: string, value: string | Blob, fileName?: string): void;\n}\n\ndeclare var FormData: {\n prototype: FormData;\n new(): FormData;\n new(form: HTMLFormElement): FormData;\n};\n\ninterface GainNode extends AudioNode {\n readonly gain: AudioParam;\n}\n\ndeclare var GainNode: {\n prototype: GainNode;\n new(): GainNode;\n};\n\ninterface Gamepad {\n readonly axes: number[];\n readonly buttons: GamepadButton[];\n readonly connected: boolean;\n readonly displayId: number;\n readonly hand: GamepadHand;\n readonly hapticActuators: GamepadHapticActuator[];\n readonly id: string;\n readonly index: number;\n readonly mapping: GamepadMappingType;\n readonly pose: GamepadPose | null;\n readonly timestamp: number;\n}\n\ndeclare var Gamepad: {\n prototype: Gamepad;\n new(): Gamepad;\n};\n\ninterface GamepadButton {\n readonly pressed: boolean;\n readonly touched: boolean;\n readonly value: number;\n}\n\ndeclare var GamepadButton: {\n prototype: GamepadButton;\n new(): GamepadButton;\n};\n\ninterface GamepadEvent extends Event {\n readonly gamepad: Gamepad;\n}\n\ndeclare var GamepadEvent: {\n prototype: GamepadEvent;\n new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent;\n};\n\ninterface GamepadHapticActuator {\n readonly type: GamepadHapticActuatorType;\n pulse(value: number, duration: number): Promise;\n}\n\ndeclare var GamepadHapticActuator: {\n prototype: GamepadHapticActuator;\n new(): GamepadHapticActuator;\n};\n\ninterface GamepadPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n}\n\ndeclare var GamepadPose: {\n prototype: GamepadPose;\n new(): GamepadPose;\n};\n\ninterface Geolocation {\n clearWatch(watchId: number): void;\n getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;\n watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;\n}\n\ndeclare var Geolocation: {\n prototype: Geolocation;\n new(): Geolocation;\n};\n\ninterface GetSVGDocument {\n getSVGDocument(): Document;\n}\n\ninterface GlobalEventHandlersEventMap {\n \"pointercancel\": PointerEvent;\n \"pointerdown\": PointerEvent;\n \"pointerenter\": PointerEvent;\n \"pointerleave\": PointerEvent;\n \"pointermove\": PointerEvent;\n \"pointerout\": PointerEvent;\n \"pointerover\": PointerEvent;\n \"pointerup\": PointerEvent;\n \"wheel\": WheelEvent;\n}\n\ninterface GlobalEventHandlers {\n onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null;\n addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface GlobalFetch {\n fetch(input?: Request | string, init?: RequestInit): Promise;\n}\n\ninterface HTMLAllCollection {\n readonly length: number;\n item(nameOrIndex?: string): HTMLCollection | Element | null;\n namedItem(name: string): HTMLCollection | Element | null;\n [index: number]: Element;\n}\n\ndeclare var HTMLAllCollection: {\n prototype: HTMLAllCollection;\n new(): HTMLAllCollection;\n};\n\ninterface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {\n Methods: string;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n /** @deprecated */\n coords: string;\n download: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n readonly mimeType: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n readonly nameProp: string;\n readonly protocolLong: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n type: string;\n urn: string;\n addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAnchorElement: {\n prototype: HTMLAnchorElement;\n new(): HTMLAnchorElement;\n};\n\ninterface HTMLAppletElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n /** @deprecated */\n alt: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n /** @deprecated */\n object: string;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAppletElement: {\n prototype: HTMLAppletElement;\n new(): HTMLAppletElement;\n};\n\ninterface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n coords: string;\n download: string;\n /**\n * Sets or gets whether clicks in this region cause action.\n */\n /** @deprecated */\n noHref: boolean;\n rel: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAreaElement: {\n prototype: HTMLAreaElement;\n new(): HTMLAreaElement;\n};\n\ninterface HTMLAreasCollection extends HTMLCollectionBase {\n}\n\ndeclare var HTMLAreasCollection: {\n prototype: HTMLAreasCollection;\n new(): HTMLAreasCollection;\n};\n\ninterface HTMLAudioElement extends HTMLMediaElement {\n addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAudioElement: {\n prototype: HTMLAudioElement;\n new(): HTMLAudioElement;\n};\n\ninterface HTMLBRElement extends HTMLElement {\n /**\n * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document.\n */\n /** @deprecated */\n clear: string;\n addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBRElement: {\n prototype: HTMLBRElement;\n new(): HTMLBRElement;\n};\n\ninterface HTMLBaseElement extends HTMLElement {\n /**\n * Gets or sets the baseline URL on which relative links are based.\n */\n href: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseElement: {\n prototype: HTMLBaseElement;\n new(): HTMLBaseElement;\n};\n\ninterface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /**\n * Sets or retrieves the font size of the object.\n */\n /** @deprecated */\n size: number;\n addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseFontElement: {\n prototype: HTMLBaseFontElement;\n new(): HTMLBaseFontElement;\n};\n\ninterface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLBodyElement extends HTMLElement, WindowEventHandlers {\n /** @deprecated */\n aLink: string;\n /** @deprecated */\n background: string;\n /** @deprecated */\n bgColor: string;\n bgProperties: string;\n /** @deprecated */\n link: string;\n /** @deprecated */\n noWrap: boolean;\n onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null;\n onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null;\n /** @deprecated */\n text: string;\n /** @deprecated */\n vLink: string;\n addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBodyElement: {\n prototype: HTMLBodyElement;\n new(): HTMLBodyElement;\n};\n\ninterface HTMLButtonElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n status: any;\n /**\n * Gets the classification and default behavior of the button.\n */\n type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the default or selected value of the control.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLButtonElement: {\n prototype: HTMLButtonElement;\n new(): HTMLButtonElement;\n};\n\ninterface HTMLCanvasElement extends HTMLElement {\n /**\n * Gets or sets the height of a canvas element on a document.\n */\n height: number;\n /**\n * Gets or sets the width of a canvas element on a document.\n */\n width: number;\n /**\n * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.\n * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext(\"2d\"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext(\"experimental-webgl\");\n */\n getContext(contextId: \"2d\", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null;\n getContext(contextId: \"webgl\" | \"experimental-webgl\", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null;\n getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null;\n /**\n * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.\n */\n msToBlob(): Blob;\n toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void;\n /**\n * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element.\n * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.\n */\n toDataURL(type?: string, ...args: any[]): string;\n addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLCanvasElement: {\n prototype: HTMLCanvasElement;\n new(): HTMLCanvasElement;\n};\n\ninterface HTMLCollectionBase {\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Retrieves an object from various collections.\n */\n item(index: number): Element;\n [index: number]: Element;\n}\n\ninterface HTMLCollection extends HTMLCollectionBase {\n /**\n * Retrieves a select object or an object from an options collection.\n */\n namedItem(name: string): Element | null;\n}\n\ndeclare var HTMLCollection: {\n prototype: HTMLCollection;\n new(): HTMLCollection;\n};\n\ninterface HTMLCollectionOf extends HTMLCollectionBase {\n item(index: number): T;\n namedItem(name: string): T;\n [index: number]: T;\n}\n\ninterface HTMLDListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDListElement: {\n prototype: HTMLDListElement;\n new(): HTMLDListElement;\n};\n\ninterface HTMLDataElement extends HTMLElement {\n value: string;\n addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataElement: {\n prototype: HTMLDataElement;\n new(): HTMLDataElement;\n};\n\ninterface HTMLDataListElement extends HTMLElement {\n readonly options: HTMLCollectionOf;\n addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataListElement: {\n prototype: HTMLDataListElement;\n new(): HTMLDataListElement;\n};\n\ninterface HTMLDetailsElement extends HTMLElement {\n open: boolean;\n addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDetailsElement: {\n prototype: HTMLDetailsElement;\n new(): HTMLDetailsElement;\n};\n\ninterface HTMLDialogElement extends HTMLElement {\n open: boolean;\n returnValue: string;\n close(returnValue?: string): void;\n show(): void;\n showModal(): void;\n addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDialogElement: {\n prototype: HTMLDialogElement;\n new(): HTMLDialogElement;\n};\n\ninterface HTMLDirectoryElement extends HTMLElement {\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDirectoryElement: {\n prototype: HTMLDirectoryElement;\n new(): HTMLDirectoryElement;\n};\n\ninterface HTMLDivElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n noWrap: boolean;\n addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDivElement: {\n prototype: HTMLDivElement;\n new(): HTMLDivElement;\n};\n\ninterface HTMLDocument extends Document {\n addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDocument: {\n prototype: HTMLDocument;\n new(): HTMLDocument;\n};\n\ninterface HTMLElementEventMap extends ElementEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforecopy\": Event;\n \"beforecut\": Event;\n \"beforedeactivate\": Event;\n \"beforepaste\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"copy\": ClipboardEvent;\n \"cuechange\": Event;\n \"cut\": ClipboardEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSManipulationStateChanged\": Event;\n \"paste\": ClipboardEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n}\n\ninterface HTMLElement extends Element, ElementCSSInlineStyle {\n accessKey: string;\n contentEditable: string;\n readonly dataset: DOMStringMap;\n dir: string;\n draggable: boolean;\n hidden: boolean;\n hideFocus: boolean;\n innerText: string;\n readonly isContentEditable: boolean;\n lang: string;\n readonly offsetHeight: number;\n readonly offsetLeft: number;\n readonly offsetParent: Element;\n readonly offsetTop: number;\n readonly offsetWidth: number;\n onabort: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecut: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null;\n onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oncanplay: ((this: HTMLElement, ev: Event) => any) | null;\n oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null;\n onchange: ((this: HTMLElement, ev: Event) => any) | null;\n onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null;\n oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n oncuechange: ((this: HTMLElement, ev: Event) => any) | null;\n oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n ondeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondurationchange: ((this: HTMLElement, ev: Event) => any) | null;\n onemptied: ((this: HTMLElement, ev: Event) => any) | null;\n onended: ((this: HTMLElement, ev: Event) => any) | null;\n onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null;\n onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oninput: ((this: HTMLElement, ev: Event) => any) | null;\n oninvalid: ((this: HTMLElement, ev: Event) => any) | null;\n onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onload: ((this: HTMLElement, ev: Event) => any) | null;\n onloadeddata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadstart: ((this: HTMLElement, ev: Event) => any) | null;\n onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null;\n onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n onpause: ((this: HTMLElement, ev: Event) => any) | null;\n onplay: ((this: HTMLElement, ev: Event) => any) | null;\n onplaying: ((this: HTMLElement, ev: Event) => any) | null;\n onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null;\n onratechange: ((this: HTMLElement, ev: Event) => any) | null;\n onreset: ((this: HTMLElement, ev: Event) => any) | null;\n onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onseeked: ((this: HTMLElement, ev: Event) => any) | null;\n onseeking: ((this: HTMLElement, ev: Event) => any) | null;\n onselect: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onselectstart: ((this: HTMLElement, ev: Event) => any) | null;\n onstalled: ((this: HTMLElement, ev: Event) => any) | null;\n onsubmit: ((this: HTMLElement, ev: Event) => any) | null;\n onsuspend: ((this: HTMLElement, ev: Event) => any) | null;\n ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null;\n onvolumechange: ((this: HTMLElement, ev: Event) => any) | null;\n onwaiting: ((this: HTMLElement, ev: Event) => any) | null;\n outerText: string;\n spellcheck: boolean;\n tabIndex: number;\n title: string;\n animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation;\n blur(): void;\n click(): void;\n dragDrop(): boolean;\n focus(): void;\n msGetInputContext(): MSInputMethodContext;\n addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLElement: {\n prototype: HTMLElement;\n new(): HTMLElement;\n};\n\ninterface HTMLEmbedElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n hidden: any;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * Retrieves the palette used for the embedded document.\n */\n readonly palette: string;\n /**\n * Retrieves the URL of the plug-in used to view an embedded document.\n */\n readonly pluginspage: string;\n readonly readyState: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrieves the height and width units of the embed object.\n */\n units: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLEmbedElement: {\n prototype: HTMLEmbedElement;\n new(): HTMLEmbedElement;\n};\n\ninterface HTMLFieldSetElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n align: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n name: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFieldSetElement: {\n prototype: HTMLFieldSetElement;\n new(): HTMLFieldSetElement;\n};\n\ninterface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFontElement: {\n prototype: HTMLFontElement;\n new(): HTMLFontElement;\n};\n\ninterface HTMLFormControlsCollection extends HTMLCollectionBase {\n namedItem(name: string): HTMLCollection | Element | null;\n}\n\ndeclare var HTMLFormControlsCollection: {\n prototype: HTMLFormControlsCollection;\n new(): HTMLFormControlsCollection;\n};\n\ninterface HTMLFormElement extends HTMLElement {\n /**\n * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form.\n */\n acceptCharset: string;\n /**\n * Sets or retrieves the URL to which the form content is sent for processing.\n */\n action: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Retrieves a collection, in source order, of all controls in a given form.\n */\n readonly elements: HTMLFormControlsCollection;\n /**\n * Sets or retrieves the MIME encoding for the form.\n */\n encoding: string;\n /**\n * Sets or retrieves the encoding type for the form.\n */\n enctype: string;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Sets or retrieves how to send the form data to the server.\n */\n method: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Designates a form that is not validated when submitted.\n */\n noValidate: boolean;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a form object or an object from an elements collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): any;\n /**\n * Retrieves a form object or an object from an elements collection.\n */\n namedItem(name: string): any;\n reportValidity(): boolean;\n /**\n * Fires when the user resets a form.\n */\n reset(): void;\n /**\n * Fires when a FORM is about to be submitted.\n */\n submit(): void;\n addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLFormElement: {\n prototype: HTMLFormElement;\n new(): HTMLFormElement;\n};\n\ninterface HTMLFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Specifies the properties of a border drawn around an object.\n */\n border: string;\n /**\n * Sets or retrieves the border color of the object.\n */\n borderColor: any;\n /**\n * Retrieves the document object of the page or frame.\n */\n /** @deprecated */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n /** @deprecated */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the amount of additional space between the frames.\n */\n frameSpacing: any;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string | number;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n /** @deprecated */\n name: string;\n /**\n * Sets or retrieves whether the user can resize the frame.\n */\n /** @deprecated */\n noResize: boolean;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n /** @deprecated */\n src: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string | number;\n addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameElement: {\n prototype: HTMLFrameElement;\n new(): HTMLFrameElement;\n};\n\ninterface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers {\n /**\n * Sets or retrieves the frame widths of the object.\n */\n /** @deprecated */\n cols: string;\n name: string;\n onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null;\n onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null;\n /**\n * Sets or retrieves the frame heights of the object.\n */\n /** @deprecated */\n rows: string;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameSetElement: {\n prototype: HTMLFrameSetElement;\n new(): HTMLFrameSetElement;\n};\n\ninterface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the horizontal rule is drawn with 3-D shading.\n */\n /** @deprecated */\n noShade: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHRElement: {\n prototype: HTMLHRElement;\n new(): HTMLHRElement;\n};\n\ninterface HTMLHeadElement extends HTMLElement {\n /** @deprecated */\n profile: string;\n addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadElement: {\n prototype: HTMLHeadElement;\n new(): HTMLHeadElement;\n};\n\ninterface HTMLHeadingElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadingElement: {\n prototype: HTMLHeadingElement;\n new(): HTMLHeadingElement;\n};\n\ninterface HTMLHtmlElement extends HTMLElement {\n /**\n * Sets or retrieves the DTD version that governs the current document.\n */\n /** @deprecated */\n version: string;\n addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHtmlElement: {\n prototype: HTMLHtmlElement;\n new(): HTMLHtmlElement;\n};\n\ninterface HTMLHyperlinkElementUtils {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n toString(): string;\n}\n\ninterface HTMLIFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLIFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n allowFullscreen: boolean;\n allowPaymentRequest: boolean;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n name: string;\n readonly sandbox: DOMTokenList;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrives the content of the page that is to contain.\n */\n srcdoc: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLIFrameElement: {\n prototype: HTMLIFrameElement;\n new(): HTMLIFrameElement;\n};\n\ninterface HTMLImageElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies the properties of a border drawn around an object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves whether the object is fully loaded.\n */\n readonly complete: boolean;\n crossOrigin: string | null;\n readonly currentSrc: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves whether the image is a server-side image map.\n */\n isMap: boolean;\n /**\n * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object.\n */\n longDesc: string;\n /** @deprecated */\n lowsrc: string;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * The original height of the image resource before sizing.\n */\n readonly naturalHeight: number;\n /**\n * The original width of the image resource before sizing.\n */\n readonly naturalWidth: number;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Sets or retrieves the vertical margin for the object.\n */\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n readonly x: number;\n readonly y: number;\n msGetAsCastingSource(): any;\n addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLImageElement: {\n prototype: HTMLImageElement;\n new(): HTMLImageElement;\n};\n\ninterface HTMLInputElement extends HTMLElement {\n /**\n * Sets or retrieves a comma-separated list of content types.\n */\n accept: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n checked: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n defaultChecked: boolean;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Returns a FileList object on a file type input object.\n */\n readonly files: FileList | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n indeterminate: boolean;\n /**\n * Specifies the ID of a pre-defined datalist of options for an input element.\n */\n readonly list: HTMLElement | null;\n /**\n * Defines the maximum acceptable value for an input element with type=\"number\".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field.\n */\n max: string;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n /**\n * Defines the minimum acceptable value for an input element with type=\"number\". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field.\n */\n min: string;\n minLength: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a string containing a regular expression that the user's input must match.\n */\n pattern: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n selectionDirection: string | null;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number | null;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number | null;\n size: number;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n /**\n * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field.\n */\n step: string;\n /**\n * Returns the content type of the object.\n */\n type: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n /** @deprecated */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns the value of the data at the cursor's current position.\n */\n value: string;\n valueAsDate: any;\n /**\n * Returns the input field value as a number.\n */\n valueAsNumber: number;\n webkitdirectory: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Makes the selection equal to the current object.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n /**\n * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value.\n * @param n Value to decrement the value by.\n */\n stepDown(n?: number): void;\n /**\n * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value.\n * @param n Value to increment the value by.\n */\n stepUp(n?: number): void;\n addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLInputElement: {\n prototype: HTMLInputElement;\n new(): HTMLInputElement;\n};\n\ninterface HTMLLIElement extends HTMLElement {\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of a list item.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLIElement: {\n prototype: HTMLLIElement;\n new(): HTMLLIElement;\n};\n\ninterface HTMLLabelElement extends HTMLElement {\n readonly control: HTMLInputElement | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the object to which the given label object is assigned.\n */\n htmlFor: string;\n addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLabelElement: {\n prototype: HTMLLabelElement;\n new(): HTMLLabelElement;\n};\n\ninterface HTMLLegendElement extends HTMLElement {\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n /** @deprecated */\n align: string;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLegendElement: {\n prototype: HTMLLegendElement;\n new(): HTMLLegendElement;\n};\n\ninterface HTMLLinkElement extends HTMLElement, LinkStyle {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves a destination URL or an anchor point.\n */\n href: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n import?: Document;\n integrity: string;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n /** @deprecated */\n target: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLinkElement: {\n prototype: HTMLLinkElement;\n new(): HTMLLinkElement;\n};\n\ninterface HTMLMainElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMainElement: {\n prototype: HTMLMainElement;\n new(): HTMLMainElement;\n};\n\ninterface HTMLMapElement extends HTMLElement {\n /**\n * Retrieves a collection of the area objects defined for the given map object.\n */\n readonly areas: HTMLAreasCollection;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMapElement: {\n prototype: HTMLMapElement;\n new(): HTMLMapElement;\n};\n\ninterface HTMLMarqueeElementEventMap extends HTMLElementEventMap {\n \"bounce\": Event;\n \"finish\": Event;\n \"start\": Event;\n}\n\ninterface HTMLMarqueeElement extends HTMLElement {\n /** @deprecated */\n behavior: string;\n /** @deprecated */\n bgColor: string;\n /** @deprecated */\n direction: string;\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /** @deprecated */\n loop: number;\n /** @deprecated */\n onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n scrollAmount: number;\n /** @deprecated */\n scrollDelay: number;\n /** @deprecated */\n trueSpeed: boolean;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n /** @deprecated */\n start(): void;\n /** @deprecated */\n stop(): void;\n addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMarqueeElement: {\n prototype: HTMLMarqueeElement;\n new(): HTMLMarqueeElement;\n};\n\ninterface HTMLMediaElementEventMap extends HTMLElementEventMap {\n \"encrypted\": MediaEncryptedEvent;\n \"msneedkey\": Event;\n}\n\ninterface HTMLMediaElement extends HTMLElement {\n /**\n * Returns an AudioTrackList object with the audio tracks for a given video element.\n */\n readonly audioTracks: AudioTrackList;\n /**\n * Gets or sets a value that indicates whether to start playing the media automatically.\n */\n autoplay: boolean;\n /**\n * Gets a collection of buffered time ranges.\n */\n readonly buffered: TimeRanges;\n /**\n * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player).\n */\n controls: boolean;\n crossOrigin: string | null;\n /**\n * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement.\n */\n readonly currentSrc: string;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n currentTime: number;\n defaultMuted: boolean;\n /**\n * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource.\n */\n defaultPlaybackRate: number;\n /**\n * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming.\n */\n readonly duration: number;\n /**\n * Gets information about whether the playback has ended or not.\n */\n readonly ended: boolean;\n /**\n * Returns an object representing the current error state of the audio or video element.\n */\n readonly error: MediaError | null;\n /**\n * Gets or sets a flag to specify whether playback should restart after it completes.\n */\n loop: boolean;\n readonly mediaKeys: MediaKeys | null;\n /**\n * Specifies the purpose of the audio or video media, such as background audio or alerts.\n */\n msAudioCategory: string;\n /**\n * Specifies the output device id that the audio will be sent to.\n */\n msAudioDeviceType: string;\n readonly msGraphicsTrustStatus: MSGraphicsTrust;\n /**\n * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element.\n */\n /** @deprecated */\n readonly msKeys: MSMediaKeys;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Specifies whether or not to enable low-latency playback on the media element.\n */\n msRealTime: boolean;\n /**\n * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted.\n */\n muted: boolean;\n /**\n * Gets the current network activity for the element.\n */\n readonly networkState: number;\n onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null;\n /** @deprecated */\n onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null;\n /**\n * Gets a flag that specifies whether playback is paused.\n */\n readonly paused: boolean;\n /**\n * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource.\n */\n playbackRate: number;\n /**\n * Gets TimeRanges for the current media resource that has been played.\n */\n readonly played: TimeRanges;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n preload: string;\n readonly readyState: number;\n /**\n * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.\n */\n readonly seekable: TimeRanges;\n /**\n * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource.\n */\n readonly seeking: boolean;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcObject: MediaStream | MediaSource | Blob | null;\n readonly textTracks: TextTrackList;\n readonly videoTracks: VideoTrackList;\n /**\n * Gets or sets the volume level for audio portions of the media element.\n */\n volume: number;\n addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack;\n /**\n * Returns a string that specifies whether the client can play a given media resource type.\n */\n canPlayType(type: string): CanPlayTypeResult;\n /**\n * Resets the audio or video object and loads a new media resource.\n */\n load(): void;\n /**\n * Clears all effects from the media pipeline.\n */\n msClearEffects(): void;\n msGetAsCastingSource(): any;\n /**\n * Inserts the specified audio effect into media pipeline.\n */\n msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n /** @deprecated */\n msSetMediaKeys(mediaKeys: MSMediaKeys): void;\n /**\n * Specifies the media protection manager for a given media pipeline.\n */\n msSetMediaProtectionManager(mediaProtectionManager?: any): void;\n /**\n * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not.\n */\n pause(): void;\n /**\n * Loads and starts playback of a media resource.\n */\n play(): Promise;\n setMediaKeys(mediaKeys: MediaKeys | null): Promise;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMediaElement: {\n prototype: HTMLMediaElement;\n new(): HTMLMediaElement;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n};\n\ninterface HTMLMenuElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n type: string;\n addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMenuElement: {\n prototype: HTMLMenuElement;\n new(): HTMLMenuElement;\n};\n\ninterface HTMLMetaElement extends HTMLElement {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Gets or sets meta-information to associate with httpEquiv or name.\n */\n content: string;\n /**\n * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header.\n */\n httpEquiv: string;\n /**\n * Sets or retrieves the value specified in the content attribute of the meta object.\n */\n name: string;\n /**\n * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object.\n */\n /** @deprecated */\n scheme: string;\n /**\n * Sets or retrieves the URL property that will be loaded after the specified time has elapsed.\n */\n /** @deprecated */\n url: string;\n addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMetaElement: {\n prototype: HTMLMetaElement;\n new(): HTMLMetaElement;\n};\n\ninterface HTMLMeterElement extends HTMLElement {\n high: number;\n low: number;\n max: number;\n min: number;\n optimum: number;\n value: number;\n addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMeterElement: {\n prototype: HTMLMeterElement;\n new(): HTMLMeterElement;\n};\n\ninterface HTMLModElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n /**\n * Sets or retrieves the date and time of a modification to the object.\n */\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLModElement: {\n prototype: HTMLModElement;\n new(): HTMLModElement;\n};\n\ninterface HTMLOListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /**\n * The starting number.\n */\n start: number;\n type: string;\n addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOListElement: {\n prototype: HTMLOListElement;\n new(): HTMLOListElement;\n};\n\ninterface HTMLObjectElement extends HTMLElement, GetSVGDocument {\n /**\n * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element.\n */\n readonly BaseHref: string;\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n border: string;\n /**\n * Sets or retrieves the URL of the file containing the compiled Java class.\n */\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n /**\n * Sets or retrieves the Internet media type for the code associated with the object.\n */\n /** @deprecated */\n codeType: string;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Sets or retrieves the URL that references the data of the object.\n */\n data: string;\n /** @deprecated */\n declare: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly readyState: number;\n /**\n * Sets or retrieves a message to be displayed while an object is loading.\n */\n /** @deprecated */\n standby: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n typemustmatch: boolean;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLObjectElement: {\n prototype: HTMLObjectElement;\n new(): HTMLObjectElement;\n};\n\ninterface HTMLOptGroupElement extends HTMLElement {\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptGroupElement: {\n prototype: HTMLOptGroupElement;\n new(): HTMLOptGroupElement;\n};\n\ninterface HTMLOptionElement extends HTMLElement {\n /**\n * Sets or retrieves the status of an option.\n */\n defaultSelected: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the ordinal position of an option in a list box.\n */\n readonly index: number;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n /**\n * Sets or retrieves whether the option in the list box is the default item.\n */\n selected: boolean;\n /**\n * Sets or retrieves the text string specified by the option tag.\n */\n text: string;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptionElement: {\n prototype: HTMLOptionElement;\n new(): HTMLOptionElement;\n};\n\ninterface HTMLOptionsCollection extends HTMLCollectionOf {\n length: number;\n selectedIndex: number;\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void;\n remove(index: number): void;\n}\n\ndeclare var HTMLOptionsCollection: {\n prototype: HTMLOptionsCollection;\n new(): HTMLOptionsCollection;\n};\n\ninterface HTMLOutputElement extends HTMLElement {\n defaultValue: string;\n readonly form: HTMLFormElement | null;\n readonly htmlFor: DOMTokenList;\n name: string;\n readonly type: string;\n readonly validationMessage: string;\n readonly validity: ValidityState;\n value: string;\n readonly willValidate: boolean;\n checkValidity(): boolean;\n reportValidity(): boolean;\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOutputElement: {\n prototype: HTMLOutputElement;\n new(): HTMLOutputElement;\n};\n\ninterface HTMLParagraphElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n clear: string;\n addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParagraphElement: {\n prototype: HTMLParagraphElement;\n new(): HTMLParagraphElement;\n};\n\ninterface HTMLParamElement extends HTMLElement {\n /**\n * Sets or retrieves the name of an input parameter for an element.\n */\n name: string;\n /**\n * Sets or retrieves the content type of the resource designated by the value attribute.\n */\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of an input parameter for an element.\n */\n value: string;\n /**\n * Sets or retrieves the data type of the value attribute.\n */\n /** @deprecated */\n valueType: string;\n addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParamElement: {\n prototype: HTMLParamElement;\n new(): HTMLParamElement;\n};\n\ninterface HTMLPictureElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPictureElement: {\n prototype: HTMLPictureElement;\n new(): HTMLPictureElement;\n};\n\ninterface HTMLPreElement extends HTMLElement {\n /**\n * Sets or gets a value that you can use to implement your own width functionality for the object.\n */\n /** @deprecated */\n width: number;\n addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPreElement: {\n prototype: HTMLPreElement;\n new(): HTMLPreElement;\n};\n\ninterface HTMLProgressElement extends HTMLElement {\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Defines the maximum, or \"done\" value for a progress element.\n */\n max: number;\n /**\n * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar).\n */\n readonly position: number;\n /**\n * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLProgressElement: {\n prototype: HTMLProgressElement;\n new(): HTMLProgressElement;\n};\n\ninterface HTMLQuoteElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLQuoteElement: {\n prototype: HTMLQuoteElement;\n new(): HTMLQuoteElement;\n};\n\ninterface HTMLScriptElement extends HTMLElement {\n async: boolean;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n charset: string;\n crossOrigin: string | null;\n /**\n * Sets or retrieves the status of the script.\n */\n defer: boolean;\n /**\n * Sets or retrieves the event for which the script is written.\n */\n /** @deprecated */\n event: string;\n /**\n * Sets or retrieves the object that is bound to the event script.\n */\n /** @deprecated */\n htmlFor: string;\n integrity: string;\n noModule: boolean;\n /**\n * Retrieves the URL to an external file that contains the source code or data.\n */\n src: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n /**\n * Sets or retrieves the MIME type for the associated scripting engine.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLScriptElement: {\n prototype: HTMLScriptElement;\n new(): HTMLScriptElement;\n};\n\ninterface HTMLSelectElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n length: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly options: HTMLOptionsCollection;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the index of the selected option in a select object.\n */\n selectedIndex: number;\n readonly selectedOptions: HTMLCollectionOf;\n /**\n * Sets or retrieves the number of rows in the list box.\n */\n size: number;\n /**\n * Retrieves the type of select control based on the value of the MULTIPLE attribute.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Adds an element to the areas, controlRange, or options collection.\n * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.\n * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): Element | null;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made.\n */\n namedItem(name: string): any;\n /**\n * Removes an element from the collection.\n * @param index Number that specifies the zero-based index of the element to remove from the collection.\n */\n remove(index?: number): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLSelectElement: {\n prototype: HTMLSelectElement;\n new(): HTMLSelectElement;\n};\n\ninterface HTMLSlotElement extends HTMLElement {\n name: string;\n assignedNodes(options?: AssignedNodesOptions): Node[];\n addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface HTMLSourceElement extends HTMLElement {\n /**\n * Gets or sets the intended media type of the media source.\n */\n media: string;\n /** @deprecated */\n msKeySystem: string;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Gets or sets the MIME type of a media resource.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSourceElement: {\n prototype: HTMLSourceElement;\n new(): HTMLSourceElement;\n};\n\ninterface HTMLSpanElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSpanElement: {\n prototype: HTMLSpanElement;\n new(): HTMLSpanElement;\n};\n\ninterface HTMLStyleElement extends HTMLElement, LinkStyle {\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Retrieves the CSS language in which the style sheet is written.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLStyleElement: {\n prototype: HTMLStyleElement;\n new(): HTMLStyleElement;\n};\n\ninterface HTMLSummaryElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSummaryElement: {\n prototype: HTMLSummaryElement;\n new(): HTMLSummaryElement;\n};\n\ninterface HTMLTableCaptionElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the caption or legend.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCaptionElement: {\n prototype: HTMLTableCaptionElement;\n new(): HTMLTableCaptionElement;\n};\n\ninterface HTMLTableCellElement extends HTMLElement {\n /**\n * Sets or retrieves abbreviated text for the object.\n */\n abbr: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a comma-delimited list of conceptual categories associated with the object.\n */\n /** @deprecated */\n axis: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves the position of the object in the cells collection of a row.\n */\n readonly cellIndex: number;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number columns in the table that the object should span.\n */\n colSpan: number;\n /**\n * Sets or retrieves a list of header cells that provide information for the object.\n */\n headers: string;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n /** @deprecated */\n noWrap: boolean;\n /**\n * Sets or retrieves how many rows in a table the cell should span.\n */\n rowSpan: number;\n /**\n * Sets or retrieves the group of cells in a table to which the object's information applies.\n */\n scope: string;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCellElement: {\n prototype: HTMLTableCellElement;\n new(): HTMLTableCellElement;\n};\n\ninterface HTMLTableColElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the object relative to the display or table.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of columns in the group.\n */\n span: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableColElement: {\n prototype: HTMLTableColElement;\n new(): HTMLTableColElement;\n};\n\ninterface HTMLTableDataCellElement extends HTMLTableCellElement {\n addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableDataCellElement: {\n prototype: HTMLTableDataCellElement;\n new(): HTMLTableDataCellElement;\n};\n\ninterface HTMLTableElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves the caption object of a table.\n */\n caption: HTMLTableCaptionElement | null;\n /**\n * Sets or retrieves the amount of space between the border of the cell and the content of the cell.\n */\n /** @deprecated */\n cellPadding: string;\n /**\n * Sets or retrieves the amount of space between cells in a table.\n */\n /** @deprecated */\n cellSpacing: string;\n /**\n * Sets or retrieves the way the border frame around the table is displayed.\n */\n /** @deprecated */\n frame: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /**\n * Sets or retrieves which dividing lines (inner borders) are displayed.\n */\n /** @deprecated */\n rules: string;\n /**\n * Sets or retrieves a description and/or structure of the object.\n */\n /** @deprecated */\n summary: string;\n /**\n * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order.\n */\n readonly tBodies: HTMLCollectionOf;\n /**\n * Retrieves the tFoot object of the table.\n */\n tFoot: HTMLTableSectionElement | null;\n /**\n * Retrieves the tHead object of the table.\n */\n tHead: HTMLTableSectionElement | null;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n /**\n * Creates an empty caption element in the table.\n */\n createCaption(): HTMLTableCaptionElement;\n /**\n * Creates an empty tBody element in the table.\n */\n createTBody(): HTMLTableSectionElement;\n /**\n * Creates an empty tFoot element in the table.\n */\n createTFoot(): HTMLTableSectionElement;\n /**\n * Returns the tHead element object if successful, or null otherwise.\n */\n createTHead(): HTMLTableSectionElement;\n /**\n * Deletes the caption element and its contents from the table.\n */\n deleteCaption(): void;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Deletes the tFoot element and its contents from the table.\n */\n deleteTFoot(): void;\n /**\n * Deletes the tHead element and its contents from the table.\n */\n deleteTHead(): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableElement: {\n prototype: HTMLTableElement;\n new(): HTMLTableElement;\n};\n\ninterface HTMLTableHeaderCellElement extends HTMLTableCellElement {\n scope: string;\n addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableHeaderCellElement: {\n prototype: HTMLTableHeaderCellElement;\n new(): HTMLTableHeaderCellElement;\n};\n\ninterface HTMLTableRowElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves a collection of all cells in the table row.\n */\n readonly cells: HTMLCollectionOf;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Retrieves the position of the object in the rows collection for the table.\n */\n readonly rowIndex: number;\n /**\n * Retrieves the position of the object in the collection.\n */\n readonly sectionRowIndex: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified cell from the table row, as well as from the cells collection.\n * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted.\n */\n deleteCell(index?: number): void;\n /**\n * Creates a new cell in the table row, and adds the cell to the cells collection.\n * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.\n */\n insertCell(index?: number): HTMLTableDataCellElement;\n addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableRowElement: {\n prototype: HTMLTableRowElement;\n new(): HTMLTableRowElement;\n};\n\ninterface HTMLTableSectionElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableSectionElement: {\n prototype: HTMLTableSectionElement;\n new(): HTMLTableSectionElement;\n};\n\ninterface HTMLTemplateElement extends HTMLElement {\n readonly content: DocumentFragment;\n addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTemplateElement: {\n prototype: HTMLTemplateElement;\n new(): HTMLTemplateElement;\n};\n\ninterface HTMLTextAreaElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n cols: number;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n minLength: number;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n /**\n * Sets or retrieves the value indicated whether the content of the object is read-only.\n */\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n rows: number;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number;\n /**\n * Retrieves the type of control.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Retrieves or sets the text in the entry field of the textArea element.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Sets or retrieves how to handle wordwrapping in the object.\n */\n wrap: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Highlights the input area of a form element.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTextAreaElement: {\n prototype: HTMLTextAreaElement;\n new(): HTMLTextAreaElement;\n};\n\ninterface HTMLTimeElement extends HTMLElement {\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTimeElement: {\n prototype: HTMLTimeElement;\n new(): HTMLTimeElement;\n};\n\ninterface HTMLTitleElement extends HTMLElement {\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTitleElement: {\n prototype: HTMLTitleElement;\n new(): HTMLTitleElement;\n};\n\ninterface HTMLTrackElement extends HTMLElement {\n default: boolean;\n kind: string;\n label: string;\n readonly readyState: number;\n src: string;\n srclang: string;\n readonly track: TextTrack;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTrackElement: {\n prototype: HTMLTrackElement;\n new(): HTMLTrackElement;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n};\n\ninterface HTMLUListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUListElement: {\n prototype: HTMLUListElement;\n new(): HTMLUListElement;\n};\n\ninterface HTMLUnknownElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUnknownElement: {\n prototype: HTMLUnknownElement;\n new(): HTMLUnknownElement;\n};\n\ninterface HTMLVideoElementEventMap extends HTMLMediaElementEventMap {\n \"MSVideoFormatChanged\": Event;\n \"MSVideoFrameStepCompleted\": Event;\n \"MSVideoOptimalLayoutChanged\": Event;\n}\n\ninterface HTMLVideoElement extends HTMLMediaElement {\n /**\n * Gets or sets the height of the video element.\n */\n height: number;\n msHorizontalMirror: boolean;\n readonly msIsLayoutOptimalForPlayback: boolean;\n readonly msIsStereo3D: boolean;\n msStereo3DPackingMode: string;\n msStereo3DRenderMode: string;\n msZoom: boolean;\n onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n /**\n * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available.\n */\n poster: string;\n /**\n * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoHeight: number;\n /**\n * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoWidth: number;\n readonly webkitDisplayingFullscreen: boolean;\n readonly webkitSupportsFullscreen: boolean;\n /**\n * Gets or sets the width of the video element.\n */\n width: number;\n getVideoPlaybackQuality(): VideoPlaybackQuality;\n msFrameStep(forward: boolean): void;\n msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void;\n webkitEnterFullScreen(): void;\n webkitEnterFullscreen(): void;\n webkitExitFullScreen(): void;\n webkitExitFullscreen(): void;\n addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLVideoElement: {\n prototype: HTMLVideoElement;\n new(): HTMLVideoElement;\n};\n\ninterface HTMLegendElement {\n readonly form: HTMLFormElement | null;\n}\n\ndeclare var HTMLegendElement: {\n prototype: HTMLegendElement;\n new(): HTMLegendElement;\n};\n\ninterface HashChangeEvent extends Event {\n readonly newURL: string;\n readonly oldURL: string;\n}\n\ndeclare var HashChangeEvent: {\n prototype: HashChangeEvent;\n new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent;\n};\n\ninterface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n forEach(callback: Function, thisArg?: any): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n}\n\ndeclare var Headers: {\n prototype: Headers;\n new(init?: HeadersInit): Headers;\n};\n\ninterface History {\n readonly length: number;\n scrollRestoration: ScrollRestoration;\n readonly state: any;\n back(distance?: any): void;\n forward(distance?: any): void;\n go(delta?: any): void;\n pushState(data: any, title?: string, url?: string | null): void;\n replaceState(data: any, title?: string, url?: string | null): void;\n}\n\ndeclare var History: {\n prototype: History;\n new(): History;\n};\n\ninterface HkdfCtrParams extends Algorithm {\n context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n hash: string | Algorithm;\n label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface IDBArrayKey extends Array {\n}\n\ninterface IDBCursor {\n readonly direction: IDBCursorDirection;\n readonly key: IDBKeyRange | number | string | Date | IDBArrayKey;\n readonly primaryKey: any;\n readonly source: IDBObjectStore | IDBIndex;\n advance(count: number): void;\n continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void;\n delete(): IDBRequest;\n update(value: any): IDBRequest;\n readonly NEXT: string;\n readonly NEXT_NO_DUPLICATE: string;\n readonly PREV: string;\n readonly PREV_NO_DUPLICATE: string;\n}\n\ndeclare var IDBCursor: {\n prototype: IDBCursor;\n new(): IDBCursor;\n readonly NEXT: string;\n readonly NEXT_NO_DUPLICATE: string;\n readonly PREV: string;\n readonly PREV_NO_DUPLICATE: string;\n};\n\ninterface IDBCursorWithValue extends IDBCursor {\n readonly value: any;\n}\n\ndeclare var IDBCursorWithValue: {\n prototype: IDBCursorWithValue;\n new(): IDBCursorWithValue;\n};\n\ninterface IDBDatabaseEventMap {\n \"abort\": Event;\n \"error\": Event;\n}\n\ninterface IDBDatabase extends EventTarget {\n readonly name: string;\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBDatabase, ev: Event) => any) | null;\n onerror: ((this: IDBDatabase, ev: Event) => any) | null;\n onversionchange: ((this: IDBDatabase, ev: Event) => any) | null;\n readonly version: number;\n close(): void;\n createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;\n deleteObjectStore(name: string): void;\n transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;\n addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBDatabase: {\n prototype: IDBDatabase;\n new(): IDBDatabase;\n};\n\ninterface IDBEnvironment {\n readonly indexedDB: IDBFactory;\n}\n\ninterface IDBFactory {\n cmp(first: any, second: any): number;\n deleteDatabase(name: string): IDBOpenDBRequest;\n open(name: string, version?: number): IDBOpenDBRequest;\n}\n\ndeclare var IDBFactory: {\n prototype: IDBFactory;\n new(): IDBFactory;\n};\n\ninterface IDBIndex {\n readonly keyPath: string | string[];\n multiEntry: boolean;\n readonly name: string;\n readonly objectStore: IDBObjectStore;\n readonly unique: boolean;\n count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n}\n\ndeclare var IDBIndex: {\n prototype: IDBIndex;\n new(): IDBIndex;\n};\n\ninterface IDBKeyRange {\n readonly lower: any;\n readonly lowerOpen: boolean;\n readonly upper: any;\n readonly upperOpen: boolean;\n}\n\ndeclare var IDBKeyRange: {\n prototype: IDBKeyRange;\n new(): IDBKeyRange;\n bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;\n lowerBound(lower: any, open?: boolean): IDBKeyRange;\n only(value: any): IDBKeyRange;\n upperBound(upper: any, open?: boolean): IDBKeyRange;\n};\n\ninterface IDBObjectStore {\n autoIncrement: boolean;\n readonly indexNames: DOMStringList;\n readonly keyPath: string | string[] | null;\n readonly name: string;\n readonly transaction: IDBTransaction;\n add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n clear(): IDBRequest;\n count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;\n delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n deleteIndex(indexName: string): void;\n get(key: any): IDBRequest;\n index(name: string): IDBIndex;\n openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n}\n\ndeclare var IDBObjectStore: {\n prototype: IDBObjectStore;\n new(): IDBObjectStore;\n};\n\ninterface IDBOpenDBRequestEventMap extends IDBRequestEventMap {\n \"blocked\": Event;\n \"upgradeneeded\": IDBVersionChangeEvent;\n}\n\ninterface IDBOpenDBRequest extends IDBRequest {\n onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;\n onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;\n addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBOpenDBRequest: {\n prototype: IDBOpenDBRequest;\n new(): IDBOpenDBRequest;\n};\n\ninterface IDBRequestEventMap {\n \"error\": Event;\n \"success\": Event;\n}\n\ninterface IDBRequest extends EventTarget {\n readonly error: DOMException;\n onerror: ((this: IDBRequest, ev: Event) => any) | null;\n onsuccess: ((this: IDBRequest, ev: Event) => any) | null;\n readonly readyState: IDBRequestReadyState;\n readonly result: any;\n readonly source: IDBObjectStore | IDBIndex | IDBCursor;\n readonly transaction: IDBTransaction;\n addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBRequest: {\n prototype: IDBRequest;\n new(): IDBRequest;\n};\n\ninterface IDBTransactionEventMap {\n \"abort\": Event;\n \"complete\": Event;\n \"error\": Event;\n}\n\ninterface IDBTransaction extends EventTarget {\n readonly db: IDBDatabase;\n readonly error: DOMException;\n readonly mode: IDBTransactionMode;\n onabort: ((this: IDBTransaction, ev: Event) => any) | null;\n oncomplete: ((this: IDBTransaction, ev: Event) => any) | null;\n onerror: ((this: IDBTransaction, ev: Event) => any) | null;\n abort(): void;\n objectStore(name: string): IDBObjectStore;\n readonly READ_ONLY: string;\n readonly READ_WRITE: string;\n readonly VERSION_CHANGE: string;\n addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBTransaction: {\n prototype: IDBTransaction;\n new(): IDBTransaction;\n readonly READ_ONLY: string;\n readonly READ_WRITE: string;\n readonly VERSION_CHANGE: string;\n};\n\ninterface IDBVersionChangeEvent extends Event {\n readonly newVersion: number | null;\n readonly oldVersion: number;\n}\n\ndeclare var IDBVersionChangeEvent: {\n prototype: IDBVersionChangeEvent;\n new(): IDBVersionChangeEvent;\n};\n\ninterface IIRFilterNode extends AudioNode {\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var IIRFilterNode: {\n prototype: IIRFilterNode;\n new(): IIRFilterNode;\n};\n\ninterface ImageBitmap {\n readonly height: number;\n readonly width: number;\n close(): void;\n}\n\ninterface ImageBitmapOptions {\n colorSpaceConversion?: \"none\" | \"default\";\n imageOrientation?: \"none\" | \"flipY\";\n premultiplyAlpha?: \"none\" | \"premultiply\" | \"default\";\n resizeHeight?: number;\n resizeQuality?: \"pixelated\" | \"low\" | \"medium\" | \"high\";\n resizeWidth?: number;\n}\n\ninterface ImageData {\n readonly data: Uint8ClampedArray;\n readonly height: number;\n readonly width: number;\n}\n\ndeclare var ImageData: {\n prototype: ImageData;\n new(width: number, height: number): ImageData;\n new(array: Uint8ClampedArray, width: number, height: number): ImageData;\n};\n\ninterface IntersectionObserver {\n readonly root: Element | null;\n readonly rootMargin: string;\n readonly thresholds: number[];\n disconnect(): void;\n observe(target: Element): void;\n takeRecords(): IntersectionObserverEntry[];\n unobserve(target: Element): void;\n}\n\ndeclare var IntersectionObserver: {\n prototype: IntersectionObserver;\n new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;\n};\n\ninterface IntersectionObserverEntry {\n readonly boundingClientRect: ClientRect | DOMRect;\n readonly intersectionRatio: number;\n readonly intersectionRect: ClientRect | DOMRect;\n readonly isIntersecting: boolean;\n readonly rootBounds: ClientRect | DOMRect;\n readonly target: Element;\n readonly time: number;\n}\n\ndeclare var IntersectionObserverEntry: {\n prototype: IntersectionObserverEntry;\n new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry;\n};\n\ninterface KeyboardEvent extends UIEvent {\n readonly altKey: boolean;\n /** @deprecated */\n char: string;\n /** @deprecated */\n readonly charCode: number;\n readonly code: string;\n readonly ctrlKey: boolean;\n readonly key: string;\n /** @deprecated */\n readonly keyCode: number;\n readonly location: number;\n readonly metaKey: boolean;\n readonly repeat: boolean;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly which: number;\n getModifierState(keyArg: string): boolean;\n /** @deprecated */\n initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n}\n\ndeclare var KeyboardEvent: {\n prototype: KeyboardEvent;\n new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n};\n\ninterface LinkStyle {\n readonly sheet: StyleSheet | null;\n}\n\ninterface ListeningStateChangedEvent extends Event {\n readonly label: string;\n readonly state: ListeningState;\n}\n\ndeclare var ListeningStateChangedEvent: {\n prototype: ListeningStateChangedEvent;\n new(): ListeningStateChangedEvent;\n};\n\ninterface Location {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n assign(url: string): void;\n reload(forcedReload?: boolean): void;\n replace(url: string): void;\n toString(): string;\n}\n\ndeclare var Location: {\n prototype: Location;\n new(): Location;\n};\n\ninterface MSAssertion {\n readonly id: string;\n readonly type: MSCredentialType;\n}\n\ndeclare var MSAssertion: {\n prototype: MSAssertion;\n new(): MSAssertion;\n};\n\ninterface MSBlobBuilder {\n append(data: any, endings?: string): void;\n getBlob(contentType?: string): Blob;\n}\n\ndeclare var MSBlobBuilder: {\n prototype: MSBlobBuilder;\n new(): MSBlobBuilder;\n};\n\ninterface MSCredentials {\n getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise;\n makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise;\n}\n\ndeclare var MSCredentials: {\n prototype: MSCredentials;\n new(): MSCredentials;\n};\n\ninterface MSDCCEvent extends Event {\n readonly maxFr: number;\n readonly maxFs: number;\n}\n\ndeclare var MSDCCEvent: {\n prototype: MSDCCEvent;\n new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent;\n};\n\ninterface MSDSHEvent extends Event {\n readonly sources: number[];\n readonly timestamp: number;\n}\n\ndeclare var MSDSHEvent: {\n prototype: MSDSHEvent;\n new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent;\n};\n\ninterface MSFIDOCredentialAssertion extends MSAssertion {\n readonly algorithm: string | Algorithm;\n readonly attestation: any;\n readonly publicKey: string;\n readonly transportHints: MSTransportType[];\n}\n\ndeclare var MSFIDOCredentialAssertion: {\n prototype: MSFIDOCredentialAssertion;\n new(): MSFIDOCredentialAssertion;\n};\n\ninterface MSFIDOSignature {\n readonly authnrData: string;\n readonly clientData: string;\n readonly signature: string;\n}\n\ndeclare var MSFIDOSignature: {\n prototype: MSFIDOSignature;\n new(): MSFIDOSignature;\n};\n\ninterface MSFIDOSignatureAssertion extends MSAssertion {\n readonly signature: MSFIDOSignature;\n}\n\ndeclare var MSFIDOSignatureAssertion: {\n prototype: MSFIDOSignatureAssertion;\n new(): MSFIDOSignatureAssertion;\n};\n\ninterface MSFileSaver {\n msSaveBlob(blob: any, defaultName?: string): boolean;\n msSaveOrOpenBlob(blob: any, defaultName?: string): boolean;\n}\n\ninterface MSGesture {\n target: Element;\n addPointer(pointerId: number): void;\n stop(): void;\n}\n\ndeclare var MSGesture: {\n prototype: MSGesture;\n new(): MSGesture;\n};\n\ninterface MSGestureEvent extends UIEvent {\n readonly clientX: number;\n readonly clientY: number;\n readonly expansion: number;\n readonly gestureObject: any;\n readonly hwTimestamp: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly rotation: number;\n readonly scale: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly translationX: number;\n readonly translationY: number;\n readonly velocityAngular: number;\n readonly velocityExpansion: number;\n readonly velocityX: number;\n readonly velocityY: number;\n initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n}\n\ndeclare var MSGestureEvent: {\n prototype: MSGestureEvent;\n new(): MSGestureEvent;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n};\n\ninterface MSGraphicsTrust {\n readonly constrictionActive: boolean;\n readonly status: string;\n}\n\ndeclare var MSGraphicsTrust: {\n prototype: MSGraphicsTrust;\n new(): MSGraphicsTrust;\n};\n\ninterface MSInputMethodContextEventMap {\n \"MSCandidateWindowHide\": Event;\n \"MSCandidateWindowShow\": Event;\n \"MSCandidateWindowUpdate\": Event;\n}\n\ninterface MSInputMethodContext extends EventTarget {\n readonly compositionEndOffset: number;\n readonly compositionStartOffset: number;\n oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null;\n readonly target: HTMLElement;\n getCandidateWindowClientRect(): ClientRect;\n getCompositionAlternatives(): string[];\n hasComposition(): boolean;\n isCandidateWindowVisible(): boolean;\n addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSInputMethodContext: {\n prototype: MSInputMethodContext;\n new(): MSInputMethodContext;\n};\n\ninterface MSMediaKeyError {\n readonly code: number;\n readonly systemCode: number;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n}\n\ndeclare var MSMediaKeyError: {\n prototype: MSMediaKeyError;\n new(): MSMediaKeyError;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n};\n\ninterface MSMediaKeyMessageEvent extends Event {\n readonly destinationURL: string | null;\n readonly message: Uint8Array;\n}\n\ndeclare var MSMediaKeyMessageEvent: {\n prototype: MSMediaKeyMessageEvent;\n new(): MSMediaKeyMessageEvent;\n};\n\ninterface MSMediaKeyNeededEvent extends Event {\n readonly initData: Uint8Array | null;\n}\n\ndeclare var MSMediaKeyNeededEvent: {\n prototype: MSMediaKeyNeededEvent;\n new(): MSMediaKeyNeededEvent;\n};\n\ninterface MSMediaKeySession extends EventTarget {\n readonly error: MSMediaKeyError | null;\n readonly keySystem: string;\n readonly sessionId: string;\n close(): void;\n update(key: Uint8Array): void;\n}\n\ndeclare var MSMediaKeySession: {\n prototype: MSMediaKeySession;\n new(): MSMediaKeySession;\n};\n\ninterface MSMediaKeys {\n readonly keySystem: string;\n createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession;\n}\n\ndeclare var MSMediaKeys: {\n prototype: MSMediaKeys;\n new(keySystem: string): MSMediaKeys;\n isTypeSupported(keySystem: string, type?: string | null): boolean;\n isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string;\n};\n\ninterface MSNavigatorDoNotTrack {\n confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean;\n confirmWebWideTrackingException(args: ExceptionInformation): boolean;\n removeSiteSpecificTrackingException(args: ExceptionInformation): void;\n removeWebWideTrackingException(args: ExceptionInformation): void;\n storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void;\n storeWebWideTrackingException(args: StoreExceptionsInformation): void;\n}\n\ninterface MSPointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var MSPointerEvent: {\n prototype: MSPointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent;\n};\n\ninterface MSStream {\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n}\n\ndeclare var MSStream: {\n prototype: MSStream;\n new(): MSStream;\n};\n\ninterface MSStreamReaderEventMap {\n \"abort\": UIEvent;\n \"error\": ErrorEvent;\n \"load\": Event;\n \"loadend\": ProgressEvent;\n \"loadstart\": Event;\n \"progress\": ProgressEvent;\n}\n\ninterface MSStreamReader extends EventTarget {\n readonly error: DOMError;\n onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null;\n onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null;\n onload: ((this: MSStreamReader, ev: Event) => any) | null;\n onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: MSStreamReader, ev: Event) => any) | null;\n onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: any;\n abort(): void;\n readAsArrayBuffer(stream: MSStream, size?: number): void;\n readAsBinaryString(stream: MSStream, size?: number): void;\n readAsBlob(stream: MSStream, size?: number): void;\n readAsDataURL(stream: MSStream, size?: number): void;\n readAsText(stream: MSStream, encoding?: string, size?: number): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSStreamReader: {\n prototype: MSStreamReader;\n new(): MSStreamReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface MediaDeviceInfo {\n readonly deviceId: string;\n readonly groupId: string;\n readonly kind: MediaDeviceKind;\n readonly label: string;\n}\n\ndeclare var MediaDeviceInfo: {\n prototype: MediaDeviceInfo;\n new(): MediaDeviceInfo;\n};\n\ninterface MediaDevicesEventMap {\n \"devicechange\": Event;\n}\n\ninterface MediaDevices extends EventTarget {\n ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;\n enumerateDevices(): Promise;\n getSupportedConstraints(): MediaTrackSupportedConstraints;\n getUserMedia(constraints: MediaStreamConstraints): Promise;\n addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaDevices: {\n prototype: MediaDevices;\n new(): MediaDevices;\n};\n\ninterface MediaElementAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaElementAudioSourceNode: {\n prototype: MediaElementAudioSourceNode;\n new(): MediaElementAudioSourceNode;\n};\n\ninterface MediaEncryptedEvent extends Event {\n readonly initData: ArrayBuffer | null;\n readonly initDataType: string;\n}\n\ndeclare var MediaEncryptedEvent: {\n prototype: MediaEncryptedEvent;\n new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent;\n};\n\ninterface MediaError {\n readonly code: number;\n readonly msExtendedCode: number;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n}\n\ndeclare var MediaError: {\n prototype: MediaError;\n new(): MediaError;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n};\n\ninterface MediaKeyMessageEvent extends Event {\n readonly message: ArrayBuffer;\n readonly messageType: MediaKeyMessageType;\n}\n\ndeclare var MediaKeyMessageEvent: {\n prototype: MediaKeyMessageEvent;\n new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent;\n};\n\ninterface MediaKeySession extends EventTarget {\n readonly closed: Promise;\n readonly expiration: number;\n readonly keyStatuses: MediaKeyStatusMap;\n readonly sessionId: string;\n close(): Promise;\n generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n load(sessionId: string): Promise;\n remove(): Promise;\n update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeySession: {\n prototype: MediaKeySession;\n new(): MediaKeySession;\n};\n\ninterface MediaKeyStatusMap {\n readonly size: number;\n forEach(callback: Function, thisArg?: any): void;\n get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus;\n has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean;\n}\n\ndeclare var MediaKeyStatusMap: {\n prototype: MediaKeyStatusMap;\n new(): MediaKeyStatusMap;\n};\n\ninterface MediaKeySystemAccess {\n readonly keySystem: string;\n createMediaKeys(): Promise;\n getConfiguration(): MediaKeySystemConfiguration;\n}\n\ndeclare var MediaKeySystemAccess: {\n prototype: MediaKeySystemAccess;\n new(): MediaKeySystemAccess;\n};\n\ninterface MediaKeys {\n createSession(sessionType?: MediaKeySessionType): MediaKeySession;\n setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeys: {\n prototype: MediaKeys;\n new(): MediaKeys;\n};\n\ninterface MediaList {\n readonly length: number;\n mediaText: string;\n appendMedium(medium: string): void;\n deleteMedium(medium: string): void;\n item(index: number): string | null;\n toString(): number;\n [index: number]: string;\n}\n\ndeclare var MediaList: {\n prototype: MediaList;\n new(): MediaList;\n};\n\ninterface MediaQueryList {\n readonly matches: boolean;\n readonly media: string;\n addListener(listener: MediaQueryListListener): void;\n removeListener(listener: MediaQueryListListener): void;\n}\n\ndeclare var MediaQueryList: {\n prototype: MediaQueryList;\n new(): MediaQueryList;\n};\n\ninterface MediaSource extends EventTarget {\n readonly activeSourceBuffers: SourceBufferList;\n duration: number;\n readonly readyState: string;\n readonly sourceBuffers: SourceBufferList;\n addSourceBuffer(type: string): SourceBuffer;\n endOfStream(error?: number): void;\n removeSourceBuffer(sourceBuffer: SourceBuffer): void;\n}\n\ndeclare var MediaSource: {\n prototype: MediaSource;\n new(): MediaSource;\n isTypeSupported(type: string): boolean;\n};\n\ninterface MediaStreamEventMap {\n \"active\": Event;\n \"addtrack\": MediaStreamTrackEvent;\n \"inactive\": Event;\n \"removetrack\": MediaStreamTrackEvent;\n}\n\ninterface MediaStream extends EventTarget {\n readonly active: boolean;\n readonly id: string;\n onactive: ((this: MediaStream, ev: Event) => any) | null;\n onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n oninactive: ((this: MediaStream, ev: Event) => any) | null;\n onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n addTrack(track: MediaStreamTrack): void;\n clone(): MediaStream;\n getAudioTracks(): MediaStreamTrack[];\n getTrackById(trackId: string): MediaStreamTrack | null;\n getTracks(): MediaStreamTrack[];\n getVideoTracks(): MediaStreamTrack[];\n removeTrack(track: MediaStreamTrack): void;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStream: {\n prototype: MediaStream;\n new(): MediaStream;\n new(stream: MediaStream): MediaStream;\n new(tracks: MediaStreamTrack[]): MediaStream;\n};\n\ninterface MediaStreamAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaStreamAudioSourceNode: {\n prototype: MediaStreamAudioSourceNode;\n new(): MediaStreamAudioSourceNode;\n};\n\ninterface MediaStreamError {\n readonly constraintName: string | null;\n readonly message: string | null;\n readonly name: string;\n}\n\ndeclare var MediaStreamError: {\n prototype: MediaStreamError;\n new(): MediaStreamError;\n};\n\ninterface MediaStreamErrorEvent extends Event {\n readonly error: MediaStreamError | null;\n}\n\ndeclare var MediaStreamErrorEvent: {\n prototype: MediaStreamErrorEvent;\n new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent;\n};\n\ninterface MediaStreamEvent extends Event {\n readonly stream: MediaStream | null;\n}\n\ndeclare var MediaStreamEvent: {\n prototype: MediaStreamEvent;\n new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent;\n};\n\ninterface MediaStreamTrackEventMap {\n \"ended\": MediaStreamErrorEvent;\n \"mute\": Event;\n \"overconstrained\": MediaStreamErrorEvent;\n \"unmute\": Event;\n}\n\ninterface MediaStreamTrack extends EventTarget {\n enabled: boolean;\n readonly id: string;\n readonly kind: string;\n readonly label: string;\n readonly muted: boolean;\n onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n readonly readonly: boolean;\n readonly readyState: MediaStreamTrackState;\n readonly remote: boolean;\n applyConstraints(constraints: MediaTrackConstraints): Promise;\n clone(): MediaStreamTrack;\n getCapabilities(): MediaTrackCapabilities;\n getConstraints(): MediaTrackConstraints;\n getSettings(): MediaTrackSettings;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStreamTrack: {\n prototype: MediaStreamTrack;\n new(): MediaStreamTrack;\n};\n\ninterface MediaStreamTrackEvent extends Event {\n readonly track: MediaStreamTrack;\n}\n\ndeclare var MediaStreamTrackEvent: {\n prototype: MediaStreamTrackEvent;\n new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent;\n};\n\ninterface MessageChannel {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\ndeclare var MessageChannel: {\n prototype: MessageChannel;\n new(): MessageChannel;\n};\n\ninterface MessageEvent extends Event {\n readonly data: any;\n readonly origin: string;\n readonly ports: ReadonlyArray;\n readonly source: Window | null;\n initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void;\n}\n\ndeclare var MessageEvent: {\n prototype: MessageEvent;\n new(type: string, eventInitDict?: MessageEventInit): MessageEvent;\n};\n\ninterface MessagePortEventMap {\n \"message\": MessageEvent;\n}\n\ninterface MessagePort extends EventTarget {\n onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;\n close(): void;\n postMessage(message?: any, transfer?: any[]): void;\n start(): void;\n addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MessagePort: {\n prototype: MessagePort;\n new(): MessagePort;\n};\n\ninterface MimeType {\n readonly description: string;\n readonly enabledPlugin: Plugin;\n readonly suffixes: string;\n readonly type: string;\n}\n\ndeclare var MimeType: {\n prototype: MimeType;\n new(): MimeType;\n};\n\ninterface MimeTypeArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(type: string): Plugin;\n [index: number]: Plugin;\n}\n\ndeclare var MimeTypeArray: {\n prototype: MimeTypeArray;\n new(): MimeTypeArray;\n};\n\ninterface MouseEvent extends UIEvent {\n readonly altKey: boolean;\n readonly button: number;\n readonly buttons: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly ctrlKey: boolean;\n /** @deprecated */\n readonly fromElement: Element;\n readonly layerX: number;\n readonly layerY: number;\n readonly metaKey: boolean;\n readonly movementX: number;\n readonly movementY: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly relatedTarget: EventTarget;\n readonly screenX: number;\n readonly screenY: number;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly toElement: Element;\n /** @deprecated */\n readonly which: number;\n readonly x: number;\n readonly y: number;\n getModifierState(keyArg: string): boolean;\n initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;\n}\n\ndeclare var MouseEvent: {\n prototype: MouseEvent;\n new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;\n};\n\ninterface MutationEvent extends Event {\n readonly attrChange: number;\n readonly attrName: string;\n readonly newValue: string;\n readonly prevValue: string;\n readonly relatedNode: Node;\n initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n}\n\ndeclare var MutationEvent: {\n prototype: MutationEvent;\n new(): MutationEvent;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n};\n\ninterface MutationObserver {\n disconnect(): void;\n observe(target: Node, options: MutationObserverInit): void;\n takeRecords(): MutationRecord[];\n}\n\ndeclare var MutationObserver: {\n prototype: MutationObserver;\n new(callback: MutationCallback): MutationObserver;\n};\n\ninterface MutationRecord {\n readonly addedNodes: NodeList;\n readonly attributeName: string | null;\n readonly attributeNamespace: string | null;\n readonly nextSibling: Node | null;\n readonly oldValue: string | null;\n readonly previousSibling: Node | null;\n readonly removedNodes: NodeList;\n readonly target: Node;\n readonly type: MutationRecordType;\n}\n\ndeclare var MutationRecord: {\n prototype: MutationRecord;\n new(): MutationRecord;\n};\n\ninterface NamedNodeMap {\n readonly length: number;\n getNamedItem(qualifiedName: string): Attr | null;\n getNamedItemNS(namespace: string | null, localName: string): Attr | null;\n item(index: number): Attr | null;\n removeNamedItem(qualifiedName: string): Attr;\n removeNamedItemNS(namespace: string | null, localName: string): Attr;\n setNamedItem(attr: Attr): Attr | null;\n setNamedItemNS(attr: Attr): Attr | null;\n [index: number]: Attr;\n}\n\ndeclare var NamedNodeMap: {\n prototype: NamedNodeMap;\n new(): NamedNodeMap;\n};\n\ninterface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage {\n readonly activeVRDisplays: ReadonlyArray;\n readonly authentication: WebAuthentication;\n readonly cookieEnabled: boolean;\n readonly doNotTrack: string | null;\n gamepadInputEmulation: GamepadInputEmulationType;\n readonly geolocation: Geolocation;\n readonly maxTouchPoints: number;\n readonly mimeTypes: MimeTypeArray;\n readonly msManipulationViewsEnabled: boolean;\n readonly msMaxTouchPoints: number;\n readonly msPointerEnabled: boolean;\n readonly plugins: PluginArray;\n readonly pointerEnabled: boolean;\n readonly serviceWorker: ServiceWorkerContainer;\n readonly webdriver: boolean;\n getGamepads(): (Gamepad | null)[];\n getVRDisplays(): Promise;\n javaEnabled(): boolean;\n msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;\n requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise;\n vibrate(pattern: number | number[]): boolean;\n}\n\ndeclare var Navigator: {\n prototype: Navigator;\n new(): Navigator;\n};\n\ninterface NavigatorBeacon {\n sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean;\n}\n\ninterface NavigatorConcurrentHardware {\n readonly hardwareConcurrency: number;\n}\n\ninterface NavigatorContentUtils {\n}\n\ninterface NavigatorID {\n readonly appCodeName: string;\n readonly appName: string;\n readonly appVersion: string;\n readonly platform: string;\n readonly product: string;\n readonly productSub: string;\n readonly userAgent: string;\n readonly vendor: string;\n readonly vendorSub: string;\n}\n\ninterface NavigatorLanguage {\n readonly language: string;\n readonly languages: ReadonlyArray;\n}\n\ninterface NavigatorOnLine {\n readonly onLine: boolean;\n}\n\ninterface NavigatorStorageUtils {\n}\n\ninterface NavigatorUserMedia {\n readonly mediaDevices: MediaDevices;\n getDisplayMedia(constraints: MediaStreamConstraints): Promise;\n getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;\n}\n\ninterface Node extends EventTarget {\n readonly baseURI: string | null;\n readonly childNodes: NodeListOf;\n readonly firstChild: Node | null;\n readonly lastChild: Node | null;\n readonly localName: string | null;\n readonly namespaceURI: string | null;\n readonly nextSibling: Node | null;\n readonly nodeName: string;\n readonly nodeType: number;\n nodeValue: string | null;\n readonly ownerDocument: Document;\n readonly parentElement: HTMLElement | null;\n readonly parentNode: Node | null;\n readonly previousSibling: Node | null;\n textContent: string | null;\n appendChild(newChild: T): T;\n cloneNode(deep?: boolean): Node;\n compareDocumentPosition(other: Node): number;\n contains(child: Node): boolean;\n hasChildNodes(): boolean;\n insertBefore(newChild: T, refChild: Node | null): T;\n isDefaultNamespace(namespaceURI: string | null): boolean;\n isEqualNode(arg: Node): boolean;\n isSameNode(other: Node): boolean;\n lookupNamespaceURI(prefix: string | null): string | null;\n lookupPrefix(namespaceURI: string | null): string | null;\n normalize(): void;\n removeChild(oldChild: T): T;\n replaceChild(newChild: Node, oldChild: T): T;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n}\n\ndeclare var Node: {\n prototype: Node;\n new(): Node;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n};\n\ninterface NodeFilter {\n acceptNode(node: Node): number;\n}\n\ndeclare var NodeFilter: {\n readonly FILTER_ACCEPT: number;\n readonly FILTER_REJECT: number;\n readonly FILTER_SKIP: number;\n readonly SHOW_ALL: number;\n readonly SHOW_ATTRIBUTE: number;\n readonly SHOW_CDATA_SECTION: number;\n readonly SHOW_COMMENT: number;\n readonly SHOW_DOCUMENT: number;\n readonly SHOW_DOCUMENT_FRAGMENT: number;\n readonly SHOW_DOCUMENT_TYPE: number;\n readonly SHOW_ELEMENT: number;\n readonly SHOW_ENTITY: number;\n readonly SHOW_ENTITY_REFERENCE: number;\n readonly SHOW_NOTATION: number;\n readonly SHOW_PROCESSING_INSTRUCTION: number;\n readonly SHOW_TEXT: number;\n};\n\ninterface NodeIterator {\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n detach(): void;\n nextNode(): Node | null;\n previousNode(): Node | null;\n}\n\ndeclare var NodeIterator: {\n prototype: NodeIterator;\n new(): NodeIterator;\n};\n\ninterface NodeList {\n readonly length: number;\n item(index: number): Node;\n [index: number]: Node;\n}\n\ndeclare var NodeList: {\n prototype: NodeList;\n new(): NodeList;\n};\n\ninterface NodeListOf extends NodeList {\n length: number;\n item(index: number): TNode;\n [index: number]: TNode;\n}\n\ninterface NodeSelector {\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface NotificationEventMap {\n \"click\": Event;\n \"close\": Event;\n \"error\": Event;\n \"show\": Event;\n}\n\ninterface Notification extends EventTarget {\n readonly body: string | null;\n readonly data: any;\n readonly dir: NotificationDirection;\n readonly icon: string | null;\n readonly lang: string | null;\n onclick: ((this: Notification, ev: Event) => any) | null;\n onclose: ((this: Notification, ev: Event) => any) | null;\n onerror: ((this: Notification, ev: Event) => any) | null;\n onshow: ((this: Notification, ev: Event) => any) | null;\n readonly permission: NotificationPermission;\n readonly tag: string | null;\n readonly title: string;\n close(): void;\n addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Notification: {\n prototype: Notification;\n new(title: string, options?: NotificationOptions): Notification;\n requestPermission(callback?: NotificationPermissionCallback): Promise;\n};\n\ninterface OES_element_index_uint {\n}\n\ndeclare var OES_element_index_uint: {\n prototype: OES_element_index_uint;\n new(): OES_element_index_uint;\n};\n\ninterface OES_standard_derivatives {\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n}\n\ndeclare var OES_standard_derivatives: {\n prototype: OES_standard_derivatives;\n new(): OES_standard_derivatives;\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n};\n\ninterface OES_texture_float {\n}\n\ndeclare var OES_texture_float: {\n prototype: OES_texture_float;\n new(): OES_texture_float;\n};\n\ninterface OES_texture_float_linear {\n}\n\ndeclare var OES_texture_float_linear: {\n prototype: OES_texture_float_linear;\n new(): OES_texture_float_linear;\n};\n\ninterface OES_texture_half_float {\n readonly HALF_FLOAT_OES: number;\n}\n\ndeclare var OES_texture_half_float: {\n prototype: OES_texture_half_float;\n new(): OES_texture_half_float;\n readonly HALF_FLOAT_OES: number;\n};\n\ninterface OES_texture_half_float_linear {\n}\n\ndeclare var OES_texture_half_float_linear: {\n prototype: OES_texture_half_float_linear;\n new(): OES_texture_half_float_linear;\n};\n\ninterface OES_vertex_array_object {\n readonly VERTEX_ARRAY_BINDING_OES: number;\n bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n createVertexArrayOES(): WebGLVertexArrayObjectOES;\n deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES;\n}\n\ninterface OfflineAudioCompletionEvent extends Event {\n readonly renderedBuffer: AudioBuffer;\n}\n\ndeclare var OfflineAudioCompletionEvent: {\n prototype: OfflineAudioCompletionEvent;\n new(): OfflineAudioCompletionEvent;\n};\n\ninterface OfflineAudioContextEventMap extends AudioContextEventMap {\n \"complete\": OfflineAudioCompletionEvent;\n}\n\ninterface OfflineAudioContext extends AudioContextBase {\n readonly length: number;\n oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null;\n startRendering(): Promise;\n suspend(suspendTime: number): Promise;\n addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OfflineAudioContext: {\n prototype: OfflineAudioContext;\n new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext;\n};\n\ninterface OscillatorNodeEventMap {\n \"ended\": Event;\n}\n\ninterface OscillatorNode extends AudioNode {\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n onended: ((this: OscillatorNode, ev: Event) => any) | null;\n type: OscillatorType;\n setPeriodicWave(periodicWave: PeriodicWave): void;\n start(when?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OscillatorNode: {\n prototype: OscillatorNode;\n new(): OscillatorNode;\n};\n\ninterface OverflowEvent extends UIEvent {\n readonly horizontalOverflow: boolean;\n readonly orient: number;\n readonly verticalOverflow: boolean;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n}\n\ndeclare var OverflowEvent: {\n prototype: OverflowEvent;\n new(): OverflowEvent;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n};\n\ninterface PageTransitionEvent extends Event {\n readonly persisted: boolean;\n}\n\ndeclare var PageTransitionEvent: {\n prototype: PageTransitionEvent;\n new(): PageTransitionEvent;\n};\n\ninterface PannerNode extends AudioNode {\n coneInnerAngle: number;\n coneOuterAngle: number;\n coneOuterGain: number;\n distanceModel: DistanceModelType;\n maxDistance: number;\n panningModel: PanningModelType;\n refDistance: number;\n rolloffFactor: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n /** @deprecated */\n setVelocity(x: number, y: number, z: number): void;\n}\n\ndeclare var PannerNode: {\n prototype: PannerNode;\n new(): PannerNode;\n};\n\ninterface ParentNode {\n readonly children: HTMLCollection;\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface ParentNode {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n}\n\ninterface Path2D extends CanvasPathMethods {\n}\n\ndeclare var Path2D: {\n prototype: Path2D;\n new(d?: Path2D | string): Path2D;\n};\n\ninterface PaymentAddress {\n readonly addressLine: string[];\n readonly city: string;\n readonly country: string;\n readonly dependentLocality: string;\n readonly languageCode: string;\n readonly organization: string;\n readonly phone: string;\n readonly postalCode: string;\n readonly recipient: string;\n readonly region: string;\n readonly sortingCode: string;\n toJSON(): any;\n}\n\ndeclare var PaymentAddress: {\n prototype: PaymentAddress;\n new(): PaymentAddress;\n};\n\ninterface PaymentRequestEventMap {\n \"shippingaddresschange\": Event;\n \"shippingoptionchange\": Event;\n}\n\ninterface PaymentRequest extends EventTarget {\n readonly id: string;\n onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null;\n onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n readonly shippingType: PaymentShippingType | null;\n abort(): Promise;\n canMakePayment(): Promise;\n show(): Promise;\n addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var PaymentRequest: {\n prototype: PaymentRequest;\n new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest;\n};\n\ninterface PaymentRequestUpdateEvent extends Event {\n updateWith(detailsPromise: Promise): void;\n}\n\ndeclare var PaymentRequestUpdateEvent: {\n prototype: PaymentRequestUpdateEvent;\n new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;\n};\n\ninterface PaymentResponse {\n readonly details: any;\n readonly methodName: string;\n readonly payerEmail: string | null;\n readonly payerName: string | null;\n readonly payerPhone: string | null;\n readonly requestId: string;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n complete(result?: PaymentComplete): Promise;\n toJSON(): any;\n}\n\ndeclare var PaymentResponse: {\n prototype: PaymentResponse;\n new(): PaymentResponse;\n};\n\ninterface PerfWidgetExternal {\n readonly activeNetworkRequestCount: number;\n readonly averageFrameTime: number;\n readonly averagePaintTime: number;\n readonly extraInformationEnabled: boolean;\n readonly independentRenderingEnabled: boolean;\n readonly irDisablingContentString: string;\n readonly irStatusAvailable: boolean;\n readonly maxCpuSpeed: number;\n readonly paintRequestsPerSecond: number;\n readonly performanceCounter: number;\n readonly performanceCounterFrequency: number;\n addEventListener(eventType: string, callback: Function): void;\n getMemoryUsage(): number;\n getProcessCpuUsage(): number;\n getRecentCpuUsage(last: number | null): any;\n getRecentFrames(last: number | null): any;\n getRecentMemoryUsage(last: number | null): any;\n getRecentPaintRequests(last: number | null): any;\n removeEventListener(eventType: string, callback: Function): void;\n repositionWindow(x: number, y: number): void;\n resizeWindow(width: number, height: number): void;\n}\n\ndeclare var PerfWidgetExternal: {\n prototype: PerfWidgetExternal;\n new(): PerfWidgetExternal;\n};\n\ninterface Performance {\n /** @deprecated */\n readonly navigation: PerformanceNavigation;\n readonly timeOrigin: number;\n /** @deprecated */\n readonly timing: PerformanceTiming;\n clearMarks(markName?: string): void;\n clearMeasures(measureName?: string): void;\n clearResourceTimings(): void;\n getEntries(): any;\n getEntriesByName(name: string, type?: string): any;\n getEntriesByType(type: string): any;\n /** @deprecated */\n getMarks(markName?: string): any;\n /** @deprecated */\n getMeasures(measureName?: string): any;\n mark(markName: string): void;\n measure(measureName: string, startMarkName?: string, endMarkName?: string): void;\n now(): number;\n setResourceTimingBufferSize(maxSize: number): void;\n toJSON(): any;\n}\n\ndeclare var Performance: {\n prototype: Performance;\n new(): Performance;\n};\n\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceEntry: {\n prototype: PerformanceEntry;\n new(): PerformanceEntry;\n};\n\ninterface PerformanceMark extends PerformanceEntry {\n}\n\ndeclare var PerformanceMark: {\n prototype: PerformanceMark;\n new(): PerformanceMark;\n};\n\ninterface PerformanceMeasure extends PerformanceEntry {\n}\n\ndeclare var PerformanceMeasure: {\n prototype: PerformanceMeasure;\n new(): PerformanceMeasure;\n};\n\ninterface PerformanceNavigation {\n readonly redirectCount: number;\n readonly type: number;\n toJSON(): any;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n}\n\ndeclare var PerformanceNavigation: {\n prototype: PerformanceNavigation;\n new(): PerformanceNavigation;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n};\n\ninterface PerformanceNavigationTiming extends PerformanceEntry {\n /** @deprecated */\n readonly connectEnd: number;\n /** @deprecated */\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n /** @deprecated */\n readonly domLoading: number;\n /** @deprecated */\n readonly domainLookupEnd: number;\n /** @deprecated */\n readonly domainLookupStart: number;\n /** @deprecated */\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n /** @deprecated */\n readonly navigationStart: number;\n readonly redirectCount: number;\n /** @deprecated */\n readonly redirectEnd: number;\n /** @deprecated */\n readonly redirectStart: number;\n /** @deprecated */\n readonly requestStart: number;\n /** @deprecated */\n readonly responseEnd: number;\n /** @deprecated */\n readonly responseStart: number;\n readonly type: NavigationType;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n readonly workerStart: number;\n}\n\ndeclare var PerformanceNavigationTiming: {\n prototype: PerformanceNavigationTiming;\n new(): PerformanceNavigationTiming;\n};\n\ninterface PerformanceResourceTiming extends PerformanceEntry {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly initiatorType: string;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly workerStart: number;\n}\n\ndeclare var PerformanceResourceTiming: {\n prototype: PerformanceResourceTiming;\n new(): PerformanceResourceTiming;\n};\n\ninterface PerformanceTiming {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly domLoading: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly msFirstPaint: number;\n readonly navigationStart: number;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceTiming: {\n prototype: PerformanceTiming;\n new(): PerformanceTiming;\n};\n\ninterface PeriodicWave {\n}\n\ndeclare var PeriodicWave: {\n prototype: PeriodicWave;\n new(): PeriodicWave;\n};\n\ninterface PermissionRequest extends DeferredPermissionRequest {\n readonly state: MSWebViewPermissionState;\n defer(): void;\n}\n\ndeclare var PermissionRequest: {\n prototype: PermissionRequest;\n new(): PermissionRequest;\n};\n\ninterface PermissionRequestedEvent extends Event {\n readonly permissionRequest: PermissionRequest;\n}\n\ndeclare var PermissionRequestedEvent: {\n prototype: PermissionRequestedEvent;\n new(): PermissionRequestedEvent;\n};\n\ninterface Plugin {\n readonly description: string;\n readonly filename: string;\n readonly length: number;\n readonly name: string;\n readonly version: string;\n item(index: number): MimeType;\n namedItem(type: string): MimeType;\n [index: number]: MimeType;\n}\n\ndeclare var Plugin: {\n prototype: Plugin;\n new(): Plugin;\n};\n\ninterface PluginArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(name: string): Plugin;\n refresh(reload?: boolean): void;\n [index: number]: Plugin;\n}\n\ndeclare var PluginArray: {\n prototype: PluginArray;\n new(): PluginArray;\n};\n\ninterface PointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var PointerEvent: {\n prototype: PointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent;\n};\n\ninterface PopStateEvent extends Event {\n readonly state: any;\n}\n\ndeclare var PopStateEvent: {\n prototype: PopStateEvent;\n new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent;\n};\n\ninterface Position {\n readonly coords: Coordinates;\n readonly timestamp: number;\n}\n\ndeclare var Position: {\n prototype: Position;\n new(): Position;\n};\n\ninterface PositionError {\n readonly code: number;\n readonly message: string;\n toString(): string;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n}\n\ndeclare var PositionError: {\n prototype: PositionError;\n new(): PositionError;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n};\n\ninterface ProcessingInstruction extends CharacterData {\n readonly target: string;\n}\n\ndeclare var ProcessingInstruction: {\n prototype: ProcessingInstruction;\n new(): ProcessingInstruction;\n};\n\ninterface ProgressEvent extends Event {\n readonly lengthComputable: boolean;\n readonly loaded: number;\n readonly total: number;\n initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;\n}\n\ndeclare var ProgressEvent: {\n prototype: ProgressEvent;\n new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent;\n};\n\ninterface PromiseRejectionEvent extends Event {\n readonly promise: PromiseLike;\n readonly reason: any;\n}\n\ninterface PromiseRejectionEventInit extends EventInit {\n promise: PromiseLike;\n reason?: any;\n}\n\ninterface PushManager {\n readonly supportedContentEncodings: ReadonlyArray;\n getSubscription(): Promise;\n permissionState(options?: PushSubscriptionOptionsInit): Promise;\n subscribe(options?: PushSubscriptionOptionsInit): Promise;\n}\n\ndeclare var PushManager: {\n prototype: PushManager;\n new(): PushManager;\n};\n\ninterface PushSubscription {\n readonly endpoint: string;\n readonly expirationTime: number | null;\n readonly options: PushSubscriptionOptions;\n getKey(name: PushEncryptionKeyName): ArrayBuffer | null;\n toJSON(): any;\n unsubscribe(): Promise;\n}\n\ndeclare var PushSubscription: {\n prototype: PushSubscription;\n new(): PushSubscription;\n};\n\ninterface PushSubscriptionOptions {\n readonly applicationServerKey: ArrayBuffer | null;\n readonly userVisibleOnly: boolean;\n}\n\ndeclare var PushSubscriptionOptions: {\n prototype: PushSubscriptionOptions;\n new(): PushSubscriptionOptions;\n};\n\ninterface RTCDTMFToneChangeEvent extends Event {\n readonly tone: string;\n}\n\ndeclare var RTCDTMFToneChangeEvent: {\n prototype: RTCDTMFToneChangeEvent;\n new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent;\n};\n\ninterface RTCDtlsTransportEventMap {\n \"dtlsstatechange\": RTCDtlsTransportStateChangedEvent;\n \"error\": Event;\n}\n\ninterface RTCDtlsTransport extends RTCStatsProvider {\n ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null;\n onerror: ((this: RTCDtlsTransport, ev: Event) => any) | null;\n readonly state: RTCDtlsTransportState;\n readonly transport: RTCIceTransport;\n getLocalParameters(): RTCDtlsParameters;\n getRemoteCertificates(): ArrayBuffer[];\n getRemoteParameters(): RTCDtlsParameters | null;\n start(remoteParameters: RTCDtlsParameters): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtlsTransport: {\n prototype: RTCDtlsTransport;\n new(transport: RTCIceTransport): RTCDtlsTransport;\n};\n\ninterface RTCDtlsTransportStateChangedEvent extends Event {\n readonly state: RTCDtlsTransportState;\n}\n\ndeclare var RTCDtlsTransportStateChangedEvent: {\n prototype: RTCDtlsTransportStateChangedEvent;\n new(): RTCDtlsTransportStateChangedEvent;\n};\n\ninterface RTCDtmfSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDtmfSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n readonly duration: number;\n readonly interToneGap: number;\n ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly sender: RTCRtpSender;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtmfSender: {\n prototype: RTCDtmfSender;\n new(sender: RTCRtpSender): RTCDtmfSender;\n};\n\ninterface RTCIceCandidate {\n candidate: string | null;\n sdpMLineIndex: number | null;\n sdpMid: string | null;\n toJSON(): any;\n}\n\ndeclare var RTCIceCandidate: {\n prototype: RTCIceCandidate;\n new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate;\n};\n\ninterface RTCIceCandidatePairChangedEvent extends Event {\n readonly pair: RTCIceCandidatePair;\n}\n\ndeclare var RTCIceCandidatePairChangedEvent: {\n prototype: RTCIceCandidatePairChangedEvent;\n new(): RTCIceCandidatePairChangedEvent;\n};\n\ninterface RTCIceGathererEventMap {\n \"error\": Event;\n \"localcandidate\": RTCIceGathererEvent;\n}\n\ninterface RTCIceGatherer extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n onerror: ((this: RTCIceGatherer, ev: Event) => any) | null;\n onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null;\n createAssociatedGatherer(): RTCIceGatherer;\n getLocalCandidates(): RTCIceCandidateDictionary[];\n getLocalParameters(): RTCIceParameters;\n addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceGatherer: {\n prototype: RTCIceGatherer;\n new(options: RTCIceGatherOptions): RTCIceGatherer;\n};\n\ninterface RTCIceGathererEvent extends Event {\n readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete;\n}\n\ndeclare var RTCIceGathererEvent: {\n prototype: RTCIceGathererEvent;\n new(): RTCIceGathererEvent;\n};\n\ninterface RTCIceTransportEventMap {\n \"candidatepairchange\": RTCIceCandidatePairChangedEvent;\n \"icestatechange\": RTCIceTransportStateChangedEvent;\n}\n\ninterface RTCIceTransport extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n readonly iceGatherer: RTCIceGatherer | null;\n oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null;\n onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null;\n readonly role: RTCIceRole;\n readonly state: RTCIceTransportState;\n addRemoteCandidate(remoteCandidate: RTCIceCandidateDictionary | RTCIceCandidateComplete): void;\n createAssociatedTransport(): RTCIceTransport;\n getNominatedCandidatePair(): RTCIceCandidatePair | null;\n getRemoteCandidates(): RTCIceCandidateDictionary[];\n getRemoteParameters(): RTCIceParameters | null;\n setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void;\n start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceTransport: {\n prototype: RTCIceTransport;\n new(): RTCIceTransport;\n};\n\ninterface RTCIceTransportStateChangedEvent extends Event {\n readonly state: RTCIceTransportState;\n}\n\ndeclare var RTCIceTransportStateChangedEvent: {\n prototype: RTCIceTransportStateChangedEvent;\n new(): RTCIceTransportStateChangedEvent;\n};\n\ninterface RTCPeerConnectionEventMap {\n \"addstream\": MediaStreamEvent;\n \"icecandidate\": RTCPeerConnectionIceEvent;\n \"iceconnectionstatechange\": Event;\n \"icegatheringstatechange\": Event;\n \"negotiationneeded\": Event;\n \"removestream\": MediaStreamEvent;\n \"signalingstatechange\": Event;\n}\n\ninterface RTCPeerConnection extends EventTarget {\n readonly canTrickleIceCandidates: boolean | null;\n readonly iceConnectionState: RTCIceConnectionState;\n readonly iceGatheringState: RTCIceGatheringState;\n readonly localDescription: RTCSessionDescription | null;\n onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null;\n onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null;\n oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null;\n onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n readonly remoteDescription: RTCSessionDescription | null;\n readonly signalingState: RTCSignalingState;\n addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise;\n addStream(stream: MediaStream): void;\n close(): void;\n createAnswer(options?: RTCOfferOptions): Promise;\n createOffer(options?: RTCOfferOptions): Promise;\n getConfiguration(): RTCConfiguration;\n getLocalStreams(): MediaStream[];\n getRemoteStreams(): MediaStream[];\n getStats(selector: MediaStreamTrack | null, successCallback?: RTCStatsCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise;\n getStreamById(streamId: string): MediaStream | null;\n removeStream(stream: MediaStream): void;\n setLocalDescription(description: RTCSessionDescriptionInit): Promise;\n setRemoteDescription(description: RTCSessionDescriptionInit): Promise;\n addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCPeerConnection: {\n prototype: RTCPeerConnection;\n new(configuration: RTCConfiguration): RTCPeerConnection;\n};\n\ninterface RTCPeerConnectionIceEvent extends Event {\n readonly candidate: RTCIceCandidate;\n}\n\ndeclare var RTCPeerConnectionIceEvent: {\n prototype: RTCPeerConnectionIceEvent;\n new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent;\n};\n\ninterface RTCRtpReceiverEventMap {\n \"error\": Event;\n \"msdecodercapacitychange\": Event;\n \"msdsh\": Event;\n}\n\ninterface RTCRtpReceiver extends RTCStatsProvider {\n onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n readonly rtcpTransport: RTCDtlsTransport;\n readonly track: MediaStreamTrack | null;\n readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport;\n getContributingSources(): RTCRtpContributingSource[];\n receive(parameters: RTCRtpParameters): void;\n requestSendCSRC(csrc: number): void;\n setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCRtpReceiver: {\n prototype: RTCRtpReceiver;\n new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver;\n getCapabilities(kind?: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpSenderEventMap {\n \"error\": Event;\n \"ssrcconflict\": RTCSsrcConflictEvent;\n}\n\ninterface RTCRtpSender extends RTCStatsProvider {\n onerror: ((this: RTCRtpSender, ev: Event) => any) | null;\n onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null;\n readonly rtcpTransport: RTCDtlsTransport;\n readonly track: MediaStreamTrack;\n readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport;\n send(parameters: RTCRtpParameters): void;\n setTrack(track: MediaStreamTrack): void;\n setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCRtpSender: {\n prototype: RTCRtpSender;\n new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender;\n getCapabilities(kind?: string): RTCRtpCapabilities;\n};\n\ninterface RTCSessionDescription {\n sdp: string | null;\n type: RTCSdpType | null;\n toJSON(): any;\n}\n\ndeclare var RTCSessionDescription: {\n prototype: RTCSessionDescription;\n new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription;\n};\n\ninterface RTCSrtpSdesTransportEventMap {\n \"error\": Event;\n}\n\ninterface RTCSrtpSdesTransport extends EventTarget {\n onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null;\n readonly transport: RTCIceTransport;\n addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSrtpSdesTransport: {\n prototype: RTCSrtpSdesTransport;\n new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport;\n getLocalParameters(): RTCSrtpSdesParameters[];\n};\n\ninterface RTCSsrcConflictEvent extends Event {\n readonly ssrc: number;\n}\n\ndeclare var RTCSsrcConflictEvent: {\n prototype: RTCSsrcConflictEvent;\n new(): RTCSsrcConflictEvent;\n};\n\ninterface RTCStatsProvider extends EventTarget {\n getStats(): Promise;\n msGetStats(): Promise;\n}\n\ndeclare var RTCStatsProvider: {\n prototype: RTCStatsProvider;\n new(): RTCStatsProvider;\n};\n\ninterface RandomSource {\n getRandomValues(array: T): T;\n}\n\ndeclare var RandomSource: {\n prototype: RandomSource;\n new(): RandomSource;\n};\n\ninterface Range {\n readonly collapsed: boolean;\n readonly commonAncestorContainer: Node;\n readonly endContainer: Node;\n readonly endOffset: number;\n readonly startContainer: Node;\n readonly startOffset: number;\n cloneContents(): DocumentFragment;\n cloneRange(): Range;\n collapse(toStart?: boolean): void;\n compareBoundaryPoints(how: number, sourceRange: Range): number;\n createContextualFragment(fragment: string): DocumentFragment;\n deleteContents(): void;\n detach(): void;\n expand(Unit: ExpandGranularity): boolean;\n extractContents(): DocumentFragment;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n insertNode(node: Node): void;\n isPointInRange(node: Node, offset: number): boolean;\n selectNode(node: Node): void;\n selectNodeContents(node: Node): void;\n setEnd(node: Node, offset: number): void;\n setEndAfter(node: Node): void;\n setEndBefore(node: Node): void;\n setStart(node: Node, offset: number): void;\n setStartAfter(node: Node): void;\n setStartBefore(node: Node): void;\n surroundContents(newParent: Node): void;\n toString(): string;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n}\n\ndeclare var Range: {\n prototype: Range;\n new(): Range;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n};\n\ninterface ReadableStream {\n readonly locked: boolean;\n cancel(): Promise;\n getReader(): ReadableStreamReader;\n}\n\ndeclare var ReadableStream: {\n prototype: ReadableStream;\n new(): ReadableStream;\n};\n\ninterface ReadableStreamReader {\n cancel(): Promise;\n read(): Promise;\n releaseLock(): void;\n}\n\ndeclare var ReadableStreamReader: {\n prototype: ReadableStreamReader;\n new(): ReadableStreamReader;\n};\n\ninterface Request extends Body {\n readonly cache: RequestCache;\n readonly credentials: RequestCredentials;\n readonly destination: RequestDestination;\n readonly headers: Headers;\n readonly integrity: string;\n readonly keepalive: boolean;\n readonly method: string;\n readonly mode: RequestMode;\n readonly redirect: RequestRedirect;\n readonly referrer: string;\n readonly referrerPolicy: ReferrerPolicy;\n readonly signal: AbortSignal | null;\n readonly type: RequestType;\n readonly url: string;\n clone(): Request;\n}\n\ndeclare var Request: {\n prototype: Request;\n new(input: Request | string, init?: RequestInit): Request;\n};\n\ninterface Response extends Body {\n readonly body: ReadableStream | null;\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\ndeclare var Response: {\n prototype: Response;\n new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response;\n error(): Response;\n redirect(url: string, status?: number): Response;\n};\n\ninterface SVGAElement extends SVGGraphicsElement, SVGURIReference {\n readonly target: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGAElement: {\n prototype: SVGAElement;\n new(): SVGAElement;\n};\n\ninterface SVGAngle {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n}\n\ndeclare var SVGAngle: {\n prototype: SVGAngle;\n new(): SVGAngle;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n};\n\ninterface SVGAnimatedAngle {\n readonly animVal: SVGAngle;\n readonly baseVal: SVGAngle;\n}\n\ndeclare var SVGAnimatedAngle: {\n prototype: SVGAnimatedAngle;\n new(): SVGAnimatedAngle;\n};\n\ninterface SVGAnimatedBoolean {\n readonly animVal: boolean;\n baseVal: boolean;\n}\n\ndeclare var SVGAnimatedBoolean: {\n prototype: SVGAnimatedBoolean;\n new(): SVGAnimatedBoolean;\n};\n\ninterface SVGAnimatedEnumeration {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedEnumeration: {\n prototype: SVGAnimatedEnumeration;\n new(): SVGAnimatedEnumeration;\n};\n\ninterface SVGAnimatedInteger {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedInteger: {\n prototype: SVGAnimatedInteger;\n new(): SVGAnimatedInteger;\n};\n\ninterface SVGAnimatedLength {\n readonly animVal: SVGLength;\n readonly baseVal: SVGLength;\n}\n\ndeclare var SVGAnimatedLength: {\n prototype: SVGAnimatedLength;\n new(): SVGAnimatedLength;\n};\n\ninterface SVGAnimatedLengthList {\n readonly animVal: SVGLengthList;\n readonly baseVal: SVGLengthList;\n}\n\ndeclare var SVGAnimatedLengthList: {\n prototype: SVGAnimatedLengthList;\n new(): SVGAnimatedLengthList;\n};\n\ninterface SVGAnimatedNumber {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedNumber: {\n prototype: SVGAnimatedNumber;\n new(): SVGAnimatedNumber;\n};\n\ninterface SVGAnimatedNumberList {\n readonly animVal: SVGNumberList;\n readonly baseVal: SVGNumberList;\n}\n\ndeclare var SVGAnimatedNumberList: {\n prototype: SVGAnimatedNumberList;\n new(): SVGAnimatedNumberList;\n};\n\ninterface SVGAnimatedPoints {\n readonly animatedPoints: SVGPointList;\n readonly points: SVGPointList;\n}\n\ninterface SVGAnimatedPreserveAspectRatio {\n readonly animVal: SVGPreserveAspectRatio;\n readonly baseVal: SVGPreserveAspectRatio;\n}\n\ndeclare var SVGAnimatedPreserveAspectRatio: {\n prototype: SVGAnimatedPreserveAspectRatio;\n new(): SVGAnimatedPreserveAspectRatio;\n};\n\ninterface SVGAnimatedRect {\n readonly animVal: SVGRect;\n readonly baseVal: SVGRect;\n}\n\ndeclare var SVGAnimatedRect: {\n prototype: SVGAnimatedRect;\n new(): SVGAnimatedRect;\n};\n\ninterface SVGAnimatedString {\n readonly animVal: string;\n baseVal: string;\n}\n\ndeclare var SVGAnimatedString: {\n prototype: SVGAnimatedString;\n new(): SVGAnimatedString;\n};\n\ninterface SVGAnimatedTransformList {\n readonly animVal: SVGTransformList;\n readonly baseVal: SVGTransformList;\n}\n\ndeclare var SVGAnimatedTransformList: {\n prototype: SVGAnimatedTransformList;\n new(): SVGAnimatedTransformList;\n};\n\ninterface SVGCircleElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGCircleElement: {\n prototype: SVGCircleElement;\n new(): SVGCircleElement;\n};\n\ninterface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes {\n readonly clipPathUnits: SVGAnimatedEnumeration;\n addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGClipPathElement: {\n prototype: SVGClipPathElement;\n new(): SVGClipPathElement;\n};\n\ninterface SVGComponentTransferFunctionElement extends SVGElement {\n readonly amplitude: SVGAnimatedNumber;\n readonly exponent: SVGAnimatedNumber;\n readonly intercept: SVGAnimatedNumber;\n readonly offset: SVGAnimatedNumber;\n readonly slope: SVGAnimatedNumber;\n readonly tableValues: SVGAnimatedNumberList;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGComponentTransferFunctionElement: {\n prototype: SVGComponentTransferFunctionElement;\n new(): SVGComponentTransferFunctionElement;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n};\n\ninterface SVGDefsElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDefsElement: {\n prototype: SVGDefsElement;\n new(): SVGDefsElement;\n};\n\ninterface SVGDescElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDescElement: {\n prototype: SVGDescElement;\n new(): SVGDescElement;\n};\n\ninterface SVGElementEventMap extends ElementEventMap {\n \"click\": MouseEvent;\n \"dblclick\": MouseEvent;\n \"focusin\": FocusEvent;\n \"focusout\": FocusEvent;\n \"load\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n}\n\ninterface SVGElement extends Element, ElementCSSInlineStyle {\n readonly className: any;\n onclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onload: ((this: SVGElement, ev: Event) => any) | null;\n onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null;\n readonly ownerSVGElement: SVGSVGElement | null;\n readonly viewportElement: SVGElement | null;\n /** @deprecated */\n xmlbase: string;\n addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGElement: {\n prototype: SVGElement;\n new(): SVGElement;\n};\n\ninterface SVGElementInstance extends EventTarget {\n readonly childNodes: SVGElementInstanceList;\n readonly correspondingElement: SVGElement;\n readonly correspondingUseElement: SVGUseElement;\n readonly firstChild: SVGElementInstance;\n readonly lastChild: SVGElementInstance;\n readonly nextSibling: SVGElementInstance;\n readonly parentNode: SVGElementInstance;\n readonly previousSibling: SVGElementInstance;\n}\n\ndeclare var SVGElementInstance: {\n prototype: SVGElementInstance;\n new(): SVGElementInstance;\n};\n\ninterface SVGElementInstanceList {\n /** @deprecated */\n readonly length: number;\n /** @deprecated */\n item(index: number): SVGElementInstance;\n}\n\ndeclare var SVGElementInstanceList: {\n prototype: SVGElementInstanceList;\n new(): SVGElementInstanceList;\n};\n\ninterface SVGEllipseElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGEllipseElement: {\n prototype: SVGEllipseElement;\n new(): SVGEllipseElement;\n};\n\ninterface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly mode: SVGAnimatedEnumeration;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEBlendElement: {\n prototype: SVGFEBlendElement;\n new(): SVGFEBlendElement;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n};\n\ninterface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly type: SVGAnimatedEnumeration;\n readonly values: SVGAnimatedNumberList;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEColorMatrixElement: {\n prototype: SVGFEColorMatrixElement;\n new(): SVGFEColorMatrixElement;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEComponentTransferElement: {\n prototype: SVGFEComponentTransferElement;\n new(): SVGFEComponentTransferElement;\n};\n\ninterface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly k1: SVGAnimatedNumber;\n readonly k2: SVGAnimatedNumber;\n readonly k3: SVGAnimatedNumber;\n readonly k4: SVGAnimatedNumber;\n readonly operator: SVGAnimatedEnumeration;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFECompositeElement: {\n prototype: SVGFECompositeElement;\n new(): SVGFECompositeElement;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n};\n\ninterface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly bias: SVGAnimatedNumber;\n readonly divisor: SVGAnimatedNumber;\n readonly edgeMode: SVGAnimatedEnumeration;\n readonly in1: SVGAnimatedString;\n readonly kernelMatrix: SVGAnimatedNumberList;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly orderX: SVGAnimatedInteger;\n readonly orderY: SVGAnimatedInteger;\n readonly preserveAlpha: SVGAnimatedBoolean;\n readonly targetX: SVGAnimatedInteger;\n readonly targetY: SVGAnimatedInteger;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEConvolveMatrixElement: {\n prototype: SVGFEConvolveMatrixElement;\n new(): SVGFEConvolveMatrixElement;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n};\n\ninterface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly diffuseConstant: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDiffuseLightingElement: {\n prototype: SVGFEDiffuseLightingElement;\n new(): SVGFEDiffuseLightingElement;\n};\n\ninterface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly scale: SVGAnimatedNumber;\n readonly xChannelSelector: SVGAnimatedEnumeration;\n readonly yChannelSelector: SVGAnimatedEnumeration;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDisplacementMapElement: {\n prototype: SVGFEDisplacementMapElement;\n new(): SVGFEDisplacementMapElement;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n};\n\ninterface SVGFEDistantLightElement extends SVGElement {\n readonly azimuth: SVGAnimatedNumber;\n readonly elevation: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDistantLightElement: {\n prototype: SVGFEDistantLightElement;\n new(): SVGFEDistantLightElement;\n};\n\ninterface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFloodElement: {\n prototype: SVGFEFloodElement;\n new(): SVGFEFloodElement;\n};\n\ninterface SVGFEFuncAElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncAElement: {\n prototype: SVGFEFuncAElement;\n new(): SVGFEFuncAElement;\n};\n\ninterface SVGFEFuncBElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncBElement: {\n prototype: SVGFEFuncBElement;\n new(): SVGFEFuncBElement;\n};\n\ninterface SVGFEFuncGElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncGElement: {\n prototype: SVGFEFuncGElement;\n new(): SVGFEFuncGElement;\n};\n\ninterface SVGFEFuncRElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncRElement: {\n prototype: SVGFEFuncRElement;\n new(): SVGFEFuncRElement;\n};\n\ninterface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly stdDeviationX: SVGAnimatedNumber;\n readonly stdDeviationY: SVGAnimatedNumber;\n setStdDeviation(stdDeviationX: number, stdDeviationY: number): void;\n addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEGaussianBlurElement: {\n prototype: SVGFEGaussianBlurElement;\n new(): SVGFEGaussianBlurElement;\n};\n\ninterface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEImageElement: {\n prototype: SVGFEImageElement;\n new(): SVGFEImageElement;\n};\n\ninterface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeElement: {\n prototype: SVGFEMergeElement;\n new(): SVGFEMergeElement;\n};\n\ninterface SVGFEMergeNodeElement extends SVGElement {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeNodeElement: {\n prototype: SVGFEMergeNodeElement;\n new(): SVGFEMergeNodeElement;\n};\n\ninterface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly operator: SVGAnimatedEnumeration;\n readonly radiusX: SVGAnimatedNumber;\n readonly radiusY: SVGAnimatedNumber;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMorphologyElement: {\n prototype: SVGFEMorphologyElement;\n new(): SVGFEMorphologyElement;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n};\n\ninterface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly dx: SVGAnimatedNumber;\n readonly dy: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEOffsetElement: {\n prototype: SVGFEOffsetElement;\n new(): SVGFEOffsetElement;\n};\n\ninterface SVGFEPointLightElement extends SVGElement {\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEPointLightElement: {\n prototype: SVGFEPointLightElement;\n new(): SVGFEPointLightElement;\n};\n\ninterface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly specularConstant: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpecularLightingElement: {\n prototype: SVGFESpecularLightingElement;\n new(): SVGFESpecularLightingElement;\n};\n\ninterface SVGFESpotLightElement extends SVGElement {\n readonly limitingConeAngle: SVGAnimatedNumber;\n readonly pointsAtX: SVGAnimatedNumber;\n readonly pointsAtY: SVGAnimatedNumber;\n readonly pointsAtZ: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpotLightElement: {\n prototype: SVGFESpotLightElement;\n new(): SVGFESpotLightElement;\n};\n\ninterface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETileElement: {\n prototype: SVGFETileElement;\n new(): SVGFETileElement;\n};\n\ninterface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly baseFrequencyX: SVGAnimatedNumber;\n readonly baseFrequencyY: SVGAnimatedNumber;\n readonly numOctaves: SVGAnimatedInteger;\n readonly seed: SVGAnimatedNumber;\n readonly stitchTiles: SVGAnimatedEnumeration;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETurbulenceElement: {\n prototype: SVGFETurbulenceElement;\n new(): SVGFETurbulenceElement;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n /** @deprecated */\n readonly filterResX: SVGAnimatedInteger;\n /** @deprecated */\n readonly filterResY: SVGAnimatedInteger;\n readonly filterUnits: SVGAnimatedEnumeration;\n readonly height: SVGAnimatedLength;\n readonly primitiveUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n /** @deprecated */\n setFilterRes(filterResX: number, filterResY: number): void;\n addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFilterElement: {\n prototype: SVGFilterElement;\n new(): SVGFilterElement;\n};\n\ninterface SVGFilterPrimitiveStandardAttributes {\n readonly height: SVGAnimatedLength;\n readonly result: SVGAnimatedString;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n}\n\ninterface SVGFitToViewBox {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly viewBox: SVGAnimatedRect;\n}\n\ninterface SVGForeignObjectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGForeignObjectElement: {\n prototype: SVGForeignObjectElement;\n new(): SVGForeignObjectElement;\n};\n\ninterface SVGGElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGElement: {\n prototype: SVGGElement;\n new(): SVGGElement;\n};\n\ninterface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n readonly gradientTransform: SVGAnimatedTransformList;\n readonly gradientUnits: SVGAnimatedEnumeration;\n readonly spreadMethod: SVGAnimatedEnumeration;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGradientElement: {\n prototype: SVGGradientElement;\n new(): SVGGradientElement;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n};\n\ninterface SVGGraphicsElement extends SVGElement, SVGTests {\n /** @deprecated */\n readonly farthestViewportElement: SVGElement | null;\n /** @deprecated */\n readonly nearestViewportElement: SVGElement | null;\n readonly transform: SVGAnimatedTransformList;\n getBBox(): SVGRect;\n getCTM(): SVGMatrix | null;\n getScreenCTM(): SVGMatrix | null;\n /** @deprecated */\n getTransformToElement(element: SVGElement): SVGMatrix;\n addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGraphicsElement: {\n prototype: SVGGraphicsElement;\n new(): SVGGraphicsElement;\n};\n\ninterface SVGImageElement extends SVGGraphicsElement, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGImageElement: {\n prototype: SVGImageElement;\n new(): SVGImageElement;\n};\n\ninterface SVGLength {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n}\n\ndeclare var SVGLength: {\n prototype: SVGLength;\n new(): SVGLength;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n};\n\ninterface SVGLengthList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGLength): SVGLength;\n clear(): void;\n getItem(index: number): SVGLength;\n initialize(newItem: SVGLength): SVGLength;\n insertItemBefore(newItem: SVGLength, index: number): SVGLength;\n removeItem(index: number): SVGLength;\n replaceItem(newItem: SVGLength, index: number): SVGLength;\n}\n\ndeclare var SVGLengthList: {\n prototype: SVGLengthList;\n new(): SVGLengthList;\n};\n\ninterface SVGLineElement extends SVGGraphicsElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLineElement: {\n prototype: SVGLineElement;\n new(): SVGLineElement;\n};\n\ninterface SVGLinearGradientElement extends SVGGradientElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLinearGradientElement: {\n prototype: SVGLinearGradientElement;\n new(): SVGLinearGradientElement;\n};\n\ninterface SVGMarkerElement extends SVGElement, SVGFitToViewBox {\n readonly markerHeight: SVGAnimatedLength;\n readonly markerUnits: SVGAnimatedEnumeration;\n readonly markerWidth: SVGAnimatedLength;\n readonly orientAngle: SVGAnimatedAngle;\n readonly orientType: SVGAnimatedEnumeration;\n readonly refX: SVGAnimatedLength;\n readonly refY: SVGAnimatedLength;\n setOrientToAngle(angle: SVGAngle): void;\n setOrientToAuto(): void;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMarkerElement: {\n prototype: SVGMarkerElement;\n new(): SVGMarkerElement;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n};\n\ninterface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes {\n readonly height: SVGAnimatedLength;\n readonly maskContentUnits: SVGAnimatedEnumeration;\n readonly maskUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMaskElement: {\n prototype: SVGMaskElement;\n new(): SVGMaskElement;\n};\n\ninterface SVGMatrix {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n flipX(): SVGMatrix;\n flipY(): SVGMatrix;\n inverse(): SVGMatrix;\n multiply(secondMatrix: SVGMatrix): SVGMatrix;\n rotate(angle: number): SVGMatrix;\n rotateFromVector(x: number, y: number): SVGMatrix;\n scale(scaleFactor: number): SVGMatrix;\n scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix;\n skewX(angle: number): SVGMatrix;\n skewY(angle: number): SVGMatrix;\n translate(x: number, y: number): SVGMatrix;\n}\n\ndeclare var SVGMatrix: {\n prototype: SVGMatrix;\n new(): SVGMatrix;\n};\n\ninterface SVGMetadataElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMetadataElement: {\n prototype: SVGMetadataElement;\n new(): SVGMetadataElement;\n};\n\ninterface SVGNumber {\n value: number;\n}\n\ndeclare var SVGNumber: {\n prototype: SVGNumber;\n new(): SVGNumber;\n};\n\ninterface SVGNumberList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGNumber): SVGNumber;\n clear(): void;\n getItem(index: number): SVGNumber;\n initialize(newItem: SVGNumber): SVGNumber;\n insertItemBefore(newItem: SVGNumber, index: number): SVGNumber;\n removeItem(index: number): SVGNumber;\n replaceItem(newItem: SVGNumber, index: number): SVGNumber;\n}\n\ndeclare var SVGNumberList: {\n prototype: SVGNumberList;\n new(): SVGNumberList;\n};\n\ninterface SVGPathElement extends SVGGraphicsElement {\n /** @deprecated */\n readonly pathSegList: SVGPathSegList;\n /** @deprecated */\n createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs;\n /** @deprecated */\n createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel;\n /** @deprecated */\n createSVGPathSegClosePath(): SVGPathSegClosePath;\n /** @deprecated */\n createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel;\n /** @deprecated */\n createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel;\n /** @deprecated */\n createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel;\n /** @deprecated */\n createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs;\n /** @deprecated */\n createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel;\n /** @deprecated */\n createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs;\n /** @deprecated */\n createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel;\n /** @deprecated */\n getPathSegAtLength(distance: number): number;\n getPointAtLength(distance: number): SVGPoint;\n getTotalLength(): number;\n addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPathElement: {\n prototype: SVGPathElement;\n new(): SVGPathElement;\n};\n\ninterface SVGPathSeg {\n readonly pathSegType: number;\n readonly pathSegTypeAsLetter: string;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n}\n\ndeclare var SVGPathSeg: {\n prototype: SVGPathSeg;\n new(): SVGPathSeg;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n};\n\ninterface SVGPathSegArcAbs extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcAbs: {\n prototype: SVGPathSegArcAbs;\n new(): SVGPathSegArcAbs;\n};\n\ninterface SVGPathSegArcRel extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcRel: {\n prototype: SVGPathSegArcRel;\n new(): SVGPathSegArcRel;\n};\n\ninterface SVGPathSegClosePath extends SVGPathSeg {\n}\n\ndeclare var SVGPathSegClosePath: {\n prototype: SVGPathSegClosePath;\n new(): SVGPathSegClosePath;\n};\n\ninterface SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicAbs: {\n prototype: SVGPathSegCurvetoCubicAbs;\n new(): SVGPathSegCurvetoCubicAbs;\n};\n\ninterface SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicRel: {\n prototype: SVGPathSegCurvetoCubicRel;\n new(): SVGPathSegCurvetoCubicRel;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothAbs: {\n prototype: SVGPathSegCurvetoCubicSmoothAbs;\n new(): SVGPathSegCurvetoCubicSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothRel: {\n prototype: SVGPathSegCurvetoCubicSmoothRel;\n new(): SVGPathSegCurvetoCubicSmoothRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticAbs: {\n prototype: SVGPathSegCurvetoQuadraticAbs;\n new(): SVGPathSegCurvetoQuadraticAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticRel: {\n prototype: SVGPathSegCurvetoQuadraticRel;\n new(): SVGPathSegCurvetoQuadraticRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothAbs: {\n prototype: SVGPathSegCurvetoQuadraticSmoothAbs;\n new(): SVGPathSegCurvetoQuadraticSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothRel: {\n prototype: SVGPathSegCurvetoQuadraticSmoothRel;\n new(): SVGPathSegCurvetoQuadraticSmoothRel;\n};\n\ninterface SVGPathSegLinetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoAbs: {\n prototype: SVGPathSegLinetoAbs;\n new(): SVGPathSegLinetoAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalAbs: {\n prototype: SVGPathSegLinetoHorizontalAbs;\n new(): SVGPathSegLinetoHorizontalAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalRel: {\n prototype: SVGPathSegLinetoHorizontalRel;\n new(): SVGPathSegLinetoHorizontalRel;\n};\n\ninterface SVGPathSegLinetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoRel: {\n prototype: SVGPathSegLinetoRel;\n new(): SVGPathSegLinetoRel;\n};\n\ninterface SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalAbs: {\n prototype: SVGPathSegLinetoVerticalAbs;\n new(): SVGPathSegLinetoVerticalAbs;\n};\n\ninterface SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalRel: {\n prototype: SVGPathSegLinetoVerticalRel;\n new(): SVGPathSegLinetoVerticalRel;\n};\n\ninterface SVGPathSegList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPathSeg): SVGPathSeg;\n clear(): void;\n getItem(index: number): SVGPathSeg;\n initialize(newItem: SVGPathSeg): SVGPathSeg;\n insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg;\n removeItem(index: number): SVGPathSeg;\n replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg;\n}\n\ndeclare var SVGPathSegList: {\n prototype: SVGPathSegList;\n new(): SVGPathSegList;\n};\n\ninterface SVGPathSegMovetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoAbs: {\n prototype: SVGPathSegMovetoAbs;\n new(): SVGPathSegMovetoAbs;\n};\n\ninterface SVGPathSegMovetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoRel: {\n prototype: SVGPathSegMovetoRel;\n new(): SVGPathSegMovetoRel;\n};\n\ninterface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly patternContentUnits: SVGAnimatedEnumeration;\n readonly patternTransform: SVGAnimatedTransformList;\n readonly patternUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPatternElement: {\n prototype: SVGPatternElement;\n new(): SVGPatternElement;\n};\n\ninterface SVGPoint {\n x: number;\n y: number;\n matrixTransform(matrix: SVGMatrix): SVGPoint;\n}\n\ndeclare var SVGPoint: {\n prototype: SVGPoint;\n new(): SVGPoint;\n};\n\ninterface SVGPointList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPoint): SVGPoint;\n clear(): void;\n getItem(index: number): SVGPoint;\n initialize(newItem: SVGPoint): SVGPoint;\n insertItemBefore(newItem: SVGPoint, index: number): SVGPoint;\n removeItem(index: number): SVGPoint;\n replaceItem(newItem: SVGPoint, index: number): SVGPoint;\n}\n\ndeclare var SVGPointList: {\n prototype: SVGPointList;\n new(): SVGPointList;\n};\n\ninterface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolygonElement: {\n prototype: SVGPolygonElement;\n new(): SVGPolygonElement;\n};\n\ninterface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolylineElement: {\n prototype: SVGPolylineElement;\n new(): SVGPolylineElement;\n};\n\ninterface SVGPreserveAspectRatio {\n align: number;\n meetOrSlice: number;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n}\n\ndeclare var SVGPreserveAspectRatio: {\n prototype: SVGPreserveAspectRatio;\n new(): SVGPreserveAspectRatio;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n};\n\ninterface SVGRadialGradientElement extends SVGGradientElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly fx: SVGAnimatedLength;\n readonly fy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRadialGradientElement: {\n prototype: SVGRadialGradientElement;\n new(): SVGRadialGradientElement;\n};\n\ninterface SVGRect {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var SVGRect: {\n prototype: SVGRect;\n new(): SVGRect;\n};\n\ninterface SVGRectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRectElement: {\n prototype: SVGRectElement;\n new(): SVGRectElement;\n};\n\ninterface SVGSVGElementEventMap extends SVGElementEventMap {\n \"SVGAbort\": Event;\n \"SVGError\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"SVGUnload\": Event;\n \"SVGZoom\": SVGZoomEvent;\n}\n\ninterface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n contentScriptType: string;\n /** @deprecated */\n contentStyleType: string;\n currentScale: number;\n readonly currentTranslate: SVGPoint;\n readonly height: SVGAnimatedLength;\n onabort: ((this: SVGSVGElement, ev: Event) => any) | null;\n onerror: ((this: SVGSVGElement, ev: Event) => any) | null;\n onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onunload: ((this: SVGSVGElement, ev: Event) => any) | null;\n onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null;\n /** @deprecated */\n readonly pixelUnitToMillimeterX: number;\n /** @deprecated */\n readonly pixelUnitToMillimeterY: number;\n /** @deprecated */\n readonly screenPixelToMillimeterX: number;\n /** @deprecated */\n readonly screenPixelToMillimeterY: number;\n /** @deprecated */\n readonly viewport: SVGRect;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n checkEnclosure(element: SVGElement, rect: SVGRect): boolean;\n checkIntersection(element: SVGElement, rect: SVGRect): boolean;\n createSVGAngle(): SVGAngle;\n createSVGLength(): SVGLength;\n createSVGMatrix(): SVGMatrix;\n createSVGNumber(): SVGNumber;\n createSVGPoint(): SVGPoint;\n createSVGRect(): SVGRect;\n createSVGTransform(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n deselectAll(): void;\n /** @deprecated */\n forceRedraw(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n /** @deprecated */\n getCurrentTime(): number;\n getElementById(elementId: string): Element;\n getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n /** @deprecated */\n pauseAnimations(): void;\n /** @deprecated */\n setCurrentTime(seconds: number): void;\n /** @deprecated */\n suspendRedraw(maxWaitMilliseconds: number): number;\n /** @deprecated */\n unpauseAnimations(): void;\n /** @deprecated */\n unsuspendRedraw(suspendHandleID: number): void;\n /** @deprecated */\n unsuspendRedrawAll(): void;\n addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSVGElement: {\n prototype: SVGSVGElement;\n new(): SVGSVGElement;\n};\n\ninterface SVGScriptElement extends SVGElement, SVGURIReference {\n type: string;\n addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGScriptElement: {\n prototype: SVGScriptElement;\n new(): SVGScriptElement;\n};\n\ninterface SVGStopElement extends SVGElement {\n readonly offset: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStopElement: {\n prototype: SVGStopElement;\n new(): SVGStopElement;\n};\n\ninterface SVGStringList {\n readonly numberOfItems: number;\n appendItem(newItem: string): string;\n clear(): void;\n getItem(index: number): string;\n initialize(newItem: string): string;\n insertItemBefore(newItem: string, index: number): string;\n removeItem(index: number): string;\n replaceItem(newItem: string, index: number): string;\n}\n\ndeclare var SVGStringList: {\n prototype: SVGStringList;\n new(): SVGStringList;\n};\n\ninterface SVGStylable {\n className: any;\n}\n\ndeclare var SVGStylable: {\n prototype: SVGStylable;\n new(): SVGStylable;\n};\n\ninterface SVGStyleElement extends SVGElement {\n disabled: boolean;\n media: string;\n title: string;\n type: string;\n addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStyleElement: {\n prototype: SVGStyleElement;\n new(): SVGStyleElement;\n};\n\ninterface SVGSwitchElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSwitchElement: {\n prototype: SVGSwitchElement;\n new(): SVGSwitchElement;\n};\n\ninterface SVGSymbolElement extends SVGElement, SVGFitToViewBox {\n addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSymbolElement: {\n prototype: SVGSymbolElement;\n new(): SVGSymbolElement;\n};\n\ninterface SVGTSpanElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTSpanElement: {\n prototype: SVGTSpanElement;\n new(): SVGTSpanElement;\n};\n\ninterface SVGTests {\n readonly requiredExtensions: SVGStringList;\n /** @deprecated */\n readonly requiredFeatures: SVGStringList;\n readonly systemLanguage: SVGStringList;\n /** @deprecated */\n hasExtension(extension: string): boolean;\n}\n\ninterface SVGTextContentElement extends SVGGraphicsElement {\n readonly lengthAdjust: SVGAnimatedEnumeration;\n readonly textLength: SVGAnimatedLength;\n getCharNumAtPosition(point: SVGPoint): number;\n getComputedTextLength(): number;\n getEndPositionOfChar(charnum: number): SVGPoint;\n getExtentOfChar(charnum: number): SVGRect;\n getNumberOfChars(): number;\n getRotationOfChar(charnum: number): number;\n getStartPositionOfChar(charnum: number): SVGPoint;\n getSubStringLength(charnum: number, nchars: number): number;\n selectSubString(charnum: number, nchars: number): void;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextContentElement: {\n prototype: SVGTextContentElement;\n new(): SVGTextContentElement;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n};\n\ninterface SVGTextElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextElement: {\n prototype: SVGTextElement;\n new(): SVGTextElement;\n};\n\ninterface SVGTextPathElement extends SVGTextContentElement, SVGURIReference {\n readonly method: SVGAnimatedEnumeration;\n readonly spacing: SVGAnimatedEnumeration;\n readonly startOffset: SVGAnimatedLength;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPathElement: {\n prototype: SVGTextPathElement;\n new(): SVGTextPathElement;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n};\n\ninterface SVGTextPositioningElement extends SVGTextContentElement {\n readonly dx: SVGAnimatedLengthList;\n readonly dy: SVGAnimatedLengthList;\n readonly rotate: SVGAnimatedNumberList;\n readonly x: SVGAnimatedLengthList;\n readonly y: SVGAnimatedLengthList;\n addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPositioningElement: {\n prototype: SVGTextPositioningElement;\n new(): SVGTextPositioningElement;\n};\n\ninterface SVGTitleElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTitleElement: {\n prototype: SVGTitleElement;\n new(): SVGTitleElement;\n};\n\ninterface SVGTransform {\n readonly angle: number;\n readonly matrix: SVGMatrix;\n readonly type: number;\n setMatrix(matrix: SVGMatrix): void;\n setRotate(angle: number, cx: number, cy: number): void;\n setScale(sx: number, sy: number): void;\n setSkewX(angle: number): void;\n setSkewY(angle: number): void;\n setTranslate(tx: number, ty: number): void;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n}\n\ndeclare var SVGTransform: {\n prototype: SVGTransform;\n new(): SVGTransform;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n};\n\ninterface SVGTransformList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGTransform): SVGTransform;\n clear(): void;\n consolidate(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n getItem(index: number): SVGTransform;\n initialize(newItem: SVGTransform): SVGTransform;\n insertItemBefore(newItem: SVGTransform, index: number): SVGTransform;\n removeItem(index: number): SVGTransform;\n replaceItem(newItem: SVGTransform, index: number): SVGTransform;\n}\n\ndeclare var SVGTransformList: {\n prototype: SVGTransformList;\n new(): SVGTransformList;\n};\n\ninterface SVGURIReference {\n readonly href: SVGAnimatedString;\n}\n\ninterface SVGUnitTypes {\n readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number;\n readonly SVG_UNIT_TYPE_UNKNOWN: number;\n readonly SVG_UNIT_TYPE_USERSPACEONUSE: number;\n}\ndeclare var SVGUnitTypes: SVGUnitTypes;\n\ninterface SVGUseElement extends SVGGraphicsElement, SVGURIReference {\n readonly animatedInstanceRoot: SVGElementInstance | null;\n readonly height: SVGAnimatedLength;\n readonly instanceRoot: SVGElementInstance | null;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGUseElement: {\n prototype: SVGUseElement;\n new(): SVGUseElement;\n};\n\ninterface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n readonly viewTarget: SVGStringList;\n addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGViewElement: {\n prototype: SVGViewElement;\n new(): SVGViewElement;\n};\n\ninterface SVGZoomAndPan {\n readonly zoomAndPan: number;\n}\n\ndeclare var SVGZoomAndPan: {\n readonly SVG_ZOOMANDPAN_DISABLE: number;\n readonly SVG_ZOOMANDPAN_MAGNIFY: number;\n readonly SVG_ZOOMANDPAN_UNKNOWN: number;\n};\n\ninterface SVGZoomEvent extends UIEvent {\n readonly newScale: number;\n readonly newTranslate: SVGPoint;\n readonly previousScale: number;\n readonly previousTranslate: SVGPoint;\n readonly zoomRectScreen: SVGRect;\n}\n\ndeclare var SVGZoomEvent: {\n prototype: SVGZoomEvent;\n new(): SVGZoomEvent;\n};\n\ninterface ScopedCredential {\n readonly id: ArrayBuffer;\n readonly type: ScopedCredentialType;\n}\n\ndeclare var ScopedCredential: {\n prototype: ScopedCredential;\n new(): ScopedCredential;\n};\n\ninterface ScopedCredentialInfo {\n readonly credential: ScopedCredential;\n readonly publicKey: CryptoKey;\n}\n\ndeclare var ScopedCredentialInfo: {\n prototype: ScopedCredentialInfo;\n new(): ScopedCredentialInfo;\n};\n\ninterface ScreenEventMap {\n \"MSOrientationChange\": Event;\n}\n\ninterface Screen extends EventTarget {\n readonly availHeight: number;\n readonly availWidth: number;\n /** @deprecated */\n bufferDepth: number;\n readonly colorDepth: number;\n readonly deviceXDPI: number;\n readonly deviceYDPI: number;\n readonly fontSmoothingEnabled: boolean;\n readonly height: number;\n readonly logicalXDPI: number;\n readonly logicalYDPI: number;\n readonly msOrientation: string;\n onmsorientationchange: ((this: Screen, ev: Event) => any) | null;\n readonly pixelDepth: number;\n readonly systemXDPI: number;\n readonly systemYDPI: number;\n readonly width: number;\n lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean;\n msLockOrientation(orientations: string | string[]): boolean;\n msUnlockOrientation(): void;\n unlockOrientation(): void;\n addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Screen: {\n prototype: Screen;\n new(): Screen;\n};\n\ninterface ScriptProcessorNodeEventMap {\n \"audioprocess\": AudioProcessingEvent;\n}\n\ninterface ScriptProcessorNode extends AudioNode {\n /** @deprecated */\n readonly bufferSize: number;\n /** @deprecated */\n onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null;\n addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ScriptProcessorNode: {\n prototype: ScriptProcessorNode;\n new(): ScriptProcessorNode;\n};\n\ninterface ScrollIntoViewOptions extends ScrollOptions {\n block?: ScrollLogicalPosition;\n inline?: ScrollLogicalPosition;\n}\n\ninterface ScrollOptions {\n behavior?: ScrollBehavior;\n}\n\ninterface ScrollToOptions extends ScrollOptions {\n left?: number;\n top?: number;\n}\n\ninterface SecurityPolicyViolationEvent extends Event {\n readonly blockedURI: string;\n readonly columnNumber: number;\n readonly documentURI: string;\n readonly effectiveDirective: string;\n readonly lineNumber: number;\n readonly originalPolicy: string;\n readonly referrer: string;\n readonly sourceFile: string;\n readonly statusCode: number;\n readonly violatedDirective: string;\n}\n\ndeclare var SecurityPolicyViolationEvent: {\n prototype: SecurityPolicyViolationEvent;\n new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent;\n};\n\ninterface Selection {\n readonly anchorNode: Node;\n readonly anchorOffset: number;\n readonly baseNode: Node;\n readonly baseOffset: number;\n readonly extentNode: Node;\n readonly extentOffset: number;\n readonly focusNode: Node;\n readonly focusOffset: number;\n readonly isCollapsed: boolean;\n readonly rangeCount: number;\n readonly type: string;\n addRange(range: Range): void;\n collapse(parentNode: Node, offset: number): void;\n collapseToEnd(): void;\n collapseToStart(): void;\n containsNode(node: Node, partlyContained: boolean): boolean;\n deleteFromDocument(): void;\n empty(): void;\n extend(newNode: Node, offset: number): void;\n getRangeAt(index: number): Range;\n removeAllRanges(): void;\n removeRange(range: Range): void;\n selectAllChildren(parentNode: Node): void;\n setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void;\n setPosition(parentNode: Node, offset: number): void;\n toString(): string;\n}\n\ndeclare var Selection: {\n prototype: Selection;\n new(): Selection;\n};\n\ninterface ServiceUIFrameContext {\n getCachedFrameMessage(key: string): string;\n postFrameMessage(key: string, data: string): void;\n}\ndeclare var ServiceUIFrameContext: ServiceUIFrameContext;\n\ninterface ServiceWorkerEventMap extends AbstractWorkerEventMap {\n \"statechange\": Event;\n}\n\ninterface ServiceWorker extends EventTarget, AbstractWorker {\n onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;\n readonly scriptURL: string;\n readonly state: ServiceWorkerState;\n postMessage(message: any, transfer?: any[]): void;\n addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorker: {\n prototype: ServiceWorker;\n new(): ServiceWorker;\n};\n\ninterface ServiceWorkerContainerEventMap {\n \"controllerchange\": Event;\n \"message\": ServiceWorkerMessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface ServiceWorkerContainer extends EventTarget {\n readonly controller: ServiceWorker | null;\n oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;\n onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null;\n onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n readonly ready: Promise;\n getRegistration(clientURL?: string): Promise;\n getRegistrations(): Promise;\n register(scriptURL: string, options?: RegistrationOptions): Promise;\n startMessages(): void;\n addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerContainer: {\n prototype: ServiceWorkerContainer;\n new(): ServiceWorkerContainer;\n};\n\ninterface ServiceWorkerMessageEvent extends Event {\n readonly data: any;\n readonly lastEventId: string;\n readonly origin: string;\n readonly ports: ReadonlyArray | null;\n readonly source: ServiceWorker | MessagePort | null;\n}\n\ndeclare var ServiceWorkerMessageEvent: {\n prototype: ServiceWorkerMessageEvent;\n new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent;\n};\n\ninterface ServiceWorkerRegistrationEventMap {\n \"updatefound\": Event;\n}\n\ninterface ServiceWorkerRegistration extends EventTarget {\n readonly active: ServiceWorker | null;\n readonly installing: ServiceWorker | null;\n onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null;\n readonly pushManager: PushManager;\n readonly scope: string;\n readonly sync: SyncManager;\n readonly waiting: ServiceWorker | null;\n getNotifications(filter?: GetNotificationOptions): Promise;\n showNotification(title: string, options?: NotificationOptions): Promise;\n unregister(): Promise;\n update(): Promise;\n addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerRegistration: {\n prototype: ServiceWorkerRegistration;\n new(): ServiceWorkerRegistration;\n};\n\ninterface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment {\n readonly host: Element;\n innerHTML: string;\n}\n\ninterface ShadowRootInit {\n delegatesFocus?: boolean;\n mode: \"open\" | \"closed\";\n}\n\ninterface SourceBuffer extends EventTarget {\n appendWindowEnd: number;\n appendWindowStart: number;\n readonly audioTracks: AudioTrackList;\n readonly buffered: TimeRanges;\n mode: AppendMode;\n timestampOffset: number;\n readonly updating: boolean;\n readonly videoTracks: VideoTrackList;\n abort(): void;\n appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n appendStream(stream: MSStream, maxSize?: number): void;\n remove(start: number, end: number): void;\n}\n\ndeclare var SourceBuffer: {\n prototype: SourceBuffer;\n new(): SourceBuffer;\n};\n\ninterface SourceBufferList extends EventTarget {\n readonly length: number;\n item(index: number): SourceBuffer;\n [index: number]: SourceBuffer;\n}\n\ndeclare var SourceBufferList: {\n prototype: SourceBufferList;\n new(): SourceBufferList;\n};\n\ninterface SpeechSynthesisEventMap {\n \"voiceschanged\": Event;\n}\n\ninterface SpeechSynthesis extends EventTarget {\n onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null;\n readonly paused: boolean;\n readonly pending: boolean;\n readonly speaking: boolean;\n cancel(): void;\n getVoices(): SpeechSynthesisVoice[];\n pause(): void;\n resume(): void;\n speak(utterance: SpeechSynthesisUtterance): void;\n addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesis: {\n prototype: SpeechSynthesis;\n new(): SpeechSynthesis;\n};\n\ninterface SpeechSynthesisEvent extends Event {\n readonly charIndex: number;\n readonly charLength: number;\n readonly elapsedTime: number;\n readonly name: string;\n readonly utterance: SpeechSynthesisUtterance;\n}\n\ndeclare var SpeechSynthesisEvent: {\n prototype: SpeechSynthesisEvent;\n new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent;\n};\n\ninterface SpeechSynthesisUtteranceEventMap {\n \"boundary\": Event;\n \"end\": Event;\n \"error\": Event;\n \"mark\": Event;\n \"pause\": Event;\n \"resume\": Event;\n \"start\": Event;\n}\n\ninterface SpeechSynthesisUtterance extends EventTarget {\n lang: string;\n onboundary: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n pitch: number;\n rate: number;\n text: string;\n voice: SpeechSynthesisVoice;\n volume: number;\n addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesisUtterance: {\n prototype: SpeechSynthesisUtterance;\n new(): SpeechSynthesisUtterance;\n new(text: string): SpeechSynthesisUtterance;\n};\n\ninterface SpeechSynthesisVoice {\n readonly default: boolean;\n readonly lang: string;\n readonly localService: boolean;\n readonly name: string;\n readonly voiceURI: string;\n}\n\ndeclare var SpeechSynthesisVoice: {\n prototype: SpeechSynthesisVoice;\n new(): SpeechSynthesisVoice;\n};\n\ninterface StereoPannerNode extends AudioNode {\n readonly pan: AudioParam;\n}\n\ndeclare var StereoPannerNode: {\n prototype: StereoPannerNode;\n new(): StereoPannerNode;\n};\n\ninterface Storage {\n readonly length: number;\n clear(): void;\n getItem(key: string): string | null;\n key(index: number): string | null;\n removeItem(key: string): void;\n setItem(key: string, value: string): void;\n [key: string]: any;\n}\n\ndeclare var Storage: {\n prototype: Storage;\n new(): Storage;\n};\n\ninterface StorageEvent extends Event {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly oldValue: string | null;\n readonly storageArea: Storage | null;\n readonly url: string;\n}\n\ndeclare var StorageEvent: {\n prototype: StorageEvent;\n new (type: string, eventInitDict?: StorageEventInit): StorageEvent;\n};\n\ninterface StorageEventInit extends EventInit {\n key?: string;\n newValue?: string;\n oldValue?: string;\n storageArea?: Storage;\n url: string;\n}\n\ninterface StyleMedia {\n readonly type: string;\n matchMedium(mediaquery: string): boolean;\n}\n\ndeclare var StyleMedia: {\n prototype: StyleMedia;\n new(): StyleMedia;\n};\n\ninterface StyleSheet {\n disabled: boolean;\n readonly href: string | null;\n readonly media: MediaList;\n readonly ownerNode: Node;\n readonly parentStyleSheet: StyleSheet | null;\n readonly title: string | null;\n readonly type: string;\n}\n\ndeclare var StyleSheet: {\n prototype: StyleSheet;\n new(): StyleSheet;\n};\n\ninterface StyleSheetList {\n readonly length: number;\n item(index: number): StyleSheet | null;\n [index: number]: StyleSheet;\n}\n\ndeclare var StyleSheetList: {\n prototype: StyleSheetList;\n new(): StyleSheetList;\n};\n\ninterface SubtleCrypto {\n decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike;\n deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n exportKey(format: \"jwk\", key: CryptoKey): PromiseLike;\n exportKey(format: \"raw\" | \"pkcs8\" | \"spki\", key: CryptoKey): PromiseLike;\n exportKey(format: string, key: CryptoKey): PromiseLike;\n generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"jwk\", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"raw\" | \"pkcs8\" | \"spki\", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike;\n}\n\ndeclare var SubtleCrypto: {\n prototype: SubtleCrypto;\n new(): SubtleCrypto;\n};\n\ninterface SyncManager {\n getTags(): Promise;\n register(tag: string): Promise;\n}\n\ndeclare var SyncManager: {\n prototype: SyncManager;\n new(): SyncManager;\n};\n\ninterface Text extends CharacterData {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly wholeText: string;\n splitText(offset: number): Text;\n}\n\ndeclare var Text: {\n prototype: Text;\n new(data?: string): Text;\n};\n\ninterface TextDecoder {\n readonly encoding: string;\n readonly fatal: boolean;\n readonly ignoreBOM: boolean;\n decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string;\n}\n\ndeclare var TextDecoder: {\n prototype: TextDecoder;\n new(label?: string, options?: TextDecoderOptions): TextDecoder;\n};\n\ninterface TextEncoder {\n readonly encoding: string;\n encode(input?: string): Uint8Array;\n}\n\ndeclare var TextEncoder: {\n prototype: TextEncoder;\n new(): TextEncoder;\n};\n\ninterface TextEvent extends UIEvent {\n readonly data: string;\n initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n}\n\ndeclare var TextEvent: {\n prototype: TextEvent;\n new(): TextEvent;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n};\n\ninterface TextMetrics {\n readonly width: number;\n}\n\ndeclare var TextMetrics: {\n prototype: TextMetrics;\n new(): TextMetrics;\n};\n\ninterface TextTrackEventMap {\n \"cuechange\": Event;\n \"error\": Event;\n \"load\": Event;\n}\n\ninterface TextTrack extends EventTarget {\n readonly activeCues: TextTrackCueList;\n readonly cues: TextTrackCueList;\n readonly inBandMetadataTrackDispatchType: string;\n readonly kind: string;\n readonly label: string;\n readonly language: string;\n mode: TextTrackMode | number;\n oncuechange: ((this: TextTrack, ev: Event) => any) | null;\n onerror: ((this: TextTrack, ev: Event) => any) | null;\n onload: ((this: TextTrack, ev: Event) => any) | null;\n readonly readyState: number;\n addCue(cue: TextTrackCue): void;\n removeCue(cue: TextTrackCue): void;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrack: {\n prototype: TextTrack;\n new(): TextTrack;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n};\n\ninterface TextTrackCueEventMap {\n \"enter\": Event;\n \"exit\": Event;\n}\n\ninterface TextTrackCue extends EventTarget {\n endTime: number;\n id: string;\n onenter: ((this: TextTrackCue, ev: Event) => any) | null;\n onexit: ((this: TextTrackCue, ev: Event) => any) | null;\n pauseOnExit: boolean;\n startTime: number;\n text: string;\n readonly track: TextTrack;\n getCueAsHTML(): DocumentFragment;\n addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrackCue: {\n prototype: TextTrackCue;\n new(startTime: number, endTime: number, text: string): TextTrackCue;\n};\n\ninterface TextTrackCueList {\n readonly length: number;\n getCueById(id: string): TextTrackCue;\n item(index: number): TextTrackCue;\n [index: number]: TextTrackCue;\n}\n\ndeclare var TextTrackCueList: {\n prototype: TextTrackCueList;\n new(): TextTrackCueList;\n};\n\ninterface TextTrackListEventMap {\n \"addtrack\": TrackEvent;\n}\n\ninterface TextTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null;\n item(index: number): TextTrack;\n addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: TextTrack;\n}\n\ndeclare var TextTrackList: {\n prototype: TextTrackList;\n new(): TextTrackList;\n};\n\ninterface TimeRanges {\n readonly length: number;\n end(index: number): number;\n start(index: number): number;\n}\n\ndeclare var TimeRanges: {\n prototype: TimeRanges;\n new(): TimeRanges;\n};\n\ninterface Touch {\n readonly clientX: number;\n readonly clientY: number;\n readonly identifier: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly target: EventTarget;\n}\n\ndeclare var Touch: {\n prototype: Touch;\n new(): Touch;\n};\n\ninterface TouchEvent extends UIEvent {\n readonly altKey: boolean;\n readonly changedTouches: TouchList;\n readonly charCode: number;\n readonly ctrlKey: boolean;\n readonly keyCode: number;\n readonly metaKey: boolean;\n readonly shiftKey: boolean;\n readonly targetTouches: TouchList;\n readonly touches: TouchList;\n /** @deprecated */\n readonly which: number;\n}\n\ndeclare var TouchEvent: {\n prototype: TouchEvent;\n new(type: string, touchEventInit?: TouchEventInit): TouchEvent;\n};\n\ninterface TouchEventInit extends EventModifierInit {\n changedTouches?: Touch[];\n targetTouches?: Touch[];\n touches?: Touch[];\n}\n\ninterface TouchList {\n readonly length: number;\n item(index: number): Touch | null;\n [index: number]: Touch;\n}\n\ndeclare var TouchList: {\n prototype: TouchList;\n new(): TouchList;\n};\n\ninterface TrackEvent extends Event {\n readonly track: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ndeclare var TrackEvent: {\n prototype: TrackEvent;\n new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent;\n};\n\ninterface TransitionEvent extends Event {\n readonly elapsedTime: number;\n readonly propertyName: string;\n initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void;\n}\n\ndeclare var TransitionEvent: {\n prototype: TransitionEvent;\n new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent;\n};\n\ninterface TreeWalker {\n currentNode: Node;\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n firstChild(): Node | null;\n lastChild(): Node | null;\n nextNode(): Node | null;\n nextSibling(): Node | null;\n parentNode(): Node | null;\n previousNode(): Node | null;\n previousSibling(): Node | null;\n}\n\ndeclare var TreeWalker: {\n prototype: TreeWalker;\n new(): TreeWalker;\n};\n\ninterface UIEvent extends Event {\n readonly detail: number;\n readonly view: Window;\n initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void;\n}\n\ndeclare var UIEvent: {\n prototype: UIEvent;\n new(typeArg: string, eventInitDict?: UIEventInit): UIEvent;\n};\n\ninterface URL {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n readonly searchParams: URLSearchParams;\n username: string;\n toString(): string;\n}\n\ndeclare var URL: {\n prototype: URL;\n new(url: string, base?: string | URL): URL;\n createObjectURL(object: any, options?: ObjectURLOptions): string;\n revokeObjectURL(url: string): void;\n};\n\ninterface URLSearchParams {\n /**\n * Appends a specified key/value pair as a new search parameter.\n */\n append(name: string, value: string): void;\n /**\n * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n */\n delete(name: string): void;\n /**\n * Returns the first value associated to the given search parameter.\n */\n get(name: string): string | null;\n /**\n * Returns all the values association with a given search parameter.\n */\n getAll(name: string): string[];\n /**\n * Returns a Boolean indicating if such a search parameter exists.\n */\n has(name: string): boolean;\n /**\n * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n */\n set(name: string, value: string): void;\n}\n\ndeclare var URLSearchParams: {\n prototype: URLSearchParams;\n new (init?: string | URLSearchParams): URLSearchParams;\n};\n\ninterface VRDisplay extends EventTarget {\n readonly capabilities: VRDisplayCapabilities;\n depthFar: number;\n depthNear: number;\n readonly displayId: number;\n readonly displayName: string;\n readonly isConnected: boolean;\n readonly isPresenting: boolean;\n readonly stageParameters: VRStageParameters | null;\n cancelAnimationFrame(handle: number): void;\n exitPresent(): Promise;\n getEyeParameters(whichEye: string): VREyeParameters;\n getFrameData(frameData: VRFrameData): boolean;\n getLayers(): VRLayer[];\n /** @deprecated */\n getPose(): VRPose;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n requestPresent(layers: VRLayer[]): Promise;\n resetPose(): void;\n submitFrame(pose?: VRPose): void;\n}\n\ndeclare var VRDisplay: {\n prototype: VRDisplay;\n new(): VRDisplay;\n};\n\ninterface VRDisplayCapabilities {\n readonly canPresent: boolean;\n readonly hasExternalDisplay: boolean;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly maxLayers: number;\n}\n\ndeclare var VRDisplayCapabilities: {\n prototype: VRDisplayCapabilities;\n new(): VRDisplayCapabilities;\n};\n\ninterface VRDisplayEvent extends Event {\n readonly display: VRDisplay;\n readonly reason: VRDisplayEventReason | null;\n}\n\ndeclare var VRDisplayEvent: {\n prototype: VRDisplayEvent;\n new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent;\n};\n\ninterface VREyeParameters {\n /** @deprecated */\n readonly fieldOfView: VRFieldOfView;\n readonly offset: Float32Array;\n readonly renderHeight: number;\n readonly renderWidth: number;\n}\n\ndeclare var VREyeParameters: {\n prototype: VREyeParameters;\n new(): VREyeParameters;\n};\n\ninterface VRFieldOfView {\n readonly downDegrees: number;\n readonly leftDegrees: number;\n readonly rightDegrees: number;\n readonly upDegrees: number;\n}\n\ndeclare var VRFieldOfView: {\n prototype: VRFieldOfView;\n new(): VRFieldOfView;\n};\n\ninterface VRFrameData {\n readonly leftProjectionMatrix: Float32Array;\n readonly leftViewMatrix: Float32Array;\n readonly pose: VRPose;\n readonly rightProjectionMatrix: Float32Array;\n readonly rightViewMatrix: Float32Array;\n readonly timestamp: number;\n}\n\ndeclare var VRFrameData: {\n prototype: VRFrameData;\n new(): VRFrameData;\n};\n\ninterface VRPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n readonly timestamp: number;\n}\n\ndeclare var VRPose: {\n prototype: VRPose;\n new(): VRPose;\n};\n\ninterface ValidityState {\n readonly badInput: boolean;\n readonly customError: boolean;\n readonly patternMismatch: boolean;\n readonly rangeOverflow: boolean;\n readonly rangeUnderflow: boolean;\n readonly stepMismatch: boolean;\n readonly tooLong: boolean;\n readonly tooShort: boolean;\n readonly typeMismatch: boolean;\n readonly valid: boolean;\n readonly valueMissing: boolean;\n}\n\ndeclare var ValidityState: {\n prototype: ValidityState;\n new(): ValidityState;\n};\n\ninterface VideoPlaybackQuality {\n readonly corruptedVideoFrames: number;\n readonly creationTime: number;\n readonly droppedVideoFrames: number;\n readonly totalFrameDelay: number;\n readonly totalVideoFrames: number;\n}\n\ndeclare var VideoPlaybackQuality: {\n prototype: VideoPlaybackQuality;\n new(): VideoPlaybackQuality;\n};\n\ninterface VideoTrack {\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n selected: boolean;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var VideoTrack: {\n prototype: VideoTrack;\n new(): VideoTrack;\n};\n\ninterface VideoTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface VideoTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: VideoTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n readonly selectedIndex: number;\n getTrackById(id: string): VideoTrack | null;\n item(index: number): VideoTrack;\n addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: VideoTrack;\n}\n\ndeclare var VideoTrackList: {\n prototype: VideoTrackList;\n new(): VideoTrackList;\n};\n\ninterface WEBGL_color_buffer_float {\n readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;\n readonly RGB32F_EXT: number;\n readonly RGBA32F_EXT: number;\n readonly UNSIGNED_NORMALIZED_EXT: number;\n}\n\ninterface WEBGL_compressed_texture_astc {\n readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number;\n getSupportedProfiles(): string[];\n}\n\ninterface WEBGL_compressed_texture_s3tc {\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n}\n\ndeclare var WEBGL_compressed_texture_s3tc: {\n prototype: WEBGL_compressed_texture_s3tc;\n new(): WEBGL_compressed_texture_s3tc;\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n};\n\ninterface WEBGL_compressed_texture_s3tc_srgb {\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number;\n}\n\ninterface WEBGL_debug_renderer_info {\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n}\n\ndeclare var WEBGL_debug_renderer_info: {\n prototype: WEBGL_debug_renderer_info;\n new(): WEBGL_debug_renderer_info;\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n};\n\ninterface WEBGL_debug_shaders {\n getTranslatedShaderSource(shader: WebGLShader): string;\n}\n\ninterface WEBGL_depth_texture {\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n}\n\ndeclare var WEBGL_depth_texture: {\n prototype: WEBGL_depth_texture;\n new(): WEBGL_depth_texture;\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n};\n\ninterface WEBGL_draw_buffers {\n readonly COLOR_ATTACHMENT0_WEBGL: number;\n readonly COLOR_ATTACHMENT10_WEBGL: number;\n readonly COLOR_ATTACHMENT11_WEBGL: number;\n readonly COLOR_ATTACHMENT12_WEBGL: number;\n readonly COLOR_ATTACHMENT13_WEBGL: number;\n readonly COLOR_ATTACHMENT14_WEBGL: number;\n readonly COLOR_ATTACHMENT15_WEBGL: number;\n readonly COLOR_ATTACHMENT1_WEBGL: number;\n readonly COLOR_ATTACHMENT2_WEBGL: number;\n readonly COLOR_ATTACHMENT3_WEBGL: number;\n readonly COLOR_ATTACHMENT4_WEBGL: number;\n readonly COLOR_ATTACHMENT5_WEBGL: number;\n readonly COLOR_ATTACHMENT6_WEBGL: number;\n readonly COLOR_ATTACHMENT7_WEBGL: number;\n readonly COLOR_ATTACHMENT8_WEBGL: number;\n readonly COLOR_ATTACHMENT9_WEBGL: number;\n readonly DRAW_BUFFER0_WEBGL: number;\n readonly DRAW_BUFFER10_WEBGL: number;\n readonly DRAW_BUFFER11_WEBGL: number;\n readonly DRAW_BUFFER12_WEBGL: number;\n readonly DRAW_BUFFER13_WEBGL: number;\n readonly DRAW_BUFFER14_WEBGL: number;\n readonly DRAW_BUFFER15_WEBGL: number;\n readonly DRAW_BUFFER1_WEBGL: number;\n readonly DRAW_BUFFER2_WEBGL: number;\n readonly DRAW_BUFFER3_WEBGL: number;\n readonly DRAW_BUFFER4_WEBGL: number;\n readonly DRAW_BUFFER5_WEBGL: number;\n readonly DRAW_BUFFER6_WEBGL: number;\n readonly DRAW_BUFFER7_WEBGL: number;\n readonly DRAW_BUFFER8_WEBGL: number;\n readonly DRAW_BUFFER9_WEBGL: number;\n readonly MAX_COLOR_ATTACHMENTS_WEBGL: number;\n readonly MAX_DRAW_BUFFERS_WEBGL: number;\n drawBuffersWEBGL(buffers: number[]): void;\n}\n\ninterface WEBGL_lose_context {\n loseContext(): void;\n restoreContext(): void;\n}\n\ninterface WaveShaperNode extends AudioNode {\n curve: Float32Array | null;\n oversample: OverSampleType;\n}\n\ndeclare var WaveShaperNode: {\n prototype: WaveShaperNode;\n new(): WaveShaperNode;\n};\n\ninterface WebAuthentication {\n getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise;\n makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise;\n}\n\ndeclare var WebAuthentication: {\n prototype: WebAuthentication;\n new(): WebAuthentication;\n};\n\ninterface WebAuthnAssertion {\n readonly authenticatorData: ArrayBuffer;\n readonly clientData: ArrayBuffer;\n readonly credential: ScopedCredential;\n readonly signature: ArrayBuffer;\n}\n\ndeclare var WebAuthnAssertion: {\n prototype: WebAuthnAssertion;\n new(): WebAuthnAssertion;\n};\n\ninterface WebGLActiveInfo {\n readonly name: string;\n readonly size: number;\n readonly type: number;\n}\n\ndeclare var WebGLActiveInfo: {\n prototype: WebGLActiveInfo;\n new(): WebGLActiveInfo;\n};\n\ninterface WebGLBuffer extends WebGLObject {\n}\n\ndeclare var WebGLBuffer: {\n prototype: WebGLBuffer;\n new(): WebGLBuffer;\n};\n\ninterface WebGLContextEvent extends Event {\n readonly statusMessage: string;\n}\n\ndeclare var WebGLContextEvent: {\n prototype: WebGLContextEvent;\n new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent;\n};\n\ninterface WebGLFramebuffer extends WebGLObject {\n}\n\ndeclare var WebGLFramebuffer: {\n prototype: WebGLFramebuffer;\n new(): WebGLFramebuffer;\n};\n\ninterface WebGLObject {\n}\n\ndeclare var WebGLObject: {\n prototype: WebGLObject;\n new(): WebGLObject;\n};\n\ninterface WebGLProgram extends WebGLObject {\n}\n\ndeclare var WebGLProgram: {\n prototype: WebGLProgram;\n new(): WebGLProgram;\n};\n\ninterface WebGLRenderbuffer extends WebGLObject {\n}\n\ndeclare var WebGLRenderbuffer: {\n prototype: WebGLRenderbuffer;\n new(): WebGLRenderbuffer;\n};\n\ninterface WebGLRenderingContext {\n readonly canvas: HTMLCanvasElement;\n readonly drawingBufferHeight: number;\n readonly drawingBufferWidth: number;\n activeTexture(texture: number): void;\n attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void;\n bindBuffer(target: number, buffer: WebGLBuffer | null): void;\n bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void;\n bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void;\n bindTexture(target: number, texture: WebGLTexture | null): void;\n blendColor(red: number, green: number, blue: number, alpha: number): void;\n blendEquation(mode: number): void;\n blendEquationSeparate(modeRGB: number, modeAlpha: number): void;\n blendFunc(sfactor: number, dfactor: number): void;\n blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;\n bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void;\n bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void;\n checkFramebufferStatus(target: number): number;\n clear(mask: number): void;\n clearColor(red: number, green: number, blue: number, alpha: number): void;\n clearDepth(depth: number): void;\n clearStencil(s: number): void;\n colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void;\n compileShader(shader: WebGLShader | null): void;\n compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void;\n copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void;\n createBuffer(): WebGLBuffer | null;\n createFramebuffer(): WebGLFramebuffer | null;\n createProgram(): WebGLProgram | null;\n createRenderbuffer(): WebGLRenderbuffer | null;\n createShader(type: number): WebGLShader | null;\n createTexture(): WebGLTexture | null;\n cullFace(mode: number): void;\n deleteBuffer(buffer: WebGLBuffer | null): void;\n deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void;\n deleteProgram(program: WebGLProgram | null): void;\n deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void;\n deleteShader(shader: WebGLShader | null): void;\n deleteTexture(texture: WebGLTexture | null): void;\n depthFunc(func: number): void;\n depthMask(flag: boolean): void;\n depthRange(zNear: number, zFar: number): void;\n detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n disable(cap: number): void;\n disableVertexAttribArray(index: number): void;\n drawArrays(mode: number, first: number, count: number): void;\n drawElements(mode: number, count: number, type: number, offset: number): void;\n enable(cap: number): void;\n enableVertexAttribArray(index: number): void;\n finish(): void;\n flush(): void;\n framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void;\n framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void;\n frontFace(mode: number): void;\n generateMipmap(target: number): void;\n getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null;\n getAttribLocation(program: WebGLProgram | null, name: string): number;\n getBufferParameter(target: number, pname: number): any;\n getContextAttributes(): WebGLContextAttributes;\n getError(): number;\n getExtension(extensionName: \"EXT_blend_minmax\"): EXT_blend_minmax | null;\n getExtension(extensionName: \"EXT_texture_filter_anisotropic\"): EXT_texture_filter_anisotropic | null;\n getExtension(extensionName: \"EXT_frag_depth\"): EXT_frag_depth | null;\n getExtension(extensionName: \"EXT_shader_texture_lod\"): EXT_shader_texture_lod | null;\n getExtension(extensionName: \"EXT_sRGB\"): EXT_sRGB | null;\n getExtension(extensionName: \"OES_vertex_array_object\"): OES_vertex_array_object | null;\n getExtension(extensionName: \"WEBGL_color_buffer_float\"): WEBGL_color_buffer_float | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_astc\"): WEBGL_compressed_texture_astc | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc_srgb\"): WEBGL_compressed_texture_s3tc_srgb | null;\n getExtension(extensionName: \"WEBGL_debug_shaders\"): WEBGL_debug_shaders | null;\n getExtension(extensionName: \"WEBGL_draw_buffers\"): WEBGL_draw_buffers | null;\n getExtension(extensionName: \"WEBGL_lose_context\"): WEBGL_lose_context | null;\n getExtension(extensionName: \"WEBGL_depth_texture\"): WEBGL_depth_texture | null;\n getExtension(extensionName: \"WEBGL_debug_renderer_info\"): WEBGL_debug_renderer_info | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc\"): WEBGL_compressed_texture_s3tc | null;\n getExtension(extensionName: \"OES_texture_half_float_linear\"): OES_texture_half_float_linear | null;\n getExtension(extensionName: \"OES_texture_half_float\"): OES_texture_half_float | null;\n getExtension(extensionName: \"OES_texture_float_linear\"): OES_texture_float_linear | null;\n getExtension(extensionName: \"OES_texture_float\"): OES_texture_float | null;\n getExtension(extensionName: \"OES_standard_derivatives\"): OES_standard_derivatives | null;\n getExtension(extensionName: \"OES_element_index_uint\"): OES_element_index_uint | null;\n getExtension(extensionName: \"ANGLE_instanced_arrays\"): ANGLE_instanced_arrays | null;\n getExtension(extensionName: string): any;\n getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any;\n getParameter(pname: number): any;\n getProgramInfoLog(program: WebGLProgram | null): string | null;\n getProgramParameter(program: WebGLProgram | null, pname: number): any;\n getRenderbufferParameter(target: number, pname: number): any;\n getShaderInfoLog(shader: WebGLShader | null): string | null;\n getShaderParameter(shader: WebGLShader | null, pname: number): any;\n getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null;\n getShaderSource(shader: WebGLShader | null): string | null;\n getSupportedExtensions(): string[] | null;\n getTexParameter(target: number, pname: number): any;\n getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any;\n getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null;\n getVertexAttrib(index: number, pname: number): any;\n getVertexAttribOffset(index: number, pname: number): number;\n hint(target: number, mode: number): void;\n isBuffer(buffer: WebGLBuffer | null): boolean;\n isContextLost(): boolean;\n isEnabled(cap: number): boolean;\n isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean;\n isProgram(program: WebGLProgram | null): boolean;\n isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean;\n isShader(shader: WebGLShader | null): boolean;\n isTexture(texture: WebGLTexture | null): boolean;\n lineWidth(width: number): void;\n linkProgram(program: WebGLProgram | null): void;\n pixelStorei(pname: number, param: number | boolean): void;\n polygonOffset(factor: number, units: number): void;\n readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n renderbufferStorage(target: number, internalformat: number, width: number, height: number): void;\n sampleCoverage(value: number, invert: boolean): void;\n scissor(x: number, y: number, width: number, height: number): void;\n shaderSource(shader: WebGLShader | null, source: string): void;\n stencilFunc(func: number, ref: number, mask: number): void;\n stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void;\n stencilMask(mask: number): void;\n stencilMaskSeparate(face: number, mask: number): void;\n stencilOp(fail: number, zfail: number, zpass: number): void;\n stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void;\n texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n texParameterf(target: number, pname: number, param: number): void;\n texParameteri(target: number, pname: number, param: number): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n uniform1f(location: WebGLUniformLocation | null, x: number): void;\n uniform1fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform1i(location: WebGLUniformLocation | null, x: number): void;\n uniform1iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n useProgram(program: WebGLProgram | null): void;\n validateProgram(program: WebGLProgram | null): void;\n vertexAttrib1f(indx: number, x: number): void;\n vertexAttrib1fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib2f(indx: number, x: number, y: number): void;\n vertexAttrib2fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib3f(indx: number, x: number, y: number, z: number): void;\n vertexAttrib3fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void;\n vertexAttrib4fv(indx: number, values: Float32Array | number[]): void;\n vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void;\n viewport(x: number, y: number, width: number, height: number): void;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n}\n\ndeclare var WebGLRenderingContext: {\n prototype: WebGLRenderingContext;\n new(): WebGLRenderingContext;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n};\n\ninterface WebGLShader extends WebGLObject {\n}\n\ndeclare var WebGLShader: {\n prototype: WebGLShader;\n new(): WebGLShader;\n};\n\ninterface WebGLShaderPrecisionFormat {\n readonly precision: number;\n readonly rangeMax: number;\n readonly rangeMin: number;\n}\n\ndeclare var WebGLShaderPrecisionFormat: {\n prototype: WebGLShaderPrecisionFormat;\n new(): WebGLShaderPrecisionFormat;\n};\n\ninterface WebGLTexture extends WebGLObject {\n}\n\ndeclare var WebGLTexture: {\n prototype: WebGLTexture;\n new(): WebGLTexture;\n};\n\ninterface WebGLUniformLocation {\n}\n\ndeclare var WebGLUniformLocation: {\n prototype: WebGLUniformLocation;\n new(): WebGLUniformLocation;\n};\n\ninterface WebGLVertexArrayObjectOES {\n}\n\ninterface WebKitCSSMatrix {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n m11: number;\n m12: number;\n m13: number;\n m14: number;\n m21: number;\n m22: number;\n m23: number;\n m24: number;\n m31: number;\n m32: number;\n m33: number;\n m34: number;\n m41: number;\n m42: number;\n m43: number;\n m44: number;\n inverse(): WebKitCSSMatrix;\n multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix;\n rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix;\n rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix;\n scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix;\n setMatrixValue(value: string): void;\n skewX(angle: number): WebKitCSSMatrix;\n skewY(angle: number): WebKitCSSMatrix;\n toString(): string;\n translate(x: number, y: number, z?: number): WebKitCSSMatrix;\n}\n\ndeclare var WebKitCSSMatrix: {\n prototype: WebKitCSSMatrix;\n new(text?: string): WebKitCSSMatrix;\n};\n\ninterface WebKitDirectoryEntry extends WebKitEntry {\n createReader(): WebKitDirectoryReader;\n}\n\ndeclare var WebKitDirectoryEntry: {\n prototype: WebKitDirectoryEntry;\n new(): WebKitDirectoryEntry;\n};\n\ninterface WebKitDirectoryReader {\n readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void;\n}\n\ndeclare var WebKitDirectoryReader: {\n prototype: WebKitDirectoryReader;\n new(): WebKitDirectoryReader;\n};\n\ninterface WebKitEntry {\n readonly filesystem: WebKitFileSystem;\n readonly fullPath: string;\n readonly isDirectory: boolean;\n readonly isFile: boolean;\n readonly name: string;\n}\n\ndeclare var WebKitEntry: {\n prototype: WebKitEntry;\n new(): WebKitEntry;\n};\n\ninterface WebKitFileEntry extends WebKitEntry {\n file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void;\n}\n\ndeclare var WebKitFileEntry: {\n prototype: WebKitFileEntry;\n new(): WebKitFileEntry;\n};\n\ninterface WebKitFileSystem {\n readonly name: string;\n readonly root: WebKitDirectoryEntry;\n}\n\ndeclare var WebKitFileSystem: {\n prototype: WebKitFileSystem;\n new(): WebKitFileSystem;\n};\n\ninterface WebKitPoint {\n x: number;\n y: number;\n}\n\ndeclare var WebKitPoint: {\n prototype: WebKitPoint;\n new(x?: number, y?: number): WebKitPoint;\n};\n\ninterface WebSocketEventMap {\n \"close\": CloseEvent;\n \"error\": Event;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface WebSocket extends EventTarget {\n binaryType: BinaryType;\n readonly bufferedAmount: number;\n readonly extensions: string;\n onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;\n onerror: ((this: WebSocket, ev: Event) => any) | null;\n onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;\n onopen: ((this: WebSocket, ev: Event) => any) | null;\n readonly protocol: string;\n readonly readyState: number;\n readonly url: string;\n close(code?: number, reason?: string): void;\n send(data: string | ArrayBuffer | Blob | ArrayBufferView): void;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var WebSocket: {\n prototype: WebSocket;\n new(url: string, protocols?: string | string[]): WebSocket;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n};\n\ninterface WheelEvent extends MouseEvent {\n readonly deltaMode: number;\n readonly deltaX: number;\n readonly deltaY: number;\n readonly deltaZ: number;\n readonly wheelDelta: number;\n readonly wheelDeltaX: number;\n readonly wheelDeltaY: number;\n getCurrentPoint(element: Element): void;\n initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n}\n\ndeclare var WheelEvent: {\n prototype: WheelEvent;\n new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n};\n\ninterface WindowEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"beforeunload\": BeforeUnloadEvent;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"compassneedscalibration\": Event;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"devicelight\": DeviceLightEvent;\n \"devicemotion\": DeviceMotionEvent;\n \"deviceorientation\": DeviceOrientationEvent;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"hashchange\": HashChangeEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"message\": MessageEvent;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"offline\": Event;\n \"online\": Event;\n \"orientationchange\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"popstate\": PopStateEvent;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": ProgressEvent;\n \"reset\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"stalled\": Event;\n \"storage\": StorageEvent;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"unload\": Event;\n \"volumechange\": Event;\n \"vrdisplayactivate\": Event;\n \"vrdisplayblur\": Event;\n \"vrdisplayconnect\": Event;\n \"vrdisplaydeactivate\": Event;\n \"vrdisplaydisconnect\": Event;\n \"vrdisplayfocus\": Event;\n \"vrdisplaypointerrestricted\": Event;\n \"vrdisplaypointerunrestricted\": Event;\n \"vrdisplaypresentchange\": Event;\n \"waiting\": Event;\n}\n\ninterface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {\n Blob: typeof Blob;\n URL: typeof URL;\n URLSearchParams: typeof URLSearchParams;\n readonly applicationCache: ApplicationCache;\n readonly caches: CacheStorage;\n readonly clientInformation: Navigator;\n readonly closed: boolean;\n readonly crypto: Crypto;\n customElements: CustomElementRegistry;\n defaultStatus: string;\n readonly devicePixelRatio: number;\n readonly doNotTrack: string;\n readonly document: Document;\n event: Event | undefined;\n readonly external: External;\n readonly frameElement: Element;\n readonly frames: Window;\n readonly history: History;\n readonly innerHeight: number;\n readonly innerWidth: number;\n readonly isSecureContext: boolean;\n readonly length: number;\n location: Location;\n readonly locationbar: BarProp;\n readonly menubar: BarProp;\n readonly msContentScript: ExtensionScriptApis;\n readonly msCredentials: MSCredentials;\n name: string;\n readonly navigator: Navigator;\n offscreenBuffering: string | boolean;\n onabort: ((this: Window, ev: UIEvent) => any) | null;\n onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\n onblur: ((this: Window, ev: FocusEvent) => any) | null;\n oncanplay: ((this: Window, ev: Event) => any) | null;\n oncanplaythrough: ((this: Window, ev: Event) => any) | null;\n onchange: ((this: Window, ev: Event) => any) | null;\n onclick: ((this: Window, ev: MouseEvent) => any) | null;\n oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\n oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\n ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\n ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\n ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\n ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\n ondrag: ((this: Window, ev: DragEvent) => any) | null;\n ondragend: ((this: Window, ev: DragEvent) => any) | null;\n ondragenter: ((this: Window, ev: DragEvent) => any) | null;\n ondragleave: ((this: Window, ev: DragEvent) => any) | null;\n ondragover: ((this: Window, ev: DragEvent) => any) | null;\n ondragstart: ((this: Window, ev: DragEvent) => any) | null;\n ondrop: ((this: Window, ev: DragEvent) => any) | null;\n ondurationchange: ((this: Window, ev: Event) => any) | null;\n onemptied: ((this: Window, ev: Event) => any) | null;\n onended: ((this: Window, ev: Event) => any) | null;\n onerror: ErrorEventHandler;\n onfocus: ((this: Window, ev: FocusEvent) => any) | null;\n onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\n oninput: ((this: Window, ev: Event) => any) | null;\n oninvalid: ((this: Window, ev: Event) => any) | null;\n onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\n onload: ((this: Window, ev: Event) => any) | null;\n onloadeddata: ((this: Window, ev: Event) => any) | null;\n onloadedmetadata: ((this: Window, ev: Event) => any) | null;\n onloadstart: ((this: Window, ev: Event) => any) | null;\n onmessage: ((this: Window, ev: MessageEvent) => any) | null;\n onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\n onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\n onmsgesturechange: ((this: Window, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\n onmsgestureend: ((this: Window, ev: Event) => any) | null;\n onmsgesturehold: ((this: Window, ev: Event) => any) | null;\n onmsgesturestart: ((this: Window, ev: Event) => any) | null;\n onmsgesturetap: ((this: Window, ev: Event) => any) | null;\n onmsinertiastart: ((this: Window, ev: Event) => any) | null;\n onmspointercancel: ((this: Window, ev: Event) => any) | null;\n onmspointerdown: ((this: Window, ev: Event) => any) | null;\n onmspointerenter: ((this: Window, ev: Event) => any) | null;\n onmspointerleave: ((this: Window, ev: Event) => any) | null;\n onmspointermove: ((this: Window, ev: Event) => any) | null;\n onmspointerout: ((this: Window, ev: Event) => any) | null;\n onmspointerover: ((this: Window, ev: Event) => any) | null;\n onmspointerup: ((this: Window, ev: Event) => any) | null;\n onoffline: ((this: Window, ev: Event) => any) | null;\n ononline: ((this: Window, ev: Event) => any) | null;\n onorientationchange: ((this: Window, ev: Event) => any) | null;\n onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpause: ((this: Window, ev: Event) => any) | null;\n onplay: ((this: Window, ev: Event) => any) | null;\n onplaying: ((this: Window, ev: Event) => any) | null;\n onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\n onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\n onratechange: ((this: Window, ev: Event) => any) | null;\n onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\n onreset: ((this: Window, ev: Event) => any) | null;\n onresize: ((this: Window, ev: UIEvent) => any) | null;\n onscroll: ((this: Window, ev: UIEvent) => any) | null;\n onseeked: ((this: Window, ev: Event) => any) | null;\n onseeking: ((this: Window, ev: Event) => any) | null;\n onselect: ((this: Window, ev: UIEvent) => any) | null;\n onstalled: ((this: Window, ev: Event) => any) | null;\n onstorage: ((this: Window, ev: StorageEvent) => any) | null;\n onsubmit: ((this: Window, ev: Event) => any) | null;\n onsuspend: ((this: Window, ev: Event) => any) | null;\n ontimeupdate: ((this: Window, ev: Event) => any) | null;\n ontouchcancel: (ev: TouchEvent) => any;\n ontouchend: (ev: TouchEvent) => any;\n ontouchmove: (ev: TouchEvent) => any;\n ontouchstart: (ev: TouchEvent) => any;\n onunload: ((this: Window, ev: Event) => any) | null;\n onvolumechange: ((this: Window, ev: Event) => any) | null;\n onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\n onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\n onwaiting: ((this: Window, ev: Event) => any) | null;\n readonly opener: any;\n readonly orientation: string | number;\n readonly outerHeight: number;\n readonly outerWidth: number;\n readonly pageXOffset: number;\n readonly pageYOffset: number;\n readonly parent: Window;\n readonly performance: Performance;\n readonly personalbar: BarProp;\n readonly screen: Screen;\n readonly screenLeft: number;\n readonly screenTop: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly scrollX: number;\n readonly scrollY: number;\n readonly scrollbars: BarProp;\n readonly self: Window;\n readonly speechSynthesis: SpeechSynthesis;\n status: string;\n readonly statusbar: BarProp;\n readonly styleMedia: StyleMedia;\n readonly toolbar: BarProp;\n readonly top: Window;\n readonly window: Window;\n alert(message?: any): void;\n blur(): void;\n cancelAnimationFrame(handle: number): void;\n captureEvents(): void;\n close(): void;\n confirm(message?: string): boolean;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\n departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\n focus(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\n getSelection(): Selection;\n matchMedia(mediaQuery: string): MediaQueryList;\n moveBy(x?: number, y?: number): void;\n moveTo(x?: number, y?: number): void;\n msWriteProfilerMark(profilerMarkName: string): void;\n open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\n postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\n prompt(message?: string, _default?: string): string | null;\n releaseEvents(): void;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n resizeBy(x?: number, y?: number): void;\n resizeTo(x?: number, y?: number): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x?: number, y?: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x?: number, y?: number): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x?: number, y?: number): void;\n stop(): void;\n webkitCancelAnimationFrame(handle: number): void;\n webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\n addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Window: {\n prototype: Window;\n new(): Window;\n};\n\ninterface WindowBase64 {\n atob(encodedString: string): string;\n btoa(rawString: string): string;\n}\n\ninterface WindowConsole {\n readonly console: Console;\n}\n\ninterface WindowEventHandlersEventMap {\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"hashchange\": HashChangeEvent;\n \"message\": MessageEvent;\n \"offline\": Event;\n \"online\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"popstate\": PopStateEvent;\n \"storage\": StorageEvent;\n \"unload\": Event;\n}\n\ninterface WindowEventHandlers {\n onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null;\n onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null;\n onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null;\n onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n ononline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null;\n onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null;\n onunload: ((this: WindowEventHandlers, ev: Event) => any) | null;\n addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface WindowLocalStorage {\n readonly localStorage: Storage;\n}\n\ninterface WindowSessionStorage {\n readonly sessionStorage: Storage;\n}\n\ninterface WindowTimers extends WindowTimersExtension {\n clearInterval(handle?: number): void;\n clearTimeout(handle?: number): void;\n setInterval(handler: (...args: any[]) => void, timeout: number): number;\n setInterval(handler: any, timeout?: any, ...args: any[]): number;\n setTimeout(handler: (...args: any[]) => void, timeout: number): number;\n setTimeout(handler: any, timeout?: any, ...args: any[]): number;\n}\n\ninterface WindowTimersExtension {\n clearImmediate(handle: number): void;\n setImmediate(handler: (...args: any[]) => void): number;\n setImmediate(handler: any, ...args: any[]): number;\n}\n\ninterface WorkerEventMap extends AbstractWorkerEventMap {\n \"message\": MessageEvent;\n}\n\ninterface Worker extends EventTarget, AbstractWorker {\n onmessage: ((this: Worker, ev: MessageEvent) => any) | null;\n /** @deprecated */\n postMessage(message: any, transfer?: any[]): void;\n terminate(): void;\n addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Worker: {\n prototype: Worker;\n new(stringUrl: string): Worker;\n};\n\ninterface WritableStream {\n readonly locked: boolean;\n abort(reason?: any): Promise;\n getWriter(): WritableStreamDefaultWriter;\n}\n\ndeclare var WritableStream: {\n prototype: WritableStream;\n new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream;\n};\n\ninterface WritableStreamDefaultController {\n error(error?: any): void;\n}\n\ndeclare var WritableStreamDefaultController: {\n prototype: WritableStreamDefaultController;\n new(): WritableStreamDefaultController;\n};\n\ninterface WritableStreamDefaultWriter {\n readonly closed: Promise;\n readonly desiredSize: number;\n readonly ready: Promise;\n abort(reason?: any): Promise;\n close(): Promise;\n releaseLock(): void;\n write(chunk?: any): Promise;\n}\n\ndeclare var WritableStreamDefaultWriter: {\n prototype: WritableStreamDefaultWriter;\n new(): WritableStreamDefaultWriter;\n};\n\ninterface XMLDocument extends Document {\n addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLDocument: {\n prototype: XMLDocument;\n new(): XMLDocument;\n};\n\ninterface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {\n \"readystatechange\": Event;\n}\n\ninterface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {\n msCaching: string;\n onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;\n readonly readyState: number;\n readonly response: any;\n readonly responseText: string;\n responseType: XMLHttpRequestResponseType;\n readonly responseURL: string;\n readonly responseXML: Document | null;\n readonly status: number;\n readonly statusText: string;\n timeout: number;\n readonly upload: XMLHttpRequestUpload;\n withCredentials: boolean;\n abort(): void;\n getAllResponseHeaders(): string;\n getResponseHeader(header: string): string | null;\n msCachingEnabled(): boolean;\n open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): void;\n overrideMimeType(mime: string): void;\n send(data?: any): void;\n setRequestHeader(header: string, value: string): void;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequest: {\n prototype: XMLHttpRequest;\n new(): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\n\ninterface XMLHttpRequestEventTargetEventMap {\n \"abort\": Event;\n \"error\": ErrorEvent;\n \"load\": Event;\n \"loadend\": ProgressEvent;\n \"loadstart\": Event;\n \"progress\": ProgressEvent;\n \"timeout\": ProgressEvent;\n}\n\ninterface XMLHttpRequestEventTarget {\n onabort: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null;\n onload: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {\n addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestUpload: {\n prototype: XMLHttpRequestUpload;\n new(): XMLHttpRequestUpload;\n};\n\ninterface XMLSerializer {\n serializeToString(target: Node): string;\n}\n\ndeclare var XMLSerializer: {\n prototype: XMLSerializer;\n new(): XMLSerializer;\n};\n\ninterface XPathEvaluator {\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver?: Node): XPathNSResolver;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathEvaluator: {\n prototype: XPathEvaluator;\n new(): XPathEvaluator;\n};\n\ninterface XPathExpression {\n evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathExpression: {\n prototype: XPathExpression;\n new(): XPathExpression;\n};\n\ninterface XPathNSResolver {\n lookupNamespaceURI(prefix: string): string;\n}\n\ndeclare var XPathNSResolver: {\n prototype: XPathNSResolver;\n new(): XPathNSResolver;\n};\n\ninterface XPathResult {\n readonly booleanValue: boolean;\n readonly invalidIteratorState: boolean;\n readonly numberValue: number;\n readonly resultType: number;\n readonly singleNodeValue: Node;\n readonly snapshotLength: number;\n readonly stringValue: string;\n iterateNext(): Node;\n snapshotItem(index: number): Node;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n}\n\ndeclare var XPathResult: {\n prototype: XPathResult;\n new(): XPathResult;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n};\n\ninterface XSLTProcessor {\n clearParameters(): void;\n getParameter(namespaceURI: string, localName: string): any;\n importStylesheet(style: Node): void;\n removeParameter(namespaceURI: string, localName: string): void;\n reset(): void;\n setParameter(namespaceURI: string, localName: string, value: any): void;\n transformToDocument(source: Node): Document;\n transformToFragment(source: Node, document: Document): DocumentFragment;\n}\n\ndeclare var XSLTProcessor: {\n prototype: XSLTProcessor;\n new(): XSLTProcessor;\n};\n\ninterface webkitRTCPeerConnection extends RTCPeerConnection {\n addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var webkitRTCPeerConnection: {\n prototype: webkitRTCPeerConnection;\n new(configuration: RTCConfiguration): webkitRTCPeerConnection;\n};\n\ndeclare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;\n\ninterface DecodeErrorCallback {\n (error: DOMException): void;\n}\n\ninterface DecodeSuccessCallback {\n (decodedData: AudioBuffer): void;\n}\n\ninterface ErrorEventHandler {\n (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void;\n}\n\ninterface EventHandlerNonNull {\n (event: Event): any;\n}\n\ninterface ForEachCallback {\n (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void;\n}\n\ninterface FrameRequestCallback {\n (time: number): void;\n}\n\ninterface FunctionStringCallback {\n (data: string): void;\n}\n\ninterface IntersectionObserverCallback {\n (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;\n}\n\ninterface MSLaunchUriCallback {\n (): void;\n}\n\ninterface MediaQueryListListener {\n (mql: MediaQueryList): void;\n}\n\ninterface MutationCallback {\n (mutations: MutationRecord[], observer: MutationObserver): void;\n}\n\ninterface NavigatorUserMediaErrorCallback {\n (error: MediaStreamError): void;\n}\n\ninterface NavigatorUserMediaSuccessCallback {\n (stream: MediaStream): void;\n}\n\ninterface NotificationPermissionCallback {\n (permission: NotificationPermission): void;\n}\n\ninterface PositionCallback {\n (position: Position): void;\n}\n\ninterface PositionErrorCallback {\n (error: PositionError): void;\n}\n\ninterface RTCPeerConnectionErrorCallback {\n (error: DOMError): void;\n}\n\ninterface RTCSessionDescriptionCallback {\n (sdp: RTCSessionDescription): void;\n}\n\ninterface RTCStatsCallback {\n (report: RTCStatsReport): void;\n}\n\ninterface VoidFunction {\n (): void;\n}\n\ninterface WritableStreamChunkCallback {\n (chunk: any, controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamDefaultControllerCallback {\n (controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamErrorCallback {\n (reason: string): void;\n}\n\ninterface HTMLElementTagNameMap {\n \"a\": HTMLAnchorElement;\n \"abbr\": HTMLElement;\n \"acronym\": HTMLElement;\n \"address\": HTMLElement;\n \"applet\": HTMLAppletElement;\n \"area\": HTMLAreaElement;\n \"article\": HTMLElement;\n \"aside\": HTMLElement;\n \"audio\": HTMLAudioElement;\n \"b\": HTMLElement;\n \"base\": HTMLBaseElement;\n \"basefont\": HTMLBaseFontElement;\n \"bdo\": HTMLElement;\n \"big\": HTMLElement;\n \"blockquote\": HTMLQuoteElement;\n \"body\": HTMLBodyElement;\n \"br\": HTMLBRElement;\n \"button\": HTMLButtonElement;\n \"canvas\": HTMLCanvasElement;\n \"caption\": HTMLTableCaptionElement;\n \"center\": HTMLElement;\n \"cite\": HTMLElement;\n \"code\": HTMLElement;\n \"col\": HTMLTableColElement;\n \"colgroup\": HTMLTableColElement;\n \"data\": HTMLDataElement;\n \"datalist\": HTMLDataListElement;\n \"dd\": HTMLElement;\n \"del\": HTMLModElement;\n \"dfn\": HTMLElement;\n \"dir\": HTMLDirectoryElement;\n \"div\": HTMLDivElement;\n \"dl\": HTMLDListElement;\n \"dt\": HTMLElement;\n \"em\": HTMLElement;\n \"embed\": HTMLEmbedElement;\n \"fieldset\": HTMLFieldSetElement;\n \"figcaption\": HTMLElement;\n \"figure\": HTMLElement;\n \"font\": HTMLFontElement;\n \"footer\": HTMLElement;\n \"form\": HTMLFormElement;\n \"frame\": HTMLFrameElement;\n \"frameset\": HTMLFrameSetElement;\n \"h1\": HTMLHeadingElement;\n \"h2\": HTMLHeadingElement;\n \"h3\": HTMLHeadingElement;\n \"h4\": HTMLHeadingElement;\n \"h5\": HTMLHeadingElement;\n \"h6\": HTMLHeadingElement;\n \"head\": HTMLHeadElement;\n \"header\": HTMLElement;\n \"hgroup\": HTMLElement;\n \"hr\": HTMLHRElement;\n \"html\": HTMLHtmlElement;\n \"i\": HTMLElement;\n \"iframe\": HTMLIFrameElement;\n \"img\": HTMLImageElement;\n \"input\": HTMLInputElement;\n \"ins\": HTMLModElement;\n \"isindex\": HTMLUnknownElement;\n \"kbd\": HTMLElement;\n \"keygen\": HTMLElement;\n \"label\": HTMLLabelElement;\n \"legend\": HTMLLegendElement;\n \"li\": HTMLLIElement;\n \"link\": HTMLLinkElement;\n \"listing\": HTMLPreElement;\n \"map\": HTMLMapElement;\n \"mark\": HTMLElement;\n \"marquee\": HTMLMarqueeElement;\n \"menu\": HTMLMenuElement;\n \"meta\": HTMLMetaElement;\n \"meter\": HTMLMeterElement;\n \"nav\": HTMLElement;\n \"nextid\": HTMLUnknownElement;\n \"nobr\": HTMLElement;\n \"noframes\": HTMLElement;\n \"noscript\": HTMLElement;\n \"object\": HTMLObjectElement;\n \"ol\": HTMLOListElement;\n \"optgroup\": HTMLOptGroupElement;\n \"option\": HTMLOptionElement;\n \"output\": HTMLOutputElement;\n \"p\": HTMLParagraphElement;\n \"param\": HTMLParamElement;\n \"picture\": HTMLPictureElement;\n \"plaintext\": HTMLElement;\n \"pre\": HTMLPreElement;\n \"progress\": HTMLProgressElement;\n \"q\": HTMLQuoteElement;\n \"rt\": HTMLElement;\n \"ruby\": HTMLElement;\n \"s\": HTMLElement;\n \"samp\": HTMLElement;\n \"script\": HTMLScriptElement;\n \"section\": HTMLElement;\n \"select\": HTMLSelectElement;\n \"slot\": HTMLSlotElement;\n \"small\": HTMLElement;\n \"source\": HTMLSourceElement;\n \"span\": HTMLSpanElement;\n \"strike\": HTMLElement;\n \"strong\": HTMLElement;\n \"style\": HTMLStyleElement;\n \"sub\": HTMLElement;\n \"sup\": HTMLElement;\n \"table\": HTMLTableElement;\n \"tbody\": HTMLTableSectionElement;\n \"td\": HTMLTableDataCellElement;\n \"template\": HTMLTemplateElement;\n \"textarea\": HTMLTextAreaElement;\n \"tfoot\": HTMLTableSectionElement;\n \"th\": HTMLTableHeaderCellElement;\n \"thead\": HTMLTableSectionElement;\n \"time\": HTMLTimeElement;\n \"title\": HTMLTitleElement;\n \"tr\": HTMLTableRowElement;\n \"track\": HTMLTrackElement;\n \"tt\": HTMLElement;\n \"u\": HTMLElement;\n \"ul\": HTMLUListElement;\n \"var\": HTMLElement;\n \"video\": HTMLVideoElement;\n \"wbr\": HTMLElement;\n \"xmp\": HTMLPreElement;\n}\n\ninterface SVGElementTagNameMap {\n \"circle\": SVGCircleElement;\n \"clippath\": SVGClipPathElement;\n \"defs\": SVGDefsElement;\n \"desc\": SVGDescElement;\n \"ellipse\": SVGEllipseElement;\n \"feblend\": SVGFEBlendElement;\n \"fecolormatrix\": SVGFEColorMatrixElement;\n \"fecomponenttransfer\": SVGFEComponentTransferElement;\n \"fecomposite\": SVGFECompositeElement;\n \"feconvolvematrix\": SVGFEConvolveMatrixElement;\n \"fediffuselighting\": SVGFEDiffuseLightingElement;\n \"fedisplacementmap\": SVGFEDisplacementMapElement;\n \"fedistantlight\": SVGFEDistantLightElement;\n \"feflood\": SVGFEFloodElement;\n \"fefunca\": SVGFEFuncAElement;\n \"fefuncb\": SVGFEFuncBElement;\n \"fefuncg\": SVGFEFuncGElement;\n \"fefuncr\": SVGFEFuncRElement;\n \"fegaussianblur\": SVGFEGaussianBlurElement;\n \"feimage\": SVGFEImageElement;\n \"femerge\": SVGFEMergeElement;\n \"femergenode\": SVGFEMergeNodeElement;\n \"femorphology\": SVGFEMorphologyElement;\n \"feoffset\": SVGFEOffsetElement;\n \"fepointlight\": SVGFEPointLightElement;\n \"fespecularlighting\": SVGFESpecularLightingElement;\n \"fespotlight\": SVGFESpotLightElement;\n \"fetile\": SVGFETileElement;\n \"feturbulence\": SVGFETurbulenceElement;\n \"filter\": SVGFilterElement;\n \"foreignobject\": SVGForeignObjectElement;\n \"g\": SVGGElement;\n \"image\": SVGImageElement;\n \"line\": SVGLineElement;\n \"lineargradient\": SVGLinearGradientElement;\n \"marker\": SVGMarkerElement;\n \"mask\": SVGMaskElement;\n \"metadata\": SVGMetadataElement;\n \"path\": SVGPathElement;\n \"pattern\": SVGPatternElement;\n \"polygon\": SVGPolygonElement;\n \"polyline\": SVGPolylineElement;\n \"radialgradient\": SVGRadialGradientElement;\n \"rect\": SVGRectElement;\n \"stop\": SVGStopElement;\n \"svg\": SVGSVGElement;\n \"switch\": SVGSwitchElement;\n \"symbol\": SVGSymbolElement;\n \"text\": SVGTextElement;\n \"textpath\": SVGTextPathElement;\n \"tspan\": SVGTSpanElement;\n \"use\": SVGUseElement;\n \"view\": SVGViewElement;\n}\n\n/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */\ninterface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { }\n\ndeclare var Audio: {\n new(src?: string): HTMLAudioElement;\n};\ndeclare var Image: {\n new(width?: number, height?: number): HTMLImageElement;\n};\ndeclare var Option: {\n new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement;\n};\ndeclare var Blob: typeof Blob;\ndeclare var URL: typeof URL;\ndeclare var URLSearchParams: typeof URLSearchParams;\ndeclare var applicationCache: ApplicationCache;\ndeclare var caches: CacheStorage;\ndeclare var clientInformation: Navigator;\ndeclare var closed: boolean;\ndeclare var crypto: Crypto;\ndeclare var customElements: CustomElementRegistry;\ndeclare var defaultStatus: string;\ndeclare var devicePixelRatio: number;\ndeclare var doNotTrack: string;\ndeclare var document: Document;\ndeclare var event: Event | undefined;\ndeclare var external: External;\ndeclare var frameElement: Element;\ndeclare var frames: Window;\ndeclare var history: History;\ndeclare var innerHeight: number;\ndeclare var innerWidth: number;\ndeclare var isSecureContext: boolean;\ndeclare var length: number;\ndeclare var location: Location;\ndeclare var locationbar: BarProp;\ndeclare var menubar: BarProp;\ndeclare var msContentScript: ExtensionScriptApis;\ndeclare var msCredentials: MSCredentials;\ndeclare const name: never;\ndeclare var navigator: Navigator;\ndeclare var offscreenBuffering: string | boolean;\ndeclare var onabort: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\ndeclare var onblur: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var oncanplay: ((this: Window, ev: Event) => any) | null;\ndeclare var oncanplaythrough: ((this: Window, ev: Event) => any) | null;\ndeclare var onchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\ndeclare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\ndeclare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\ndeclare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\ndeclare var ondrag: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragend: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragenter: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragleave: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragover: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragstart: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondrop: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondurationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onemptied: ((this: Window, ev: Event) => any) | null;\ndeclare var onended: ((this: Window, ev: Event) => any) | null;\ndeclare var onerror: ErrorEventHandler;\ndeclare var onfocus: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\ndeclare var oninput: ((this: Window, ev: Event) => any) | null;\ndeclare var oninvalid: ((this: Window, ev: Event) => any) | null;\ndeclare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onload: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadeddata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadedmetadata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadstart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;\ndeclare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var onmsgesturechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgestureend: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturehold: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturestart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturetap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsinertiastart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointercancel: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerdown: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerenter: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerleave: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointermove: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerout: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerover: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerup: ((this: Window, ev: Event) => any) | null;\ndeclare var onoffline: ((this: Window, ev: Event) => any) | null;\ndeclare var ononline: ((this: Window, ev: Event) => any) | null;\ndeclare var onorientationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpause: ((this: Window, ev: Event) => any) | null;\ndeclare var onplay: ((this: Window, ev: Event) => any) | null;\ndeclare var onplaying: ((this: Window, ev: Event) => any) | null;\ndeclare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\ndeclare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onratechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onreset: ((this: Window, ev: Event) => any) | null;\ndeclare var onresize: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onscroll: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onseeked: ((this: Window, ev: Event) => any) | null;\ndeclare var onseeking: ((this: Window, ev: Event) => any) | null;\ndeclare var onselect: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onstalled: ((this: Window, ev: Event) => any) | null;\ndeclare var onstorage: ((this: Window, ev: StorageEvent) => any) | null;\ndeclare var onsubmit: ((this: Window, ev: Event) => any) | null;\ndeclare var onsuspend: ((this: Window, ev: Event) => any) | null;\ndeclare var ontimeupdate: ((this: Window, ev: Event) => any) | null;\ndeclare var ontouchcancel: (ev: TouchEvent) => any;\ndeclare var ontouchend: (ev: TouchEvent) => any;\ndeclare var ontouchmove: (ev: TouchEvent) => any;\ndeclare var ontouchstart: (ev: TouchEvent) => any;\ndeclare var onunload: ((this: Window, ev: Event) => any) | null;\ndeclare var onvolumechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onwaiting: ((this: Window, ev: Event) => any) | null;\ndeclare var opener: any;\ndeclare var orientation: string | number;\ndeclare var outerHeight: number;\ndeclare var outerWidth: number;\ndeclare var pageXOffset: number;\ndeclare var pageYOffset: number;\ndeclare var parent: Window;\ndeclare var performance: Performance;\ndeclare var personalbar: BarProp;\ndeclare var screen: Screen;\ndeclare var screenLeft: number;\ndeclare var screenTop: number;\ndeclare var screenX: number;\ndeclare var screenY: number;\ndeclare var scrollX: number;\ndeclare var scrollY: number;\ndeclare var scrollbars: BarProp;\ndeclare var self: Window;\ndeclare var speechSynthesis: SpeechSynthesis;\ndeclare var status: string;\ndeclare var statusbar: BarProp;\ndeclare var styleMedia: StyleMedia;\ndeclare var toolbar: BarProp;\ndeclare var top: Window;\ndeclare var window: Window;\ndeclare function alert(message?: any): void;\ndeclare function blur(): void;\ndeclare function cancelAnimationFrame(handle: number): void;\ndeclare function captureEvents(): void;\ndeclare function close(): void;\ndeclare function confirm(message?: string): boolean;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\ndeclare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\ndeclare function focus(): void;\ndeclare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\ndeclare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\ndeclare function getSelection(): Selection;\ndeclare function matchMedia(mediaQuery: string): MediaQueryList;\ndeclare function moveBy(x?: number, y?: number): void;\ndeclare function moveTo(x?: number, y?: number): void;\ndeclare function msWriteProfilerMark(profilerMarkName: string): void;\ndeclare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\ndeclare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\ndeclare function prompt(message?: string, _default?: string): string | null;\ndeclare function releaseEvents(): void;\ndeclare function requestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function resizeBy(x?: number, y?: number): void;\ndeclare function resizeTo(x?: number, y?: number): void;\ndeclare function scroll(options?: ScrollToOptions): void;\ndeclare function scroll(x?: number, y?: number): void;\ndeclare function scrollBy(options?: ScrollToOptions): void;\ndeclare function scrollBy(x?: number, y?: number): void;\ndeclare function scrollTo(options?: ScrollToOptions): void;\ndeclare function scrollTo(x?: number, y?: number): void;\ndeclare function stop(): void;\ndeclare function webkitCancelAnimationFrame(handle: number): void;\ndeclare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function toString(): string;\ndeclare function dispatchEvent(evt: Event): boolean;\ndeclare function clearInterval(handle?: number): void;\ndeclare function clearTimeout(handle?: number): void;\ndeclare function setInterval(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setInterval(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function clearImmediate(handle: number): void;\ndeclare function setImmediate(handler: (...args: any[]) => void): number;\ndeclare function setImmediate(handler: any, ...args: any[]): number;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare var console: Console;\ndeclare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onwheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var indexedDB: IDBFactory;\ndeclare function atob(encodedString: string): string;\ndeclare function btoa(rawString: string): string;\ndeclare function fetch(input?: Request | string, init?: RequestInit): Promise;\ndeclare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\ndeclare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\ndeclare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\ndeclare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\ntype ScrollBehavior = \"auto\" | \"instant\" | \"smooth\";\ntype ScrollLogicalPosition = \"start\" | \"center\" | \"end\" | \"nearest\";\ntype MouseWheelEvent = WheelEvent;\ntype ScrollRestoration = \"auto\" | \"manual\";\ntype FormDataEntryValue = string | File;\ntype InsertPosition = \"beforebegin\" | \"afterbegin\" | \"beforeend\" | \"afterend\";\ntype HeadersInit = Headers | string[][] | { [key: string]: string };\ntype OrientationLockType = \"any\" | \"natural\" | \"portrait\" | \"landscape\" | \"portrait-primary\" | \"portrait-secondary\" | \"landscape-primary\"| \"landscape-secondary\";\ntype IDBValidKey = number | string | Date | IDBArrayKey;\ntype AlgorithmIdentifier = string | Algorithm;\ntype MutationRecordType = \"attributes\" | \"characterData\" | \"childList\";\ntype AAGUID = string;\ntype BodyInit = any;\ntype ByteString = string;\ntype ConstrainBoolean = boolean | ConstrainBooleanParameters;\ntype ConstrainDOMString = string | string[] | ConstrainDOMStringParameters;\ntype ConstrainDouble = number | ConstrainDoubleRange;\ntype ConstrainLong = number | ConstrainLongRange;\ntype CryptoOperationData = ArrayBufferView;\ntype GLbitfield = number;\ntype GLboolean = boolean;\ntype GLbyte = number;\ntype GLclampf = number;\ntype GLenum = number;\ntype GLfloat = number;\ntype GLint = number;\ntype GLintptr = number;\ntype GLshort = number;\ntype GLsizei = number;\ntype GLsizeiptr = number;\ntype GLubyte = number;\ntype GLuint = number;\ntype GLushort = number;\ntype IDBKeyPath = string;\ntype MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload;\ntype MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent;\ntype MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload;\ntype RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete;\ntype RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport;\ntype RequestInfo = Request | string;\ntype USVString = string;\ntype payloadtype = number;\ntype BufferSource = ArrayBuffer | ArrayBufferView;\ntype ClientTypes = \"window\" | \"worker\" | \"sharedworker\" | \"all\";\ntype AppendMode = \"segments\" | \"sequence\";\ntype AudioContextLatencyCategory = \"balanced\" | \"interactive\" | \"playback\";\ntype AudioContextState = \"suspended\" | \"running\" | \"closed\";\ntype BinaryType = \"blob\" | \"arraybuffer\";\ntype BiquadFilterType = \"lowpass\" | \"highpass\" | \"bandpass\" | \"lowshelf\" | \"highshelf\" | \"peaking\" | \"notch\" | \"allpass\";\ntype CanPlayTypeResult = \"\" | \"maybe\" | \"probably\";\ntype CanvasFillRule = \"nonzero\" | \"evenodd\";\ntype ChannelCountMode = \"max\" | \"clamped-max\" | \"explicit\";\ntype ChannelInterpretation = \"speakers\" | \"discrete\";\ntype DisplayCaptureSurfaceType = \"monitor\" | \"window\" | \"application\" | \"browser\";\ntype DistanceModelType = \"linear\" | \"inverse\" | \"exponential\";\ntype EndOfStreamError = \"network\" | \"decode\";\ntype ExpandGranularity = \"character\" | \"word\" | \"sentence\" | \"textedit\";\ntype GamepadHand = \"\" | \"left\" | \"right\";\ntype GamepadHapticActuatorType = \"vibration\";\ntype GamepadInputEmulationType = \"mouse\" | \"keyboard\" | \"gamepad\";\ntype GamepadMappingType = \"\" | \"standard\";\ntype IDBCursorDirection = \"next\" | \"nextunique\" | \"prev\" | \"prevunique\";\ntype IDBRequestReadyState = \"pending\" | \"done\";\ntype IDBTransactionMode = \"readonly\" | \"readwrite\" | \"versionchange\";\ntype KeyFormat = \"raw\" | \"spki\" | \"pkcs8\" | \"jwk\";\ntype KeyType = \"public\" | \"private\" | \"secret\";\ntype KeyUsage = \"encrypt\" | \"decrypt\" | \"sign\" | \"verify\" | \"deriveKey\" | \"deriveBits\" | \"wrapKey\" | \"unwrapKey\";\ntype ListeningState = \"inactive\" | \"active\" | \"disambiguation\";\ntype MSCredentialType = \"FIDO_2_0\";\ntype MSIceAddrType = \"os\" | \"stun\" | \"turn\" | \"peer-derived\";\ntype MSIceType = \"failed\" | \"direct\" | \"relay\";\ntype MSStatsType = \"description\" | \"localclientevent\" | \"inbound-network\" | \"outbound-network\" | \"inbound-payload\" | \"outbound-payload\" | \"transportdiagnostics\";\ntype MSTransportType = \"Embedded\" | \"USB\" | \"NFC\" | \"BT\";\ntype MSWebViewPermissionState = \"unknown\" | \"defer\" | \"allow\" | \"deny\";\ntype MSWebViewPermissionType = \"geolocation\" | \"unlimitedIndexedDBQuota\" | \"media\" | \"pointerlock\" | \"webnotifications\";\ntype MediaDeviceKind = \"audioinput\" | \"audiooutput\" | \"videoinput\";\ntype MediaKeyMessageType = \"license-request\" | \"license-renewal\" | \"license-release\" | \"individualization-request\";\ntype MediaKeySessionType = \"temporary\" | \"persistent-license\" | \"persistent-release-message\";\ntype MediaKeyStatus = \"usable\" | \"expired\" | \"output-downscaled\" | \"output-not-allowed\" | \"status-pending\" | \"internal-error\";\ntype MediaKeysRequirement = \"required\" | \"optional\" | \"not-allowed\";\ntype MediaStreamTrackState = \"live\" | \"ended\";\ntype NavigationReason = \"up\" | \"down\" | \"left\" | \"right\";\ntype NavigationType = \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\";\ntype NotificationDirection = \"auto\" | \"ltr\" | \"rtl\";\ntype NotificationPermission = \"default\" | \"denied\" | \"granted\";\ntype OscillatorType = \"sine\" | \"square\" | \"sawtooth\" | \"triangle\" | \"custom\";\ntype OverSampleType = \"none\" | \"2x\" | \"4x\";\ntype PanningModelType = \"equalpower\" | \"HRTF\";\ntype PaymentComplete = \"success\" | \"fail\" | \"unknown\";\ntype PaymentShippingType = \"shipping\" | \"delivery\" | \"pickup\";\ntype PushEncryptionKeyName = \"p256dh\" | \"auth\";\ntype PushPermissionState = \"granted\" | \"denied\" | \"prompt\";\ntype RTCBundlePolicy = \"balanced\" | \"max-compat\" | \"max-bundle\";\ntype RTCDegradationPreference = \"maintain-framerate\" | \"maintain-resolution\" | \"balanced\";\ntype RTCDtlsRole = \"auto\" | \"client\" | \"server\";\ntype RTCDtlsTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\";\ntype RTCIceCandidateType = \"host\" | \"srflx\" | \"prflx\" | \"relay\";\ntype RTCIceComponent = \"RTP\" | \"RTCP\";\ntype RTCIceConnectionState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"failed\" | \"disconnected\" | \"closed\";\ntype RTCIceGatherPolicy = \"all\" | \"nohost\" | \"relay\";\ntype RTCIceGathererState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceGatheringState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceProtocol = \"udp\" | \"tcp\";\ntype RTCIceRole = \"controlling\" | \"controlled\";\ntype RTCIceTcpCandidateType = \"active\" | \"passive\" | \"so\";\ntype RTCIceTransportPolicy = \"none\" | \"relay\" | \"all\";\ntype RTCIceTransportState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"closed\";\ntype RTCSdpType = \"offer\" | \"pranswer\" | \"answer\";\ntype RTCSignalingState = \"stable\" | \"have-local-offer\" | \"have-remote-offer\" | \"have-local-pranswer\" | \"have-remote-pranswer\" | \"closed\";\ntype RTCStatsIceCandidatePairState = \"frozen\" | \"waiting\" | \"inprogress\" | \"failed\" | \"succeeded\" | \"cancelled\";\ntype RTCStatsIceCandidateType = \"host\" | \"serverreflexive\" | \"peerreflexive\" | \"relayed\";\ntype RTCStatsType = \"inboundrtp\" | \"outboundrtp\" | \"session\" | \"datachannel\" | \"track\" | \"transport\" | \"candidatepair\" | \"localcandidate\" | \"remotecandidate\";\ntype ReadyState = \"closed\" | \"open\" | \"ended\";\ntype ReferrerPolicy = \"\" | \"no-referrer\" | \"no-referrer-when-downgrade\" | \"origin-only\" | \"origin-when-cross-origin\" | \"unsafe-url\";\ntype RequestCache = \"default\" | \"no-store\" | \"reload\" | \"no-cache\" | \"force-cache\";\ntype RequestCredentials = \"omit\" | \"same-origin\" | \"include\";\ntype RequestDestination = \"\" | \"document\" | \"sharedworker\" | \"subresource\" | \"unknown\" | \"worker\";\ntype RequestMode = \"navigate\" | \"same-origin\" | \"no-cors\" | \"cors\";\ntype RequestRedirect = \"follow\" | \"error\" | \"manual\";\ntype RequestType = \"\" | \"audio\" | \"font\" | \"image\" | \"script\" | \"style\" | \"track\" | \"video\";\ntype ResponseType = \"basic\" | \"cors\" | \"default\" | \"error\" | \"opaque\" | \"opaqueredirect\";\ntype ScopedCredentialType = \"ScopedCred\";\ntype ServiceWorkerState = \"installing\" | \"installed\" | \"activating\" | \"activated\" | \"redundant\";\ntype TextTrackKind = \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\ntype TextTrackMode = \"disabled\" | \"hidden\" | \"showing\";\ntype Transport = \"usb\" | \"nfc\" | \"ble\";\ntype VRDisplayEventReason = \"mounted\" | \"navigation\" | \"requested\" | \"unmounted\";\ntype VREye = \"left\" | \"right\";\ntype VideoFacingModeEnum = \"user\" | \"environment\" | \"left\" | \"right\";\ntype VisibilityState = \"hidden\" | \"visible\" | \"prerender\" | \"unloaded\";\ntype XMLHttpRequestResponseType = \"\" | \"arraybuffer\" | \"blob\" | \"document\" | \"json\" | \"text\";\n\n\n/////////////////////////////\n/// WorkerGlobalScope APIs\n/////////////////////////////\n// These are only available in a Web Worker\ndeclare function importScripts(...urls: string[]): void;\n\n\n\n\n/////////////////////////////\n/// Windows Script Host APIS\n/////////////////////////////\n\n\ninterface ActiveXObject {\n new (s: string): any;\n}\ndeclare var ActiveXObject: ActiveXObject;\n\ninterface ITextWriter {\n Write(s: string): void;\n WriteLine(s: string): void;\n Close(): void;\n}\n\ninterface TextStreamBase {\n /**\n * The column number of the current character position in an input stream.\n */\n Column: number;\n\n /**\n * The current line number in an input stream.\n */\n Line: number;\n\n /**\n * Closes a text stream.\n * It is not necessary to close standard streams; they close automatically when the process ends. If\n * you close a standard stream, be aware that any other pointers to that standard stream become invalid.\n */\n Close(): void;\n}\n\ninterface TextStreamWriter extends TextStreamBase {\n /**\n * Sends a string to an output stream.\n */\n Write(s: string): void;\n\n /**\n * Sends a specified number of blank lines (newline characters) to an output stream.\n */\n WriteBlankLines(intLines: number): void;\n\n /**\n * Sends a string followed by a newline character to an output stream.\n */\n WriteLine(s: string): void;\n}\n\ninterface TextStreamReader extends TextStreamBase {\n /**\n * Returns a specified number of characters from an input stream, starting at the current pointer position.\n * Does not return until the ENTER key is pressed.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n Read(characters: number): string;\n\n /**\n * Returns all characters from an input stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadAll(): string;\n\n /**\n * Returns an entire line from an input stream.\n * Although this method extracts the newline character, it does not add it to the returned string.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadLine(): string;\n\n /**\n * Skips a specified number of characters when reading from an input text stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)\n */\n Skip(characters: number): void;\n\n /**\n * Skips the next line when reading from an input text stream.\n * Can only be used on a stream in reading mode, not writing or appending mode.\n */\n SkipLine(): void;\n\n /**\n * Indicates whether the stream pointer position is at the end of a line.\n */\n AtEndOfLine: boolean;\n\n /**\n * Indicates whether the stream pointer position is at the end of a stream.\n */\n AtEndOfStream: boolean;\n}\n\ndeclare var WScript: {\n /**\n * Outputs text to either a message box (under WScript.exe) or the command console window followed by\n * a newline (under CScript.exe).\n */\n Echo(s: any): void;\n\n /**\n * Exposes the write-only error output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdErr: TextStreamWriter;\n\n /**\n * Exposes the write-only output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdOut: TextStreamWriter;\n Arguments: { length: number; Item(n: number): string; };\n\n /**\n * The full path of the currently running script.\n */\n ScriptFullName: string;\n\n /**\n * Forces the script to stop immediately, with an optional exit code.\n */\n Quit(exitCode?: number): number;\n\n /**\n * The Windows Script Host build version number.\n */\n BuildVersion: number;\n\n /**\n * Fully qualified path of the host executable.\n */\n FullName: string;\n\n /**\n * Gets/sets the script mode - interactive(true) or batch(false).\n */\n Interactive: boolean;\n\n /**\n * The name of the host executable (WScript.exe or CScript.exe).\n */\n Name: string;\n\n /**\n * Path of the directory containing the host executable.\n */\n Path: string;\n\n /**\n * The filename of the currently running script.\n */\n ScriptName: string;\n\n /**\n * Exposes the read-only input stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdIn: TextStreamReader;\n\n /**\n * Windows Script Host version\n */\n Version: string;\n\n /**\n * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.\n */\n ConnectObject(objEventSource: any, strPrefix: string): void;\n\n /**\n * Creates a COM object.\n * @param strProgiID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n CreateObject(strProgID: string, strPrefix?: string): any;\n\n /**\n * Disconnects a COM object from its event sources.\n */\n DisconnectObject(obj: any): void;\n\n /**\n * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.\n * @param strPathname Fully qualified path to the file containing the object persisted to disk.\n * For objects in memory, pass a zero-length string.\n * @param strProgID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;\n\n /**\n * Suspends script execution for a specified length of time, then continues execution.\n * @param intTime Interval (in milliseconds) to suspend script execution.\n */\n Sleep(intTime: number): void;\n};\n\n/**\n * Represents an Automation SAFEARRAY\n */\ndeclare class SafeArray {\n private constructor();\n private SafeArray_typekey: SafeArray;\n}\n\n/**\n * Allows enumerating over a COM collection, which may not have indexed item access.\n */\ninterface Enumerator {\n /**\n * Returns true if the current item is the last one in the collection, or the collection is empty,\n * or the current item is undefined.\n */\n atEnd(): boolean;\n\n /**\n * Returns the current item in the collection\n */\n item(): T;\n\n /**\n * Resets the current item in the collection to the first item. If there are no items in the collection,\n * the current item is set to undefined.\n */\n moveFirst(): void;\n\n /**\n * Moves the current item to the next item in the collection. If the enumerator is at the end of\n * the collection or the collection is empty, the current item is set to undefined.\n */\n moveNext(): void;\n}\n\ninterface EnumeratorConstructor {\n new (safearray: SafeArray): Enumerator;\n new (collection: { Item(index: any): T }): Enumerator;\n new (collection: any): Enumerator;\n}\n\ndeclare var Enumerator: EnumeratorConstructor;\n\n/**\n * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.\n */\ninterface VBArray {\n /**\n * Returns the number of dimensions (1-based).\n */\n dimensions(): number;\n\n /**\n * Takes an index for each dimension in the array, and returns the item at the corresponding location.\n */\n getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;\n\n /**\n * Returns the smallest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n lbound(dimension?: number): number;\n\n /**\n * Returns the largest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n ubound(dimension?: number): number;\n\n /**\n * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,\n * each successive dimension is appended to the end of the array.\n * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]\n */\n toArray(): T[];\n}\n\ninterface VBArrayConstructor {\n new (safeArray: SafeArray): VBArray;\n}\n\ndeclare var VBArray: VBArrayConstructor;\n\n/**\n * Automation date (VT_DATE)\n */\ndeclare class VarDate {\n private constructor();\n private VarDate_typekey: VarDate;\n}\n\ninterface DateConstructor {\n new (vd: VarDate): Date;\n}\n\ninterface Date {\n getVarDate: () => VarDate;\n}\n\n\n/// \n\ninterface DOMTokenList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Headers {\n [Symbol.iterator](): IterableIterator<[string, string]>;\n /**\n * Returns an iterator allowing to go through all key/value pairs contained in this object.\n */\n entries(): IterableIterator<[string, string]>;\n /**\n * Returns an iterator allowing to go through all keys f the key/value pairs contained in this object.\n */\n keys(): IterableIterator;\n /**\n * Returns an iterator allowing to go through all values of the key/value pairs contained in this object.\n */\n values(): IterableIterator;\n}\n\ninterface NodeList {\n /**\n * Returns an array of key, value pairs for every entry in the list\n */\n entries(): IterableIterator<[number, Node]>;\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void;\n /**\n * Returns an list of keys in the list\n */\n keys(): IterableIterator;\n\n /**\n * Returns an list of values in the list\n */\n values(): IterableIterator;\n\n\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface NodeListOf {\n\n /**\n * Returns an array of key, value pairs for every entry in the list\n */\n entries(): IterableIterator<[number, TNode]>;\n\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: TNode, index: number, listObj: NodeListOf) => void, thisArg?: any): void;\n /**\n * Returns an list of keys in the list\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the list\n */\n values(): IterableIterator;\n\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface HTMLCollectionBase {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface HTMLCollectionOf {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface FormData {\n /**\n * Returns an array of key, value pairs for every entry in the list\n */\n entries(): IterableIterator<[string, string | File]>;\n /**\n * Returns a list of keys in the list\n */\n keys(): IterableIterator;\n /**\n * Returns a list of values in the list\n */\n values(): IterableIterator;\n\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface URLSearchParams {\n /**\n * Returns an array of key, value pairs for every entry in the search params\n */\n entries(): IterableIterator<[string, string]>;\n /**\n * Returns a list of keys in the search params\n */\n keys(): IterableIterator;\n /**\n * Returns a list of values in the search params\n */\n values(): IterableIterator;\n /**\n * iterate over key/value pairs\n */\n [Symbol.iterator](): IterableIterator<[string, string]>;\n}\n"; +export const contents = "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// ECMAScript APIs\n/////////////////////////////\n\ndeclare const NaN: number;\ndeclare const Infinity: number;\n\n/**\n * Evaluates JavaScript code and executes it.\n * @param x A String value that contains valid JavaScript code.\n */\ndeclare function eval(x: string): any;\n\n/**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\ndeclare function parseInt(s: string, radix?: number): number;\n\n/**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\ndeclare function parseFloat(string: string): number;\n\n/**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\n * @param number A numeric value.\n */\ndeclare function isNaN(number: number): boolean;\n\n/**\n * Determines whether a supplied number is finite.\n * @param number Any numeric value.\n */\ndeclare function isFinite(number: number): boolean;\n\n/**\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\n * @param encodedURI A value representing an encoded URI.\n */\ndeclare function decodeURI(encodedURI: string): string;\n\n/**\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\n * @param encodedURIComponent A value representing an encoded URI component.\n */\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\n\n/**\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\n * @param uri A value representing an encoded URI.\n */\ndeclare function encodeURI(uri: string): string;\n\n/**\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\n * @param uriComponent A value representing an encoded URI component.\n */\ndeclare function encodeURIComponent(uriComponent: string): string;\n\n/**\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\n * @param string A string value\n */\ndeclare function escape(string: string): string;\n\n/**\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\n * @param string A string value\n */\ndeclare function unescape(string: string): string;\n\ninterface Symbol {\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): symbol;\n}\n\ndeclare type PropertyKey = string | number | symbol;\n\ninterface PropertyDescriptor {\n configurable?: boolean;\n enumerable?: boolean;\n value?: any;\n writable?: boolean;\n get?(): any;\n set?(v: any): void;\n}\n\ninterface PropertyDescriptorMap {\n [s: string]: PropertyDescriptor;\n}\n\ninterface Object {\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\n constructor: Function;\n\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns a date converted to a string using the current locale. */\n toLocaleString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): Object;\n\n /**\n * Determines whether an object has a property with the specified name.\n * @param v A property name.\n */\n hasOwnProperty(v: PropertyKey): boolean;\n\n /**\n * Determines whether an object exists in another object's prototype chain.\n * @param v Another object whose prototype chain is to be checked.\n */\n isPrototypeOf(v: Object): boolean;\n\n /**\n * Determines whether a specified property is enumerable.\n * @param v A property name.\n */\n propertyIsEnumerable(v: PropertyKey): boolean;\n}\n\ninterface ObjectConstructor {\n new(value?: any): Object;\n (): any;\n (value: any): any;\n\n /** A reference to the prototype for a class of objects. */\n readonly prototype: Object;\n\n /**\n * Returns the prototype of an object.\n * @param o The object that references the prototype.\n */\n getPrototypeOf(o: any): any;\n\n /**\n * Gets the own property descriptor of the specified object.\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\n * @param o Object that contains the property.\n * @param p Name of the property.\n */\n getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined;\n\n /**\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\n * @param o Object that contains the own properties.\n */\n getOwnPropertyNames(o: any): string[];\n\n /**\n * Creates an object that has the specified prototype or that has null prototype.\n * @param o Object to use as a prototype. May be null.\n */\n create(o: object | null): any;\n\n /**\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\n * @param o Object to use as a prototype. May be null\n * @param properties JavaScript object that contains one or more property descriptors.\n */\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Adds a property to an object, or modifies attributes of an existing property.\n * @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.\n * @param p The property name.\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\n */\n defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType): any;\n\n /**\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\n */\n defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n seal(o: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(a: T[]): ReadonlyArray;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(f: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(o: T): Readonly;\n\n /**\n * Prevents the addition of new properties to an object.\n * @param o Object to make non-extensible.\n */\n preventExtensions(o: T): T;\n\n /**\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isSealed(o: any): boolean;\n\n /**\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isFrozen(o: any): boolean;\n\n /**\n * Returns a value that indicates whether new properties can be added to an object.\n * @param o Object to test.\n */\n isExtensible(o: any): boolean;\n\n /**\n * Returns the names of the enumerable properties and methods of an object.\n * @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.\n */\n keys(o: {}): string[];\n}\n\n/**\n * Provides functionality common to all JavaScript objects.\n */\ndeclare const Object: ObjectConstructor;\n\n/**\n * Creates a new function.\n */\ninterface Function {\n /**\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\n * @param thisArg The object to be used as the this object.\n * @param argArray A set of arguments to be passed to the function.\n */\n apply(this: Function, thisArg: any, argArray?: any): any;\n\n /**\n * Calls a method of an object, substituting another object for the current object.\n * @param thisArg The object to be used as the current object.\n * @param argArray A list of arguments to be passed to the method.\n */\n call(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /**\n * For a given function, creates a bound function that has the same body as the original function.\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\n * @param thisArg An object to which the this keyword can refer inside the new function.\n * @param argArray A list of arguments to be passed to the new function.\n */\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /** Returns a string representation of a function. */\n toString(): string;\n\n prototype: any;\n readonly length: number;\n\n // Non-standard extensions\n arguments: any;\n caller: Function;\n}\n\ninterface FunctionConstructor {\n /**\n * Creates a new function.\n * @param args A list of arguments the function accepts.\n */\n new(...args: string[]): Function;\n (...args: string[]): Function;\n readonly prototype: Function;\n}\n\ndeclare const Function: FunctionConstructor;\n\ninterface IArguments {\n [index: number]: any;\n length: number;\n callee: Function;\n}\n\ninterface String {\n /** Returns a string representation of a string. */\n toString(): string;\n\n /**\n * Returns the character at the specified index.\n * @param pos The zero-based index of the desired character.\n */\n charAt(pos: number): string;\n\n /**\n * Returns the Unicode value of the character at the specified location.\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\n */\n charCodeAt(index: number): number;\n\n /**\n * Returns a string that contains the concatenation of two or more strings.\n * @param strings The strings to append to the end of the string.\n */\n concat(...strings: string[]): string;\n\n /**\n * Returns the position of the first occurrence of a substring.\n * @param searchString The substring to search for in the string\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\n */\n indexOf(searchString: string, position?: number): number;\n\n /**\n * Returns the last occurrence of a substring in the string.\n * @param searchString The substring to search for.\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\n */\n lastIndexOf(searchString: string, position?: number): number;\n\n /**\n * Determines whether two strings are equivalent in the current locale.\n * @param that String to compare to target string\n */\n localeCompare(that: string): number;\n\n /**\n * Matches a string with a regular expression, and returns an array containing the results of that search.\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\n */\n match(regexp: string | RegExp): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: string | RegExp, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param regexp The regular expression pattern and applicable flags.\n */\n search(regexp: string | RegExp): number;\n\n /**\n * Returns a section of a string.\n * @param start The index to the beginning of the specified portion of stringObj.\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\n * If this value is not specified, the substring continues to the end of stringObj.\n */\n slice(start?: number, end?: number): string;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(separator: string | RegExp, limit?: number): string[];\n\n /**\n * Returns the substring at the specified location within a String object.\n * @param start The zero-based index number indicating the beginning of the substring.\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\n * If end is omitted, the characters from start through the end of the original string are returned.\n */\n substring(start: number, end?: number): string;\n\n /** Converts all the alphabetic characters in a string to lowercase. */\n toLowerCase(): string;\n\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\n toLocaleLowerCase(): string;\n\n /** Converts all the alphabetic characters in a string to uppercase. */\n toUpperCase(): string;\n\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\n toLocaleUpperCase(): string;\n\n /** Removes the leading and trailing white space and line terminator characters from a string. */\n trim(): string;\n\n /** Returns the length of a String object. */\n readonly length: number;\n\n // IE extensions\n /**\n * Gets a substring beginning at the specified location and having the specified length.\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\n * @param length The number of characters to include in the returned substring.\n */\n substr(from: number, length?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): string;\n\n readonly [index: number]: string;\n}\n\ninterface StringConstructor {\n new(value?: any): String;\n (value?: any): string;\n readonly prototype: String;\n fromCharCode(...codes: number[]): string;\n}\n\n/**\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\n */\ndeclare const String: StringConstructor;\n\ninterface Boolean {\n /** Returns the primitive value of the specified object. */\n valueOf(): boolean;\n}\n\ninterface BooleanConstructor {\n new(value?: any): Boolean;\n (value?: any): boolean;\n readonly prototype: Boolean;\n}\n\ndeclare const Boolean: BooleanConstructor;\n\ninterface Number {\n /**\n * Returns a string representation of an object.\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\n */\n toString(radix?: number): string;\n\n /**\n * Returns a string representing a number in fixed-point notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toFixed(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented in exponential notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toExponential(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\n */\n toPrecision(precision?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): number;\n}\n\ninterface NumberConstructor {\n new(value?: any): Number;\n (value?: any): number;\n readonly prototype: Number;\n\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\n readonly MAX_VALUE: number;\n\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\n readonly MIN_VALUE: number;\n\n /**\n * A value that is not a number.\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\n */\n readonly NaN: number;\n\n /**\n * A value that is less than the largest negative number that can be represented in JavaScript.\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\n */\n readonly NEGATIVE_INFINITY: number;\n\n /**\n * A value greater than the largest number that can be represented in JavaScript.\n * JavaScript displays POSITIVE_INFINITY values as infinity.\n */\n readonly POSITIVE_INFINITY: number;\n}\n\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\ndeclare const Number: NumberConstructor;\n\ninterface TemplateStringsArray extends ReadonlyArray {\n readonly raw: ReadonlyArray;\n}\n\n/**\n * The type of `import.meta`.\n * \n * If you need to declare that a given property exists on `import.meta`,\n * this type may be augmented via interface merging.\n */\ninterface ImportMeta {\n}\n\ninterface Math {\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\n readonly E: number;\n /** The natural logarithm of 10. */\n readonly LN10: number;\n /** The natural logarithm of 2. */\n readonly LN2: number;\n /** The base-2 logarithm of e. */\n readonly LOG2E: number;\n /** The base-10 logarithm of e. */\n readonly LOG10E: number;\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\n readonly PI: number;\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\n readonly SQRT1_2: number;\n /** The square root of 2. */\n readonly SQRT2: number;\n /**\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\n * For example, the absolute value of -5 is the same as the absolute value of 5.\n * @param x A numeric expression for which the absolute value is needed.\n */\n abs(x: number): number;\n /**\n * Returns the arc cosine (or inverse cosine) of a number.\n * @param x A numeric expression.\n */\n acos(x: number): number;\n /**\n * Returns the arcsine of a number.\n * @param x A numeric expression.\n */\n asin(x: number): number;\n /**\n * Returns the arctangent of a number.\n * @param x A numeric expression for which the arctangent is needed.\n */\n atan(x: number): number;\n /**\n * Returns the angle (in radians) from the X axis to a point.\n * @param y A numeric expression representing the cartesian y-coordinate.\n * @param x A numeric expression representing the cartesian x-coordinate.\n */\n atan2(y: number, x: number): number;\n /**\n * Returns the smallest integer greater than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n ceil(x: number): number;\n /**\n * Returns the cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cos(x: number): number;\n /**\n * Returns e (the base of natural logarithms) raised to a power.\n * @param x A numeric expression representing the power of e.\n */\n exp(x: number): number;\n /**\n * Returns the greatest integer less than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n floor(x: number): number;\n /**\n * Returns the natural logarithm (base e) of a number.\n * @param x A numeric expression.\n */\n log(x: number): number;\n /**\n * Returns the larger of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n max(...values: number[]): number;\n /**\n * Returns the smaller of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n min(...values: number[]): number;\n /**\n * Returns the value of a base expression taken to a specified power.\n * @param x The base value of the expression.\n * @param y The exponent value of the expression.\n */\n pow(x: number, y: number): number;\n /** Returns a pseudorandom number between 0 and 1. */\n random(): number;\n /**\n * Returns a supplied numeric expression rounded to the nearest number.\n * @param x The value to be rounded to the nearest number.\n */\n round(x: number): number;\n /**\n * Returns the sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sin(x: number): number;\n /**\n * Returns the square root of a number.\n * @param x A numeric expression.\n */\n sqrt(x: number): number;\n /**\n * Returns the tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tan(x: number): number;\n}\n/** An intrinsic object that provides basic mathematics functionality and constants. */\ndeclare const Math: Math;\n\n/** Enables basic storage and retrieval of dates and times. */\ninterface Date {\n /** Returns a string representation of a date. The format of the string depends on the locale. */\n toString(): string;\n /** Returns a date as a string value. */\n toDateString(): string;\n /** Returns a time as a string value. */\n toTimeString(): string;\n /** Returns a value as a string value appropriate to the host environment's current locale. */\n toLocaleString(): string;\n /** Returns a date as a string value appropriate to the host environment's current locale. */\n toLocaleDateString(): string;\n /** Returns a time as a string value appropriate to the host environment's current locale. */\n toLocaleTimeString(): string;\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\n valueOf(): number;\n /** Gets the time value in milliseconds. */\n getTime(): number;\n /** Gets the year, using local time. */\n getFullYear(): number;\n /** Gets the year using Universal Coordinated Time (UTC). */\n getUTCFullYear(): number;\n /** Gets the month, using local time. */\n getMonth(): number;\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\n getUTCMonth(): number;\n /** Gets the day-of-the-month, using local time. */\n getDate(): number;\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\n getUTCDate(): number;\n /** Gets the day of the week, using local time. */\n getDay(): number;\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\n getUTCDay(): number;\n /** Gets the hours in a date, using local time. */\n getHours(): number;\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\n getUTCHours(): number;\n /** Gets the minutes of a Date object, using local time. */\n getMinutes(): number;\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\n getUTCMinutes(): number;\n /** Gets the seconds of a Date object, using local time. */\n getSeconds(): number;\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCSeconds(): number;\n /** Gets the milliseconds of a Date, using local time. */\n getMilliseconds(): number;\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCMilliseconds(): number;\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\n getTimezoneOffset(): number;\n /**\n * Sets the date and time value in the Date object.\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\n */\n setTime(time: number): number;\n /**\n * Sets the milliseconds value in the Date object using local time.\n * @param ms A numeric value equal to the millisecond value.\n */\n setMilliseconds(ms: number): number;\n /**\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\n * @param ms A numeric value equal to the millisecond value.\n */\n setUTCMilliseconds(ms: number): number;\n\n /**\n * Sets the seconds value in the Date object using local time.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setSeconds(sec: number, ms?: number): number;\n /**\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCSeconds(sec: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using local time.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the hour value in the Date object using local time.\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the numeric day-of-the-month value of the Date object using local time.\n * @param date A numeric value equal to the day of the month.\n */\n setDate(date: number): number;\n /**\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\n * @param date A numeric value equal to the day of the month.\n */\n setUTCDate(date: number): number;\n /**\n * Sets the month value in the Date object using local time.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\n */\n setMonth(month: number, date?: number): number;\n /**\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\n */\n setUTCMonth(month: number, date?: number): number;\n /**\n * Sets the year of the Date object using local time.\n * @param year A numeric value for the year.\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\n * @param date A numeric value equal for the day of the month.\n */\n setFullYear(year: number, month?: number, date?: number): number;\n /**\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\n * @param year A numeric value equal to the year.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\n * @param date A numeric value equal to the day of the month.\n */\n setUTCFullYear(year: number, month?: number, date?: number): number;\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\n toUTCString(): string;\n /** Returns a date as a string value in ISO format. */\n toISOString(): string;\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\n toJSON(key?: any): string;\n}\n\ninterface DateConstructor {\n new(): Date;\n new(value: number | string): Date;\n new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;\n (): string;\n readonly prototype: Date;\n /**\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\n * @param s A date string\n */\n parse(s: string): number;\n /**\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\n * @param month The month as an number between 0 and 11 (January to December).\n * @param date The date as an number between 1 and 31.\n * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.\n * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.\n * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.\n * @param ms An number from 0 to 999 that specifies the milliseconds.\n */\n UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;\n now(): number;\n}\n\ndeclare const Date: DateConstructor;\n\ninterface RegExpMatchArray extends Array {\n index?: number;\n input?: string;\n}\n\ninterface RegExpExecArray extends Array {\n index: number;\n input: string;\n}\n\ninterface RegExp {\n /**\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\n * @param string The String object or string literal on which to perform the search.\n */\n exec(string: string): RegExpExecArray | null;\n\n /**\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\n * @param string String on which to perform the search.\n */\n test(string: string): boolean;\n\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\n readonly source: string;\n\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\n readonly global: boolean;\n\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\n readonly ignoreCase: boolean;\n\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\n readonly multiline: boolean;\n\n lastIndex: number;\n\n // Non-standard extensions\n compile(): this;\n}\n\ninterface RegExpConstructor {\n new(pattern: RegExp | string): RegExp;\n new(pattern: string, flags?: string): RegExp;\n (pattern: RegExp | string): RegExp;\n (pattern: string, flags?: string): RegExp;\n readonly prototype: RegExp;\n\n // Non-standard extensions\n $1: string;\n $2: string;\n $3: string;\n $4: string;\n $5: string;\n $6: string;\n $7: string;\n $8: string;\n $9: string;\n lastMatch: string;\n}\n\ndeclare const RegExp: RegExpConstructor;\n\ninterface Error {\n name: string;\n message: string;\n stack?: string;\n}\n\ninterface ErrorConstructor {\n new(message?: string): Error;\n (message?: string): Error;\n readonly prototype: Error;\n}\n\ndeclare const Error: ErrorConstructor;\n\ninterface EvalError extends Error {\n}\n\ninterface EvalErrorConstructor {\n new(message?: string): EvalError;\n (message?: string): EvalError;\n readonly prototype: EvalError;\n}\n\ndeclare const EvalError: EvalErrorConstructor;\n\ninterface RangeError extends Error {\n}\n\ninterface RangeErrorConstructor {\n new(message?: string): RangeError;\n (message?: string): RangeError;\n readonly prototype: RangeError;\n}\n\ndeclare const RangeError: RangeErrorConstructor;\n\ninterface ReferenceError extends Error {\n}\n\ninterface ReferenceErrorConstructor {\n new(message?: string): ReferenceError;\n (message?: string): ReferenceError;\n readonly prototype: ReferenceError;\n}\n\ndeclare const ReferenceError: ReferenceErrorConstructor;\n\ninterface SyntaxError extends Error {\n}\n\ninterface SyntaxErrorConstructor {\n new(message?: string): SyntaxError;\n (message?: string): SyntaxError;\n readonly prototype: SyntaxError;\n}\n\ndeclare const SyntaxError: SyntaxErrorConstructor;\n\ninterface TypeError extends Error {\n}\n\ninterface TypeErrorConstructor {\n new(message?: string): TypeError;\n (message?: string): TypeError;\n readonly prototype: TypeError;\n}\n\ndeclare const TypeError: TypeErrorConstructor;\n\ninterface URIError extends Error {\n}\n\ninterface URIErrorConstructor {\n new(message?: string): URIError;\n (message?: string): URIError;\n readonly prototype: URIError;\n}\n\ndeclare const URIError: URIErrorConstructor;\n\ninterface JSON {\n /**\n * Converts a JavaScript Object Notation (JSON) string into an object.\n * @param text A valid JSON string.\n * @param reviver A function that transforms the results. This function is called for each member of the object.\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\n */\n parse(text: string, reviver?: (key: any, value: any) => any): any;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer A function that transforms the results.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\n}\n\n/**\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\n */\ndeclare const JSON: JSON;\n\n\n/////////////////////////////\n/// ECMAScript Array API (specially handled by compiler)\n/////////////////////////////\n\ninterface ReadonlyArray {\n /**\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n readonly length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n\n readonly [n: number]: T;\n}\n\ninterface ConcatArray {\n readonly length: number;\n readonly [n: number]: T;\n join(separator?: string): string;\n slice(start?: number, end?: number): T[];\n}\n\ninterface Array {\n /**\n * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Removes the last element from an array and returns it.\n */\n pop(): T | undefined;\n /**\n * Appends new elements to an array, and returns the new length of the array.\n * @param items New elements of the Array.\n */\n push(...items: T[]): number;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Reverses the elements in an Array.\n */\n reverse(): T[];\n /**\n * Removes the first element from an array and returns it.\n */\n shift(): T | undefined;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: T, b: T) => number): this;\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n */\n splice(start: number, deleteCount?: number): T[];\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the array in place of the deleted elements.\n */\n splice(start: number, deleteCount: number, ...items: T[]): T[];\n /**\n * Inserts new elements at the start of an array.\n * @param items Elements to insert at the start of the Array.\n */\n unshift(...items: T[]): number;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n\n [n: number]: T;\n}\n\ninterface ArrayConstructor {\n new(arrayLength?: number): any[];\n new (arrayLength: number): T[];\n new (...items: T[]): T[];\n (arrayLength?: number): any[];\n (arrayLength: number): T[];\n (...items: T[]): T[];\n isArray(arg: any): arg is Array;\n readonly prototype: Array;\n}\n\ndeclare const Array: ArrayConstructor;\n\ninterface TypedPropertyDescriptor {\n enumerable?: boolean;\n configurable?: boolean;\n writable?: boolean;\n value?: T;\n get?: () => T;\n set?: (value: T) => void;\n}\n\ndeclare type ClassDecorator = (target: TFunction) => TFunction | void;\ndeclare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;\ndeclare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;\ndeclare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;\n\ndeclare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike;\n\ninterface PromiseLike {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike;\n}\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface Promise {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise;\n\n /**\n * Attaches a callback for only the rejection of the Promise.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of the callback.\n */\n catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise;\n}\n\ninterface ArrayLike {\n readonly length: number;\n readonly [n: number]: T;\n}\n\n/**\n * Make all properties in T optional\n */\ntype Partial = {\n [P in keyof T]?: T[P];\n};\n\n/**\n * Make all properties in T required\n */\ntype Required = {\n [P in keyof T]-?: T[P];\n};\n\n/**\n * Make all properties in T readonly\n */\ntype Readonly = {\n readonly [P in keyof T]: T[P];\n};\n\n/**\n * From T pick a set of properties K\n */\ntype Pick = {\n [P in K]: T[P];\n};\n\n/**\n * Construct a type with a set of properties K of type T\n */\ntype Record = {\n [P in K]: T;\n};\n\n/**\n * Exclude from T those types that are assignable to U\n */\ntype Exclude = T extends U ? never : T;\n\n/**\n * Extract from T those types that are assignable to U\n */\ntype Extract = T extends U ? T : never;\n\n/**\n * Exclude null and undefined from T\n */\ntype NonNullable = T extends null | undefined ? never : T;\n\n/**\n * Obtain the return type of a function type\n */\ntype ReturnType any> = T extends (...args: any[]) => infer R ? R : any;\n\n/**\n * Obtain the return type of a constructor function type\n */\ntype InstanceType any> = T extends new (...args: any[]) => infer R ? R : any;\n\n/**\n * Marker for contextual 'this' type\n */\ninterface ThisType { }\n\n/**\n * Represents a raw buffer of binary data, which is used to store data for the\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\n * but can be passed to a typed array or DataView Object to interpret the raw\n * buffer as needed.\n */\ninterface ArrayBuffer {\n /**\n * Read-only. The length of the ArrayBuffer (in bytes).\n */\n readonly byteLength: number;\n\n /**\n * Returns a section of an ArrayBuffer.\n */\n slice(begin: number, end?: number): ArrayBuffer;\n}\n\n/**\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\n */\ninterface ArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\n\ninterface ArrayBufferConstructor {\n readonly prototype: ArrayBuffer;\n new(byteLength: number): ArrayBuffer;\n isView(arg: any): arg is ArrayBufferView;\n}\ndeclare const ArrayBuffer: ArrayBufferConstructor;\n\ninterface ArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\ninterface DataView {\n readonly buffer: ArrayBuffer;\n readonly byteLength: number;\n readonly byteOffset: number;\n /**\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt8(byteOffset: number): number;\n\n /**\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt16(byteOffset: number, littleEndian?: boolean): number;\n /**\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint8(byteOffset: number): number;\n\n /**\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint16(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Stores an Float32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Float64 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setInt8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Int16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setUint8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Uint16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\n}\n\ninterface DataViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;\n}\ndeclare const DataView: DataViewConstructor;\n\n/**\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Int8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\ninterface Int8ArrayConstructor {\n readonly prototype: Int8Array;\n new(length: number): Int8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n\n\n}\ndeclare const Int8Array: Int8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ArrayConstructor {\n readonly prototype: Uint8Array;\n new(length: number): Uint8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n\n}\ndeclare const Uint8Array: Uint8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\n * If the requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8ClampedArray {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8ClampedArray;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8ClampedArray;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8ClampedArray;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ClampedArrayConstructor {\n readonly prototype: Uint8ClampedArray;\n new(length: number): Uint8ClampedArray;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8ClampedArray;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\ndeclare const Uint8ClampedArray: Uint8ClampedArrayConstructor;\n\n/**\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int16ArrayConstructor {\n readonly prototype: Int16Array;\n new(length: number): Int16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n\n\n}\ndeclare const Int16Array: Int16ArrayConstructor;\n\n/**\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint16ArrayConstructor {\n readonly prototype: Uint16Array;\n new(length: number): Uint16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n\n\n}\ndeclare const Uint16Array: Uint16ArrayConstructor;\n/**\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int32ArrayConstructor {\n readonly prototype: Int32Array;\n new(length: number): Int32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n\n}\ndeclare const Int32Array: Int32ArrayConstructor;\n\n/**\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint32ArrayConstructor {\n readonly prototype: Uint32Array;\n new(length: number): Uint32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n\n}\ndeclare const Uint32Array: Uint32ArrayConstructor;\n\n/**\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\n * of bytes could not be allocated an exception is raised.\n */\ninterface Float32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float32ArrayConstructor {\n readonly prototype: Float32Array;\n new(length: number): Float32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n\n\n}\ndeclare const Float32Array: Float32ArrayConstructor;\n\n/**\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Float64Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float64Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float64Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float64Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float64ArrayConstructor {\n readonly prototype: Float64Array;\n new(length: number): Float64Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n\n}\ndeclare const Float64Array: Float64ArrayConstructor;\n\n/////////////////////////////\n/// ECMAScript Internationalization API\n/////////////////////////////\n\ndeclare namespace Intl {\n interface CollatorOptions {\n usage?: string;\n localeMatcher?: string;\n numeric?: boolean;\n caseFirst?: string;\n sensitivity?: string;\n ignorePunctuation?: boolean;\n }\n\n interface ResolvedCollatorOptions {\n locale: string;\n usage: string;\n sensitivity: string;\n ignorePunctuation: boolean;\n collation: string;\n caseFirst: string;\n numeric: boolean;\n }\n\n interface Collator {\n compare(x: string, y: string): number;\n resolvedOptions(): ResolvedCollatorOptions;\n }\n var Collator: {\n new(locales?: string | string[], options?: CollatorOptions): Collator;\n (locales?: string | string[], options?: CollatorOptions): Collator;\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\n };\n\n interface NumberFormatOptions {\n localeMatcher?: string;\n style?: string;\n currency?: string;\n currencyDisplay?: string;\n useGrouping?: boolean;\n minimumIntegerDigits?: number;\n minimumFractionDigits?: number;\n maximumFractionDigits?: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n }\n\n interface ResolvedNumberFormatOptions {\n locale: string;\n numberingSystem: string;\n style: string;\n currency?: string;\n currencyDisplay?: string;\n minimumIntegerDigits: number;\n minimumFractionDigits: number;\n maximumFractionDigits: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n useGrouping: boolean;\n }\n\n interface NumberFormat {\n format(value: number): string;\n resolvedOptions(): ResolvedNumberFormatOptions;\n }\n var NumberFormat: {\n new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\n };\n\n interface DateTimeFormatOptions {\n localeMatcher?: string;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n formatMatcher?: string;\n hour12?: boolean;\n timeZone?: string;\n }\n\n interface ResolvedDateTimeFormatOptions {\n locale: string;\n calendar: string;\n numberingSystem: string;\n timeZone: string;\n hour12?: boolean;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n }\n\n interface DateTimeFormat {\n format(date?: Date | number): string;\n resolvedOptions(): ResolvedDateTimeFormatOptions;\n }\n var DateTimeFormat: {\n new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\n };\n}\n\ninterface String {\n /**\n * Determines whether two strings are equivalent in the current or specified locale.\n * @param that String to compare to target string\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\n */\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\n}\n\ninterface Number {\n /**\n * Converts a number to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\n}\n\ninterface Date {\n /**\n * Converts a date and time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n /**\n * Converts a date to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n\n /**\n * Converts a time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface Array {\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;\n find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): number;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: T, start?: number, end?: number): this;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n}\n\ninterface ArrayConstructor {\n /**\n * Creates an array from an array-like object.\n * @param arrayLike An array-like object to convert to an array.\n */\n from(arrayLike: ArrayLike): T[];\n\n /**\n * Creates an array from an iterable object.\n * @param arrayLike An array-like object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[];\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: T[]): T[];\n}\n\ninterface DateConstructor {\n new (value: number | string | Date): Date;\n}\n\ninterface Function {\n /**\n * Returns the name of the function. Function names are read-only and can not be changed.\n */\n readonly name: string;\n}\n\ninterface Math {\n /**\n * Returns the number of leading zero bits in the 32-bit binary representation of a number.\n * @param x A numeric expression.\n */\n clz32(x: number): number;\n\n /**\n * Returns the result of 32-bit multiplication of two numbers.\n * @param x First number\n * @param y Second number\n */\n imul(x: number, y: number): number;\n\n /**\n * Returns the sign of the x, indicating whether x is positive, negative or zero.\n * @param x The numeric expression to test\n */\n sign(x: number): number;\n\n /**\n * Returns the base 10 logarithm of a number.\n * @param x A numeric expression.\n */\n log10(x: number): number;\n\n /**\n * Returns the base 2 logarithm of a number.\n * @param x A numeric expression.\n */\n log2(x: number): number;\n\n /**\n * Returns the natural logarithm of 1 + x.\n * @param x A numeric expression.\n */\n log1p(x: number): number;\n\n /**\n * Returns the result of (e^x - 1), which is an implementation-dependent approximation to\n * subtracting 1 from the exponential function of x (e raised to the power of x, where e\n * is the base of the natural logarithms).\n * @param x A numeric expression.\n */\n expm1(x: number): number;\n\n /**\n * Returns the hyperbolic cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cosh(x: number): number;\n\n /**\n * Returns the hyperbolic sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sinh(x: number): number;\n\n /**\n * Returns the hyperbolic tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tanh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n acosh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n asinh(x: number): number;\n\n /**\n * Returns the inverse hyperbolic tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n atanh(x: number): number;\n\n /**\n * Returns the square root of the sum of squares of its arguments.\n * @param values Values to compute the square root for.\n * If no arguments are passed, the result is +0.\n * If there is only one argument, the result is the absolute value.\n * If any argument is +Infinity or -Infinity, the result is +Infinity.\n * If any argument is NaN, the result is NaN.\n * If all arguments are either +0 or −0, the result is +0.\n */\n hypot(...values: number[]): number;\n\n /**\n * Returns the integral part of the a numeric expression, x, removing any fractional digits.\n * If x is already an integer, the result is x.\n * @param x A numeric expression.\n */\n trunc(x: number): number;\n\n /**\n * Returns the nearest single precision float representation of a number.\n * @param x A numeric expression.\n */\n fround(x: number): number;\n\n /**\n * Returns an implementation-dependent approximation to the cube root of number.\n * @param x A numeric expression.\n */\n cbrt(x: number): number;\n}\n\ninterface NumberConstructor {\n /**\n * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1\n * that is representable as a Number value, which is approximately:\n * 2.2204460492503130808472633361816 x 10‍−‍16.\n */\n readonly EPSILON: number;\n\n /**\n * Returns true if passed value is finite.\n * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a\n * number. Only finite values of the type number, result in true.\n * @param number A numeric value.\n */\n isFinite(number: number): boolean;\n\n /**\n * Returns true if the value passed is an integer, false otherwise.\n * @param number A numeric value.\n */\n isInteger(number: number): boolean;\n\n /**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a\n * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter\n * to a number. Only values of the type number, that are also NaN, result in true.\n * @param number A numeric value.\n */\n isNaN(number: number): boolean;\n\n /**\n * Returns true if the value passed is a safe integer.\n * @param number A numeric value.\n */\n isSafeInteger(number: number): boolean;\n\n /**\n * The value of the largest integer n such that n and n + 1 are both exactly representable as\n * a Number value.\n * The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.\n */\n readonly MAX_SAFE_INTEGER: number;\n\n /**\n * The value of the smallest integer n such that n and n − 1 are both exactly representable as\n * a Number value.\n * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).\n */\n readonly MIN_SAFE_INTEGER: number;\n\n /**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\n parseFloat(string: string): number;\n\n /**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\n parseInt(string: string, radix?: number): number;\n}\n\ninterface ObjectConstructor {\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source The source object from which to copy properties.\n */\n assign(target: T, source: U): T & U;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source1 The first source object from which to copy properties.\n * @param source2 The second source object from which to copy properties.\n */\n assign(target: T, source1: U, source2: V): T & U & V;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param source1 The first source object from which to copy properties.\n * @param source2 The second source object from which to copy properties.\n * @param source3 The third source object from which to copy properties.\n */\n assign(target: T, source1: U, source2: V, source3: W): T & U & V & W;\n\n /**\n * Copy the values of all of the enumerable own properties from one or more source objects to a\n * target object. Returns the target object.\n * @param target The target object to copy to.\n * @param sources One or more source objects from which to copy properties\n */\n assign(target: object, ...sources: any[]): any;\n\n /**\n * Returns an array of all symbol properties found directly on object o.\n * @param o Object to retrieve the symbols from.\n */\n getOwnPropertySymbols(o: any): symbol[];\n\n /**\n * Returns true if the values are the same value, false otherwise.\n * @param value1 The first value.\n * @param value2 The second value.\n */\n is(value1: any, value2: any): boolean;\n\n /**\n * Sets the prototype of a specified object o to object proto or null. Returns the object o.\n * @param o The object to change its prototype.\n * @param proto The value of the new prototype or null.\n */\n setPrototypeOf(o: any, proto: object | null): any;\n}\n\ninterface ReadonlyArray {\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray) => value is S, thisArg?: any): S | undefined;\n find(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): T | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: T, index: number, obj: ReadonlyArray) => boolean, thisArg?: any): number;\n}\n\ninterface RegExp {\n /**\n * Returns a string indicating the flags of the regular expression in question. This field is read-only.\n * The characters in this string are sequenced and concatenated in the following order:\n *\n * - \"g\" for global\n * - \"i\" for ignoreCase\n * - \"m\" for multiline\n * - \"u\" for unicode\n * - \"y\" for sticky\n *\n * If no flags are set, the value is the empty string.\n */\n readonly flags: string;\n\n /**\n * Returns a Boolean value indicating the state of the sticky flag (y) used with a regular\n * expression. Default is false. Read-only.\n */\n readonly sticky: boolean;\n\n /**\n * Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular\n * expression. Default is false. Read-only.\n */\n readonly unicode: boolean;\n}\n\ninterface RegExpConstructor {\n new (pattern: RegExp, flags?: string): RegExp;\n (pattern: RegExp, flags?: string): RegExp;\n}\n\ninterface String {\n /**\n * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point\n * value of the UTF-16 encoded code point starting at the string element at position pos in\n * the String resulting from converting this object to a String.\n * If there is no element at that position, the result is undefined.\n * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.\n */\n codePointAt(pos: number): number | undefined;\n\n /**\n * Returns true if searchString appears as a substring of the result of converting this\n * object to a String, at one or more positions that are\n * greater than or equal to position; otherwise, returns false.\n * @param searchString search string\n * @param position If position is undefined, 0 is assumed, so as to search all of the String.\n */\n includes(searchString: string, position?: number): boolean;\n\n /**\n * Returns true if the sequence of elements of searchString converted to a String is the\n * same as the corresponding elements of this object (converted to a String) starting at\n * endPosition – length(this). Otherwise returns false.\n */\n endsWith(searchString: string, endPosition?: number): boolean;\n\n /**\n * Returns the String value result of normalizing the string into the normalization form\n * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.\n * @param form Applicable values: \"NFC\", \"NFD\", \"NFKC\", or \"NFKD\", If not specified default\n * is \"NFC\"\n */\n normalize(form: \"NFC\" | \"NFD\" | \"NFKC\" | \"NFKD\"): string;\n\n /**\n * Returns the String value result of normalizing the string into the normalization form\n * named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.\n * @param form Applicable values: \"NFC\", \"NFD\", \"NFKC\", or \"NFKD\", If not specified default\n * is \"NFC\"\n */\n normalize(form?: string): string;\n\n /**\n * Returns a String value that is made from count copies appended together. If count is 0,\n * the empty string is returned.\n * @param count number of copies to append\n */\n repeat(count: number): string;\n\n /**\n * Returns true if the sequence of elements of searchString converted to a String is the\n * same as the corresponding elements of this object (converted to a String) starting at\n * position. Otherwise returns false.\n */\n startsWith(searchString: string, position?: number): boolean;\n\n /**\n * Returns an HTML anchor element and sets the name attribute to the text value\n * @param name\n */\n anchor(name: string): string;\n\n /** Returns a HTML element */\n big(): string;\n\n /** Returns a HTML element */\n blink(): string;\n\n /** Returns a HTML element */\n bold(): string;\n\n /** Returns a HTML element */\n fixed(): string;\n\n /** Returns a HTML element and sets the color attribute value */\n fontcolor(color: string): string;\n\n /** Returns a HTML element and sets the size attribute value */\n fontsize(size: number): string;\n\n /** Returns a HTML element and sets the size attribute value */\n fontsize(size: string): string;\n\n /** Returns an HTML element */\n italics(): string;\n\n /** Returns an HTML element and sets the href attribute value */\n link(url: string): string;\n\n /** Returns a HTML element */\n small(): string;\n\n /** Returns a HTML element */\n strike(): string;\n\n /** Returns a HTML element */\n sub(): string;\n\n /** Returns a HTML element */\n sup(): string;\n}\n\ninterface StringConstructor {\n /**\n * Return the String value whose elements are, in order, the elements in the List elements.\n * If length is 0, the empty string is returned.\n */\n fromCodePoint(...codePoints: number[]): string;\n\n /**\n * String.raw is intended for use as a tag function of a Tagged Template String. When called\n * as such the first argument will be a well formed template call site object and the rest\n * parameter will contain the substitution values.\n * @param template A well-formed template string call site representation.\n * @param substitutions A set of substitution values.\n */\n raw(template: TemplateStringsArray, ...substitutions: any[]): string;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface Map {\n clear(): void;\n delete(key: K): boolean;\n forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void;\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): this;\n readonly size: number;\n}\n\ninterface MapConstructor {\n new (entries?: ReadonlyArray<[K, V]> | null): Map;\n readonly prototype: Map;\n}\ndeclare var Map: MapConstructor;\n\ninterface ReadonlyMap {\n forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void;\n get(key: K): V | undefined;\n has(key: K): boolean;\n readonly size: number;\n}\n\ninterface WeakMap {\n delete(key: K): boolean;\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): this;\n}\n\ninterface WeakMapConstructor {\n new (entries?: ReadonlyArray<[K, V]> | null): WeakMap;\n readonly prototype: WeakMap;\n}\ndeclare var WeakMap: WeakMapConstructor;\n\ninterface Set {\n add(value: T): this;\n clear(): void;\n delete(value: T): boolean;\n forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void;\n has(value: T): boolean;\n readonly size: number;\n}\n\ninterface SetConstructor {\n new (values?: ReadonlyArray | null): Set;\n readonly prototype: Set;\n}\ndeclare var Set: SetConstructor;\n\ninterface ReadonlySet {\n forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void;\n has(value: T): boolean;\n readonly size: number;\n}\n\ninterface WeakSet {\n add(value: T): this;\n delete(value: T): boolean;\n has(value: T): boolean;\n}\n\ninterface WeakSetConstructor {\n new (values?: ReadonlyArray | null): WeakSet;\n readonly prototype: WeakSet;\n}\ndeclare var WeakSet: WeakSetConstructor;\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface Generator extends Iterator { }\n\ninterface GeneratorFunction {\n /**\n * Creates a new Generator object.\n * @param args A list of arguments the function accepts.\n */\n new (...args: any[]): Generator;\n /**\n * Creates a new Generator object.\n * @param args A list of arguments the function accepts.\n */\n (...args: any[]): Generator;\n /**\n * The length of the arguments.\n */\n readonly length: number;\n /**\n * Returns the name of the function.\n */\n readonly name: string;\n /**\n * A reference to the prototype.\n */\n readonly prototype: Generator;\n}\n\ninterface GeneratorFunctionConstructor {\n /**\n * Creates a new Generator function.\n * @param args A list of arguments the function accepts.\n */\n new (...args: string[]): GeneratorFunction;\n /**\n * Creates a new Generator function.\n * @param args A list of arguments the function accepts.\n */\n (...args: string[]): GeneratorFunction;\n /**\n * The length of the arguments.\n */\n readonly length: number;\n /**\n * Returns the name of the function.\n */\n readonly name: string;\n /**\n * A reference to the prototype.\n */\n readonly prototype: GeneratorFunction;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface PromiseConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Promise;\n\n /**\n * Creates a new Promise.\n * @param executor A callback used to initialize the promise. This callback is passed two arguments:\n * a resolve callback used resolve the promise with a value or the result of another promise,\n * and a reject callback used to reject the promise with a provided reason or error.\n */\n new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n 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]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>;\n\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: (T | PromiseLike)[]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike, T6 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike, T5 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: (T | PromiseLike)[]): Promise;\n\n /**\n * Creates a new rejected promise for the provided reason.\n * @param reason The reason the promise was rejected.\n * @returns A new rejected Promise.\n */\n reject(reason?: any): Promise;\n\n /**\n * Creates a new resolved promise for the provided value.\n * @param value A promise.\n * @returns A promise whose internal state matches the provided promise.\n */\n resolve(value: T | PromiseLike): Promise;\n\n /**\n * Creates a new resolved promise .\n * @returns A resolved promise.\n */\n resolve(): Promise;\n}\n\ndeclare var Promise: PromiseConstructor;\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface SymbolConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Symbol;\n\n /**\n * Returns a new unique Symbol value.\n * @param description Description of the new Symbol object.\n */\n (description?: string | number): symbol;\n\n /**\n * Returns a Symbol object from the global symbol registry matching the given key if found.\n * Otherwise, returns a new symbol with this key.\n * @param key key to search for.\n */\n for(key: string): symbol;\n\n /**\n * Returns a key from the global symbol registry matching the given Symbol if found.\n * Otherwise, returns a undefined.\n * @param sym Symbol to find the key for.\n */\n keyFor(sym: symbol): string | undefined;\n}\n\ndeclare var Symbol: SymbolConstructor;\n\n\ninterface SymbolConstructor {\n /**\n * A method that returns the default iterator for an object. Called by the semantics of the\n * for-of statement.\n */\n readonly iterator: symbol;\n}\n\ninterface IteratorResult {\n done: boolean;\n value: T;\n}\n\ninterface Iterator {\n next(value?: any): IteratorResult;\n return?(value?: any): IteratorResult;\n throw?(e?: any): IteratorResult;\n}\n\ninterface Iterable {\n [Symbol.iterator](): Iterator;\n}\n\ninterface IterableIterator extends Iterator {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Array {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, T]>;\n\n /**\n * Returns an iterable of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface ArrayConstructor {\n /**\n * Creates an array from an iterable object.\n * @param iterable An iterable object to convert to an array.\n */\n from(iterable: Iterable | ArrayLike): T[];\n\n /**\n * Creates an array from an iterable object.\n * @param iterable An iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(iterable: Iterable | ArrayLike, mapfn: (v: T, k: number) => U, thisArg?: any): U[];\n}\n\ninterface ReadonlyArray {\n /** Iterator of values in the array. */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, T]>;\n\n /**\n * Returns an iterable of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface IArguments {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Map {\n /** Returns an iterable of entries in the map. */\n [Symbol.iterator](): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the map.\n */\n entries(): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of keys in the map\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the map\n */\n values(): IterableIterator;\n}\n\ninterface ReadonlyMap {\n /** Returns an iterable of entries in the map. */\n [Symbol.iterator](): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of key, value pairs for every entry in the map.\n */\n entries(): IterableIterator<[K, V]>;\n\n /**\n * Returns an iterable of keys in the map\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the map\n */\n values(): IterableIterator;\n}\n\ninterface MapConstructor {\n new (iterable: Iterable<[K, V]>): Map;\n}\n\ninterface WeakMap { }\n\ninterface WeakMapConstructor {\n new (iterable: Iterable<[K, V]>): WeakMap;\n}\n\ninterface Set {\n /** Iterates over values in the set. */\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an iterable of [v,v] pairs for every value `v` in the set.\n */\n entries(): IterableIterator<[T, T]>;\n /**\n * Despite its name, returns an iterable of the values in the set,\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the set.\n */\n values(): IterableIterator;\n}\n\ninterface ReadonlySet {\n /** Iterates over values in the set. */\n [Symbol.iterator](): IterableIterator;\n\n /**\n * Returns an iterable of [v,v] pairs for every value `v` in the set.\n */\n entries(): IterableIterator<[T, T]>;\n\n /**\n * Despite its name, returns an iterable of the values in the set,\n */\n keys(): IterableIterator;\n\n /**\n * Returns an iterable of values in the set.\n */\n values(): IterableIterator;\n}\n\ninterface SetConstructor {\n new (iterable: Iterable): Set;\n}\n\ninterface WeakSet { }\n\ninterface WeakSetConstructor {\n new (iterable: Iterable): WeakSet;\n}\n\ninterface Promise { }\n\ninterface PromiseConstructor {\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n all(values: Iterable>): Promise;\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n * @param values An array of Promises.\n * @returns A new Promise.\n */\n race(values: Iterable>): Promise;\n}\n\ndeclare namespace Reflect {\n function enumerate(target: object): IterableIterator;\n}\n\ninterface String {\n /** Iterator */\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Int8Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int8ArrayConstructor {\n new (elements: Iterable): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n}\n\ninterface Uint8Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint8ArrayConstructor {\n new (elements: Iterable): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n}\n\ninterface Uint8ClampedArray {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint8ClampedArrayConstructor {\n new (elements: Iterable): Uint8ClampedArray;\n\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\n\ninterface Int16Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int16ArrayConstructor {\n new (elements: Iterable): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n}\n\ninterface Uint16Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint16ArrayConstructor {\n new (elements: Iterable): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n}\n\ninterface Int32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Int32ArrayConstructor {\n new (elements: Iterable): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n}\n\ninterface Uint32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Uint32ArrayConstructor {\n new (elements: Iterable): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n}\n\ninterface Float32Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Float32ArrayConstructor {\n new (elements: Iterable): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n}\n\ninterface Float64Array {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the array\n */\n entries(): IterableIterator<[number, number]>;\n /**\n * Returns an list of keys in the array\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the array\n */\n values(): IterableIterator;\n}\n\ninterface Float64ArrayConstructor {\n new (elements: Iterable): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface ProxyHandler {\n getPrototypeOf? (target: T): object | null;\n setPrototypeOf? (target: T, v: any): boolean;\n isExtensible? (target: T): boolean;\n preventExtensions? (target: T): boolean;\n getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined;\n has? (target: T, p: PropertyKey): boolean;\n get? (target: T, p: PropertyKey, receiver: any): any;\n set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;\n deleteProperty? (target: T, p: PropertyKey): boolean;\n defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;\n enumerate? (target: T): PropertyKey[];\n ownKeys? (target: T): PropertyKey[];\n apply? (target: T, thisArg: any, argArray?: any): any;\n construct? (target: T, argArray: any, newTarget?: any): object;\n}\n\ninterface ProxyConstructor {\n revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; };\n new (target: T, handler: ProxyHandler): T;\n}\ndeclare var Proxy: ProxyConstructor;\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ndeclare namespace Reflect {\n function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any;\n function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any;\n function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;\n function deleteProperty(target: object, propertyKey: PropertyKey): boolean;\n function get(target: object, propertyKey: PropertyKey, receiver?: any): any;\n function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor | undefined;\n function getPrototypeOf(target: object): object;\n function has(target: object, propertyKey: PropertyKey): boolean;\n function isExtensible(target: object): boolean;\n function ownKeys(target: object): PropertyKey[];\n function preventExtensions(target: object): boolean;\n function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean;\n function setPrototypeOf(target: object, proto: any): boolean;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface SymbolConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Symbol;\n\n /**\n * Returns a new unique Symbol value.\n * @param description Description of the new Symbol object.\n */\n (description?: string | number): symbol;\n\n /**\n * Returns a Symbol object from the global symbol registry matching the given key if found.\n * Otherwise, returns a new symbol with this key.\n * @param key key to search for.\n */\n for(key: string): symbol;\n\n /**\n * Returns a key from the global symbol registry matching the given Symbol if found.\n * Otherwise, returns a undefined.\n * @param sym Symbol to find the key for.\n */\n keyFor(sym: symbol): string | undefined;\n}\n\ndeclare var Symbol: SymbolConstructor;\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\ninterface SymbolConstructor {\n /**\n * A reference to the prototype.\n */\n readonly prototype: Symbol;\n\n /**\n * Returns a new unique Symbol value.\n * @param description Description of the new Symbol object.\n */\n (description?: string | number): symbol;\n\n /**\n * Returns a Symbol object from the global symbol registry matching the given key if found.\n * Otherwise, returns a new symbol with this key.\n * @param key key to search for.\n */\n for(key: string): symbol;\n\n /**\n * Returns a key from the global symbol registry matching the given Symbol if found.\n * Otherwise, returns a undefined.\n * @param sym Symbol to find the key for.\n */\n keyFor(sym: symbol): string | undefined;\n}\n\ndeclare var Symbol: SymbolConstructor;\n\n\ninterface SymbolConstructor {\n /**\n * A method that determines if a constructor object recognizes an object as one of the\n * constructor’s instances. Called by the semantics of the instanceof operator.\n */\n readonly hasInstance: symbol;\n\n /**\n * A Boolean value that if true indicates that an object should flatten to its array elements\n * by Array.prototype.concat.\n */\n readonly isConcatSpreadable: symbol;\n\n /**\n * A regular expression method that matches the regular expression against a string. Called\n * by the String.prototype.match method.\n */\n readonly match: symbol;\n\n /**\n * A regular expression method that replaces matched substrings of a string. Called by the\n * String.prototype.replace method.\n */\n readonly replace: symbol;\n\n /**\n * A regular expression method that returns the index within a string that matches the\n * regular expression. Called by the String.prototype.search method.\n */\n readonly search: symbol;\n\n /**\n * A function valued property that is the constructor function that is used to create\n * derived objects.\n */\n readonly species: symbol;\n\n /**\n * A regular expression method that splits a string at the indices that match the regular\n * expression. Called by the String.prototype.split method.\n */\n readonly split: symbol;\n\n /**\n * A method that converts an object to a corresponding primitive value.\n * Called by the ToPrimitive abstract operation.\n */\n readonly toPrimitive: symbol;\n\n /**\n * A String value that is used in the creation of the default string description of an object.\n * Called by the built-in method Object.prototype.toString.\n */\n readonly toStringTag: symbol;\n\n /**\n * An Object whose own property names are property names that are excluded from the 'with'\n * environment bindings of the associated objects.\n */\n readonly unscopables: symbol;\n}\n\ninterface Symbol {\n readonly [Symbol.toStringTag]: \"Symbol\";\n}\n\ninterface Array {\n /**\n * Returns an object whose properties have the value 'true'\n * when they will be absent when used in a 'with' statement.\n */\n [Symbol.unscopables](): {\n copyWithin: boolean;\n entries: boolean;\n fill: boolean;\n find: boolean;\n findIndex: boolean;\n keys: boolean;\n values: boolean;\n };\n}\n\ninterface Date {\n /**\n * Converts a Date object to a string.\n */\n [Symbol.toPrimitive](hint: \"default\"): string;\n /**\n * Converts a Date object to a string.\n */\n [Symbol.toPrimitive](hint: \"string\"): string;\n /**\n * Converts a Date object to a number.\n */\n [Symbol.toPrimitive](hint: \"number\"): number;\n /**\n * Converts a Date object to a string or number.\n *\n * @param hint The strings \"number\", \"string\", or \"default\" to specify what primitive to return.\n *\n * @throws {TypeError} If 'hint' was given something other than \"number\", \"string\", or \"default\".\n * @returns A number if 'hint' was \"number\", a string if 'hint' was \"string\" or \"default\".\n */\n [Symbol.toPrimitive](hint: string): string | number;\n}\n\ninterface Map {\n readonly [Symbol.toStringTag]: \"Map\";\n}\n\ninterface WeakMap {\n readonly [Symbol.toStringTag]: \"WeakMap\";\n}\n\ninterface Set {\n readonly [Symbol.toStringTag]: \"Set\";\n}\n\ninterface WeakSet {\n readonly [Symbol.toStringTag]: \"WeakSet\";\n}\n\ninterface JSON {\n readonly [Symbol.toStringTag]: \"JSON\";\n}\n\ninterface Function {\n /**\n * Determines whether the given value inherits from this function if this function was used\n * as a constructor function.\n *\n * A constructor function can control which objects are recognized as its instances by\n * 'instanceof' by overriding this method.\n */\n [Symbol.hasInstance](value: any): boolean;\n}\n\ninterface GeneratorFunction {\n readonly [Symbol.toStringTag]: \"GeneratorFunction\";\n}\n\ninterface Math {\n readonly [Symbol.toStringTag]: \"Math\";\n}\n\ninterface Promise {\n readonly [Symbol.toStringTag]: \"Promise\";\n}\n\ninterface PromiseConstructor {\n readonly [Symbol.species]: PromiseConstructor;\n}\n\ninterface RegExp {\n /**\n * Matches a string with this regular expression, and returns an array containing the results of\n * that search.\n * @param string A string to search within.\n */\n [Symbol.match](string: string): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using this regular expression.\n * @param string A String object or string literal whose contents matching against\n * this regular expression will be replaced\n * @param replaceValue A String object or string literal containing the text to replace for every\n * successful match of this regular expression.\n */\n [Symbol.replace](string: string, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using this regular expression.\n * @param string A String object or string literal whose contents matching against\n * this regular expression will be replaced\n * @param replacer A function that returns the replacement text.\n */\n [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the position beginning first substring match in a regular expression search\n * using this regular expression.\n *\n * @param string The string to search within.\n */\n [Symbol.search](string: string): number;\n\n /**\n * Returns an array of substrings that were delimited by strings in the original input that\n * match against this regular expression.\n *\n * If the regular expression contains capturing parentheses, then each time this\n * regular expression matches, the results (including any undefined results) of the\n * capturing parentheses are spliced.\n *\n * @param string string value to split\n * @param limit if not undefined, the output array is truncated so that it contains no more\n * than 'limit' elements.\n */\n [Symbol.split](string: string, limit?: number): string[];\n}\n\ninterface RegExpConstructor {\n readonly [Symbol.species]: RegExpConstructor;\n}\n\ninterface String {\n /**\n * Matches a string an object that supports being matched against, and returns an array containing the results of that search.\n * @param matcher An object that supports being matched against.\n */\n match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using an object that supports replacement within a string.\n * @param searchValue A object can search for and replace matches within a string.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using an object that supports replacement within a string.\n * @param searchValue A object can search for and replace matches within a string.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param searcher An object which supports searching within a string.\n */\n search(searcher: { [Symbol.search](string: string): number; }): number;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param splitter An object that can split a string.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];\n}\n\ninterface ArrayBuffer {\n readonly [Symbol.toStringTag]: \"ArrayBuffer\";\n}\n\ninterface DataView {\n readonly [Symbol.toStringTag]: \"DataView\";\n}\n\ninterface Int8Array {\n readonly [Symbol.toStringTag]: \"Int8Array\";\n}\n\ninterface Uint8Array {\n readonly [Symbol.toStringTag]: \"UInt8Array\";\n}\n\ninterface Uint8ClampedArray {\n readonly [Symbol.toStringTag]: \"Uint8ClampedArray\";\n}\n\ninterface Int16Array {\n readonly [Symbol.toStringTag]: \"Int16Array\";\n}\n\ninterface Uint16Array {\n readonly [Symbol.toStringTag]: \"Uint16Array\";\n}\n\ninterface Int32Array {\n readonly [Symbol.toStringTag]: \"Int32Array\";\n}\n\ninterface Uint32Array {\n readonly [Symbol.toStringTag]: \"Uint32Array\";\n}\n\ninterface Float32Array {\n readonly [Symbol.toStringTag]: \"Float32Array\";\n}\n\ninterface Float64Array {\n readonly [Symbol.toStringTag]: \"Float64Array\";\n}\n\ninterface ArrayConstructor {\n readonly [Symbol.species]: ArrayConstructor;\n}\ninterface MapConstructor {\n readonly [Symbol.species]: MapConstructor;\n}\ninterface SetConstructor {\n readonly [Symbol.species]: SetConstructor;\n}\ninterface ArrayBufferConstructor {\n readonly [Symbol.species]: ArrayBufferConstructor;\n}\n\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// DOM APIs\n/////////////////////////////\n\ninterface Account {\n displayName: string;\n id: string;\n imageURL?: string;\n name?: string;\n rpDisplayName: string;\n}\n\ninterface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\ninterface AesCbcParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCtrParams extends Algorithm {\n counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n length: number;\n}\n\ninterface AesDerivedKeyParams extends Algorithm {\n length: number;\n}\n\ninterface AesGcmParams extends Algorithm {\n additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n tagLength?: number;\n}\n\ninterface AesKeyAlgorithm extends KeyAlgorithm {\n length: number;\n}\n\ninterface AesKeyGenParams extends Algorithm {\n length: number;\n}\n\ninterface Algorithm {\n name: string;\n}\n\ninterface AnalyserOptions extends AudioNodeOptions {\n fftSize?: number;\n maxDecibels?: number;\n minDecibels?: number;\n smoothingTimeConstant?: number;\n}\n\ninterface AnimationEventInit extends EventInit {\n animationName?: string;\n elapsedTime?: number;\n pseudoElement?: string;\n}\n\ninterface AnimationPlaybackEventInit extends EventInit {\n currentTime?: number | null;\n timelineTime?: number | null;\n}\n\ninterface AssertionOptions {\n allowList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface AudioBufferOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface AudioBufferSourceOptions {\n buffer?: AudioBuffer | null;\n detune?: number;\n loop?: boolean;\n loopEnd?: number;\n loopStart?: number;\n playbackRate?: number;\n}\n\ninterface AudioContextInfo {\n currentTime?: number;\n sampleRate?: number;\n}\n\ninterface AudioContextOptions {\n latencyHint?: AudioContextLatencyCategory | number;\n sampleRate?: number;\n}\n\ninterface AudioNodeOptions {\n channelCount?: number;\n channelCountMode?: ChannelCountMode;\n channelInterpretation?: ChannelInterpretation;\n}\n\ninterface AudioParamDescriptor {\n automationRate?: AutomationRate;\n defaultValue?: number;\n maxValue?: number;\n minValue?: number;\n name: string;\n}\n\ninterface AudioProcessingEventInit extends EventInit {\n inputBuffer: AudioBuffer;\n outputBuffer: AudioBuffer;\n playbackTime: number;\n}\n\ninterface AudioTimestamp {\n contextTime?: number;\n performanceTime?: number;\n}\n\ninterface AudioWorkletNodeOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n numberOfOutputs?: number;\n outputChannelCount?: number[];\n parameterData?: Record;\n processorOptions?: any;\n}\n\ninterface BiquadFilterOptions extends AudioNodeOptions {\n Q?: number;\n detune?: number;\n frequency?: number;\n gain?: number;\n type?: BiquadFilterType;\n}\n\ninterface BlobPropertyBag {\n type?: string;\n}\n\ninterface ByteLengthChunk {\n byteLength?: number;\n}\n\ninterface CacheQueryOptions {\n cacheName?: string;\n ignoreMethod?: boolean;\n ignoreSearch?: boolean;\n ignoreVary?: boolean;\n}\n\ninterface ChannelMergerOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n}\n\ninterface ChannelSplitterOptions extends AudioNodeOptions {\n numberOfOutputs?: number;\n}\n\ninterface ClientData {\n challenge: string;\n extensions?: WebAuthnExtensions;\n hashAlg: string | Algorithm;\n origin: string;\n rpId: string;\n tokenBinding?: string;\n}\n\ninterface ClientQueryOptions {\n includeUncontrolled?: boolean;\n type?: ClientTypes;\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number;\n reason?: string;\n wasClean?: boolean;\n}\n\ninterface CompositionEventInit extends UIEventInit {\n data?: string;\n}\n\ninterface ComputedEffectTiming extends EffectTiming {\n activeDuration?: number;\n currentIteration?: number | null;\n endTime?: number;\n localTime?: number | null;\n progress?: number | null;\n}\n\ninterface ComputedKeyframe extends Record {\n composite?: CompositeOperation | null;\n computedOffset?: number;\n easing?: string;\n offset?: number | null;\n}\n\ninterface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface ConstantSourceOptions {\n offset?: number;\n}\n\ninterface ConstrainBooleanParameters {\n exact?: boolean;\n ideal?: boolean;\n}\n\ninterface ConstrainDOMStringParameters {\n exact?: string | string[];\n ideal?: string | string[];\n}\n\ninterface ConstrainDoubleRange extends DoubleRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainLongRange extends LongRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainVideoFacingModeParameters {\n exact?: VideoFacingModeEnum | VideoFacingModeEnum[];\n ideal?: VideoFacingModeEnum | VideoFacingModeEnum[];\n}\n\ninterface ConvolverOptions extends AudioNodeOptions {\n buffer?: AudioBuffer | null;\n disableNormalization?: boolean;\n}\n\ninterface CustomEventInit extends EventInit {\n detail?: T;\n}\n\ninterface DOMMatrix2DInit {\n a?: number;\n b?: number;\n c?: number;\n d?: number;\n e?: number;\n f?: number;\n m11?: number;\n m12?: number;\n m21?: number;\n m22?: number;\n m41?: number;\n m42?: number;\n}\n\ninterface DOMMatrixInit extends DOMMatrix2DInit {\n is2D?: boolean;\n m13?: number;\n m14?: number;\n m23?: number;\n m24?: number;\n m31?: number;\n m32?: number;\n m33?: number;\n m34?: number;\n m43?: number;\n m44?: number;\n}\n\ninterface DOMPointInit {\n w?: number;\n x?: number;\n y?: number;\n z?: number;\n}\n\ninterface DOMQuadInit {\n p1?: DOMPointInit;\n p2?: DOMPointInit;\n p3?: DOMPointInit;\n p4?: DOMPointInit;\n}\n\ninterface DOMRectInit {\n height?: number;\n width?: number;\n x?: number;\n y?: number;\n}\n\ninterface DelayOptions extends AudioNodeOptions {\n delayTime?: number;\n maxDelayTime?: number;\n}\n\ninterface DeviceAccelerationDict {\n x?: number | null;\n y?: number | null;\n z?: number | null;\n}\n\ninterface DeviceLightEventInit extends EventInit {\n value?: number;\n}\n\ninterface DeviceMotionEventInit extends EventInit {\n acceleration?: DeviceAccelerationDict | null;\n accelerationIncludingGravity?: DeviceAccelerationDict | null;\n interval?: number | null;\n rotationRate?: DeviceRotationRateDict | null;\n}\n\ninterface DeviceOrientationEventInit extends EventInit {\n absolute?: boolean;\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DeviceRotationRateDict {\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DocumentTimelineOptions {\n originTime?: number;\n}\n\ninterface DoubleRange {\n max?: number;\n min?: number;\n}\n\ninterface DynamicsCompressorOptions extends AudioNodeOptions {\n attack?: number;\n knee?: number;\n ratio?: number;\n release?: number;\n threshold?: number;\n}\n\ninterface EcKeyAlgorithm extends KeyAlgorithm {\n namedCurve: string;\n}\n\ninterface EcKeyGenParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcKeyImportParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcdhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface EcdsaParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface EffectTiming {\n delay?: number;\n direction?: PlaybackDirection;\n duration?: number | string;\n easing?: string;\n endDelay?: number;\n fill?: FillMode;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface ErrorEventInit extends EventInit {\n colno?: number;\n error?: any;\n filename?: string;\n lineno?: number;\n message?: string;\n}\n\ninterface EventInit {\n bubbles?: boolean;\n cancelable?: boolean;\n composed?: boolean;\n}\n\ninterface EventListenerOptions {\n capture?: boolean;\n}\n\ninterface EventModifierInit extends UIEventInit {\n altKey?: boolean;\n ctrlKey?: boolean;\n metaKey?: boolean;\n modifierAltGraph?: boolean;\n modifierCapsLock?: boolean;\n modifierFn?: boolean;\n modifierFnLock?: boolean;\n modifierHyper?: boolean;\n modifierNumLock?: boolean;\n modifierOS?: boolean;\n modifierScrollLock?: boolean;\n modifierSuper?: boolean;\n modifierSymbol?: boolean;\n modifierSymbolLock?: boolean;\n shiftKey?: boolean;\n}\n\ninterface ExceptionInformation {\n domain?: string | null;\n}\n\ninterface ExtendableEventInit extends EventInit {\n}\n\ninterface ExtendableMessageEventInit extends ExtendableEventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: object | ServiceWorker | MessagePort;\n}\n\ninterface FetchEventInit extends ExtendableEventInit {\n clientId?: string;\n preloadResponse: Promise;\n request: Request;\n resultingClientId?: string;\n targetClientId?: string;\n}\n\ninterface FilePropertyBag extends BlobPropertyBag {\n lastModified?: number;\n}\n\ninterface FocusEventInit extends UIEventInit {\n relatedTarget?: EventTarget | null;\n}\n\ninterface FocusNavigationEventInit extends EventInit {\n navigationReason?: string | null;\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface FocusNavigationOrigin {\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface GainOptions extends AudioNodeOptions {\n gain?: number;\n}\n\ninterface GamepadEventInit extends EventInit {\n gamepad?: Gamepad;\n}\n\ninterface GetNotificationOptions {\n tag?: string;\n}\n\ninterface HashChangeEventInit extends EventInit {\n newURL?: string;\n oldURL?: string;\n}\n\ninterface HkdfParams extends Algorithm {\n hash: string | Algorithm;\n info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface HmacImportParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface HmacKeyAlgorithm extends KeyAlgorithm {\n hash: KeyAlgorithm;\n length: number;\n}\n\ninterface HmacKeyGenParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface IDBIndexParameters {\n multiEntry?: boolean;\n unique?: boolean;\n}\n\ninterface IDBObjectStoreParameters {\n autoIncrement?: boolean;\n keyPath?: string | string[];\n}\n\ninterface IDBVersionChangeEventInit extends EventInit {\n newVersion?: number | null;\n oldVersion?: number;\n}\n\ninterface IIRFilterOptions extends AudioNodeOptions {\n feedback: number[];\n feedforward: number[];\n}\n\ninterface IntersectionObserverEntryInit {\n boundingClientRect: DOMRectInit;\n intersectionRect: DOMRectInit;\n isIntersecting: boolean;\n rootBounds: DOMRectInit;\n target: Element;\n time: number;\n}\n\ninterface IntersectionObserverInit {\n root?: Element | null;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\ninterface JsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\ninterface KeyAlgorithm {\n name: string;\n}\n\ninterface KeyboardEventInit extends EventModifierInit {\n code?: string;\n key?: string;\n location?: number;\n repeat?: boolean;\n}\n\ninterface Keyframe extends Record {\n composite?: CompositeOperation | null;\n easing?: string;\n offset?: number | null;\n}\n\ninterface KeyframeAnimationOptions extends KeyframeEffectOptions {\n id?: string;\n}\n\ninterface KeyframeEffectOptions extends EffectTiming {\n composite?: CompositeOperation;\n iterationComposite?: IterationCompositeOperation;\n}\n\ninterface LongRange {\n max?: number;\n min?: number;\n}\n\ninterface MSAccountInfo {\n accountImageUri?: string;\n accountName?: string;\n rpDisplayName: string;\n userDisplayName: string;\n userId?: string;\n}\n\ninterface MSAudioLocalClientEvent extends MSLocalClientEventBase {\n cpuInsufficientEventRatio?: number;\n deviceCaptureNotFunctioningEventRatio?: number;\n deviceClippingEventRatio?: number;\n deviceEchoEventRatio?: number;\n deviceGlitchesEventRatio?: number;\n deviceHalfDuplexAECEventRatio?: number;\n deviceHowlingEventCount?: number;\n deviceLowSNREventRatio?: number;\n deviceLowSpeechLevelEventRatio?: number;\n deviceMultipleEndpointsEventCount?: number;\n deviceNearEndToEchoRatioEventRatio?: number;\n deviceRenderMuteEventRatio?: number;\n deviceRenderNotFunctioningEventRatio?: number;\n deviceRenderZeroVolumeEventRatio?: number;\n networkDelayEventRatio?: number;\n networkSendQualityEventRatio?: number;\n}\n\ninterface MSAudioRecvPayload extends MSPayloadBase {\n burstLossLength1?: number;\n burstLossLength2?: number;\n burstLossLength3?: number;\n burstLossLength4?: number;\n burstLossLength5?: number;\n burstLossLength6?: number;\n burstLossLength7?: number;\n burstLossLength8OrHigher?: number;\n fecRecvDistance1?: number;\n fecRecvDistance2?: number;\n fecRecvDistance3?: number;\n packetReorderDepthAvg?: number;\n packetReorderDepthMax?: number;\n packetReorderRatio?: number;\n ratioCompressedSamplesAvg?: number;\n ratioConcealedSamplesAvg?: number;\n ratioStretchedSamplesAvg?: number;\n samplingRate?: number;\n signal?: MSAudioRecvSignal;\n}\n\ninterface MSAudioRecvSignal {\n initialSignalLevelRMS?: number;\n recvNoiseLevelCh1?: number;\n recvSignalLevelCh1?: number;\n renderLoopbackSignalLevel?: number;\n renderNoiseLevel?: number;\n renderSignalLevel?: number;\n}\n\ninterface MSAudioSendPayload extends MSPayloadBase {\n audioFECUsed?: boolean;\n samplingRate?: number;\n sendMutePercent?: number;\n signal?: MSAudioSendSignal;\n}\n\ninterface MSAudioSendSignal {\n noiseLevel?: number;\n sendNoiseLevelCh1?: number;\n sendSignalLevelCh1?: number;\n}\n\ninterface MSConnectivity {\n iceType?: MSIceType;\n iceWarningFlags?: MSIceWarningFlags;\n relayAddress?: MSRelayAddress;\n}\n\ninterface MSCredentialFilter {\n accept?: MSCredentialSpec[];\n}\n\ninterface MSCredentialParameters {\n type?: MSCredentialType;\n}\n\ninterface MSCredentialSpec {\n id?: string;\n type: MSCredentialType;\n}\n\ninterface MSDCCEventInit extends EventInit {\n maxFr?: number;\n maxFs?: number;\n}\n\ninterface MSDSHEventInit extends EventInit {\n sources?: number[];\n timestamp?: number;\n}\n\ninterface MSDelay {\n roundTrip?: number;\n roundTripMax?: number;\n}\n\ninterface MSDescription extends RTCStats {\n connectivity?: MSConnectivity;\n deviceDevName?: string;\n localAddr?: MSIPAddressInfo;\n networkconnectivity?: MSNetworkConnectivityInfo;\n reflexiveLocalIPAddr?: MSIPAddressInfo;\n remoteAddr?: MSIPAddressInfo;\n transport?: RTCIceProtocol;\n}\n\ninterface MSFIDOCredentialParameters extends MSCredentialParameters {\n algorithm?: string | Algorithm;\n authenticators?: string[];\n}\n\ninterface MSIPAddressInfo {\n ipAddr?: string;\n manufacturerMacAddrMask?: string;\n port?: number;\n}\n\ninterface MSIceWarningFlags {\n allocationMessageIntegrityFailed?: boolean;\n alternateServerReceived?: boolean;\n connCheckMessageIntegrityFailed?: boolean;\n connCheckOtherError?: boolean;\n fipsAllocationFailure?: boolean;\n multipleRelayServersAttempted?: boolean;\n noRelayServersConfigured?: boolean;\n portRangeExhausted?: boolean;\n pseudoTLSFailure?: boolean;\n tcpNatConnectivityFailed?: boolean;\n tcpRelayConnectivityFailed?: boolean;\n turnAuthUnknownUsernameError?: boolean;\n turnTcpAllocateFailed?: boolean;\n turnTcpSendFailed?: boolean;\n turnTcpTimedOut?: boolean;\n turnTurnTcpConnectivityFailed?: boolean;\n turnUdpAllocateFailed?: boolean;\n turnUdpSendFailed?: boolean;\n udpLocalConnectivityFailed?: boolean;\n udpNatConnectivityFailed?: boolean;\n udpRelayConnectivityFailed?: boolean;\n useCandidateChecksFailed?: boolean;\n}\n\ninterface MSJitter {\n interArrival?: number;\n interArrivalMax?: number;\n interArrivalSD?: number;\n}\n\ninterface MSLocalClientEventBase extends RTCStats {\n networkBandwidthLowEventRatio?: number;\n networkReceiveQualityEventRatio?: number;\n}\n\ninterface MSNetwork extends RTCStats {\n delay?: MSDelay;\n jitter?: MSJitter;\n packetLoss?: MSPacketLoss;\n utilization?: MSUtilization;\n}\n\ninterface MSNetworkConnectivityInfo {\n linkspeed?: number;\n networkConnectionDetails?: string;\n vpn?: boolean;\n}\n\ninterface MSNetworkInterfaceType {\n interfaceTypeEthernet?: boolean;\n interfaceTypePPP?: boolean;\n interfaceTypeTunnel?: boolean;\n interfaceTypeWWAN?: boolean;\n interfaceTypeWireless?: boolean;\n}\n\ninterface MSOutboundNetwork extends MSNetwork {\n appliedBandwidthLimit?: number;\n}\n\ninterface MSPacketLoss {\n lossRate?: number;\n lossRateMax?: number;\n}\n\ninterface MSPayloadBase extends RTCStats {\n payloadDescription?: string;\n}\n\ninterface MSPortRange {\n max?: number;\n min?: number;\n}\n\ninterface MSRelayAddress {\n port?: number;\n relayAddress?: string;\n}\n\ninterface MSSignatureParameters {\n userPrompt?: string;\n}\n\ninterface MSTransportDiagnosticsStats extends RTCStats {\n allocationTimeInMs?: number;\n baseAddress?: string;\n baseInterface?: MSNetworkInterfaceType;\n iceRole?: RTCIceRole;\n iceWarningFlags?: MSIceWarningFlags;\n interfaces?: MSNetworkInterfaceType;\n localAddrType?: MSIceAddrType;\n localAddress?: string;\n localInterface?: MSNetworkInterfaceType;\n localMR?: string;\n localMRTCPPort?: number;\n localSite?: string;\n msRtcEngineVersion?: string;\n networkName?: string;\n numConsentReqReceived?: number;\n numConsentReqSent?: number;\n numConsentRespReceived?: number;\n numConsentRespSent?: number;\n portRangeMax?: number;\n portRangeMin?: number;\n protocol?: RTCIceProtocol;\n remoteAddrType?: MSIceAddrType;\n remoteAddress?: string;\n remoteMR?: string;\n remoteMRTCPPort?: number;\n remoteSite?: string;\n rtpRtcpMux?: boolean;\n stunVer?: number;\n}\n\ninterface MSUtilization {\n bandwidthEstimation?: number;\n bandwidthEstimationAvg?: number;\n bandwidthEstimationMax?: number;\n bandwidthEstimationMin?: number;\n bandwidthEstimationStdDev?: number;\n packets?: number;\n}\n\ninterface MSVideoPayload extends MSPayloadBase {\n durationSeconds?: number;\n resolution?: string;\n videoBitRateAvg?: number;\n videoBitRateMax?: number;\n videoFrameRateAvg?: number;\n videoPacketLossRate?: number;\n}\n\ninterface MSVideoRecvPayload extends MSVideoPayload {\n lowBitRateCallPercent?: number;\n lowFrameRateCallPercent?: number;\n recvBitRateAverage?: number;\n recvBitRateMaximum?: number;\n recvCodecType?: string;\n recvFpsHarmonicAverage?: number;\n recvFrameRateAverage?: number;\n recvNumResSwitches?: number;\n recvReorderBufferMaxSuccessfullyOrderedExtent?: number;\n recvReorderBufferMaxSuccessfullyOrderedLateTime?: number;\n recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number;\n recvReorderBufferPacketsDroppedDueToTimeout?: number;\n recvReorderBufferReorderedPackets?: number;\n recvResolutionHeight?: number;\n recvResolutionWidth?: number;\n recvVideoStreamsMax?: number;\n recvVideoStreamsMin?: number;\n recvVideoStreamsMode?: number;\n reorderBufferTotalPackets?: number;\n videoFrameLossRate?: number;\n videoPostFECPLR?: number;\n videoResolutions?: MSVideoResolutionDistribution;\n}\n\ninterface MSVideoResolutionDistribution {\n cifQuality?: number;\n h1080Quality?: number;\n h1440Quality?: number;\n h2160Quality?: number;\n h720Quality?: number;\n vgaQuality?: number;\n}\n\ninterface MSVideoSendPayload extends MSVideoPayload {\n sendBitRateAverage?: number;\n sendBitRateMaximum?: number;\n sendFrameRateAverage?: number;\n sendResolutionHeight?: number;\n sendResolutionWidth?: number;\n sendVideoStreamsMax?: number;\n}\n\ninterface MediaElementAudioSourceOptions {\n mediaElement: HTMLMediaElement;\n}\n\ninterface MediaEncryptedEventInit extends EventInit {\n initData?: ArrayBuffer | null;\n initDataType?: string;\n}\n\ninterface MediaKeyMessageEventInit extends EventInit {\n message?: ArrayBuffer | null;\n messageType?: MediaKeyMessageType;\n}\n\ninterface MediaKeySystemConfiguration {\n audioCapabilities?: MediaKeySystemMediaCapability[];\n distinctiveIdentifier?: MediaKeysRequirement;\n initDataTypes?: string[];\n persistentState?: MediaKeysRequirement;\n videoCapabilities?: MediaKeySystemMediaCapability[];\n}\n\ninterface MediaKeySystemMediaCapability {\n contentType?: string;\n robustness?: string;\n}\n\ninterface MediaStreamAudioSourceOptions {\n mediaStream: MediaStream;\n}\n\ninterface MediaStreamConstraints {\n audio?: boolean | MediaTrackConstraints;\n peerIdentity?: string;\n video?: boolean | MediaTrackConstraints;\n}\n\ninterface MediaStreamErrorEventInit extends EventInit {\n error?: MediaStreamError | null;\n}\n\ninterface MediaStreamEventInit extends EventInit {\n stream?: MediaStream;\n}\n\ninterface MediaStreamTrackAudioSourceOptions {\n mediaStreamTrack: MediaStreamTrack;\n}\n\ninterface MediaStreamTrackEventInit extends EventInit {\n track?: MediaStreamTrack | null;\n}\n\ninterface MediaTrackCapabilities {\n aspectRatio?: number | DoubleRange;\n deviceId?: string;\n echoCancellation?: boolean[];\n facingMode?: string;\n frameRate?: number | DoubleRange;\n groupId?: string;\n height?: number | LongRange;\n sampleRate?: number | LongRange;\n sampleSize?: number | LongRange;\n volume?: number | DoubleRange;\n width?: number | LongRange;\n}\n\ninterface MediaTrackConstraintSet {\n aspectRatio?: number | ConstrainDoubleRange;\n channelCount?: number | ConstrainLongRange;\n deviceId?: string | string[] | ConstrainDOMStringParameters;\n displaySurface?: string | string[] | ConstrainDOMStringParameters;\n echoCancellation?: boolean | ConstrainBooleanParameters;\n facingMode?: string | string[] | ConstrainDOMStringParameters;\n frameRate?: number | ConstrainDoubleRange;\n groupId?: string | string[] | ConstrainDOMStringParameters;\n height?: number | ConstrainLongRange;\n latency?: number | ConstrainDoubleRange;\n logicalSurface?: boolean | ConstrainBooleanParameters;\n sampleRate?: number | ConstrainLongRange;\n sampleSize?: number | ConstrainLongRange;\n volume?: number | ConstrainDoubleRange;\n width?: number | ConstrainLongRange;\n}\n\ninterface MediaTrackConstraints extends MediaTrackConstraintSet {\n advanced?: MediaTrackConstraintSet[];\n}\n\ninterface MediaTrackSettings {\n aspectRatio?: number;\n deviceId?: string;\n echoCancellation?: boolean;\n facingMode?: string;\n frameRate?: number;\n groupId?: string;\n height?: number;\n sampleRate?: number;\n sampleSize?: number;\n volume?: number;\n width?: number;\n}\n\ninterface MediaTrackSupportedConstraints {\n aspectRatio?: boolean;\n deviceId?: boolean;\n echoCancellation?: boolean;\n facingMode?: boolean;\n frameRate?: boolean;\n groupId?: boolean;\n height?: boolean;\n sampleRate?: boolean;\n sampleSize?: boolean;\n volume?: boolean;\n width?: boolean;\n}\n\ninterface MessageEventInit extends EventInit {\n channel?: string;\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: Window | null;\n}\n\ninterface MouseEventInit extends EventModifierInit {\n button?: number;\n buttons?: number;\n clientX?: number;\n clientY?: number;\n relatedTarget?: EventTarget | null;\n screenX?: number;\n screenY?: number;\n}\n\ninterface MsZoomToOptions {\n animate?: string;\n contentX?: number;\n contentY?: number;\n scaleFactor?: number;\n viewportX?: string | null;\n viewportY?: string | null;\n}\n\ninterface MutationObserverInit {\n attributeFilter?: string[];\n attributeOldValue?: boolean;\n attributes?: boolean;\n characterData?: boolean;\n characterDataOldValue?: boolean;\n childList?: boolean;\n subtree?: boolean;\n}\n\ninterface NavigationPreloadState {\n enabled?: boolean;\n headerValue?: string;\n}\n\ninterface NotificationAction {\n action: string;\n icon?: string;\n title: string;\n}\n\ninterface NotificationEventInit extends ExtendableEventInit {\n action?: string;\n notification: Notification;\n}\n\ninterface NotificationOptions {\n actions?: NotificationAction[];\n badge?: string;\n body?: string;\n data?: any;\n dir?: NotificationDirection;\n icon?: string;\n image?: string;\n lang?: string;\n renotify?: boolean;\n requireInteraction?: boolean;\n silent?: boolean;\n tag?: string;\n timestamp?: number;\n vibrate?: VibratePattern;\n}\n\ninterface OfflineAudioCompletionEventInit extends EventInit {\n renderedBuffer: AudioBuffer;\n}\n\ninterface OfflineAudioContextOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface OptionalEffectTiming {\n delay?: number;\n direction?: PlaybackDirection;\n duration?: number | string;\n easing?: string;\n endDelay?: number;\n fill?: FillMode;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface OscillatorOptions extends AudioNodeOptions {\n detune?: number;\n frequency?: number;\n periodicWave?: PeriodicWave;\n type?: OscillatorType;\n}\n\ninterface PannerOptions extends AudioNodeOptions {\n coneInnerAngle?: number;\n coneOuterAngle?: number;\n coneOuterGain?: number;\n distanceModel?: DistanceModelType;\n maxDistance?: number;\n orientationX?: number;\n orientationY?: number;\n orientationZ?: number;\n panningModel?: PanningModelType;\n positionX?: number;\n positionY?: number;\n positionZ?: number;\n refDistance?: number;\n rolloffFactor?: number;\n}\n\ninterface PaymentCurrencyAmount {\n currency: string;\n currencySystem?: string;\n value: string;\n}\n\ninterface PaymentDetailsBase {\n displayItems?: PaymentItem[];\n modifiers?: PaymentDetailsModifier[];\n shippingOptions?: PaymentShippingOption[];\n}\n\ninterface PaymentDetailsInit extends PaymentDetailsBase {\n id?: string;\n total: PaymentItem;\n}\n\ninterface PaymentDetailsModifier {\n additionalDisplayItems?: PaymentItem[];\n data?: any;\n supportedMethods: string | string[];\n total?: PaymentItem;\n}\n\ninterface PaymentDetailsUpdate extends PaymentDetailsBase {\n error?: string;\n total?: PaymentItem;\n}\n\ninterface PaymentItem {\n amount: PaymentCurrencyAmount;\n label: string;\n pending?: boolean;\n}\n\ninterface PaymentMethodData {\n data?: any;\n supportedMethods: string | string[];\n}\n\ninterface PaymentOptions {\n requestPayerEmail?: boolean;\n requestPayerName?: boolean;\n requestPayerPhone?: boolean;\n requestShipping?: boolean;\n shippingType?: string;\n}\n\ninterface PaymentRequestUpdateEventInit extends EventInit {\n}\n\ninterface PaymentShippingOption {\n amount: PaymentCurrencyAmount;\n id: string;\n label: string;\n selected?: boolean;\n}\n\ninterface Pbkdf2Params extends Algorithm {\n hash: string | Algorithm;\n iterations: number;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface PerformanceObserverInit {\n buffered?: boolean;\n entryTypes: string[];\n}\n\ninterface PeriodicWaveConstraints {\n disableNormalization?: boolean;\n}\n\ninterface PeriodicWaveOptions extends PeriodicWaveConstraints {\n imag?: number[] | Float32Array;\n real?: number[] | Float32Array;\n}\n\ninterface PointerEventInit extends MouseEventInit {\n height?: number;\n isPrimary?: boolean;\n pointerId?: number;\n pointerType?: string;\n pressure?: number;\n tangentialPressure?: number;\n tiltX?: number;\n tiltY?: number;\n twist?: number;\n width?: number;\n}\n\ninterface PopStateEventInit extends EventInit {\n state?: any;\n}\n\ninterface PositionOptions {\n enableHighAccuracy?: boolean;\n maximumAge?: number;\n timeout?: number;\n}\n\ninterface ProgressEventInit extends EventInit {\n lengthComputable?: boolean;\n loaded?: number;\n total?: number;\n}\n\ninterface PromiseRejectionEventInit extends EventInit {\n promise: Promise;\n reason?: any;\n}\n\ninterface PropertyIndexedKeyframes extends Record {\n composite?: CompositeOperation | (CompositeOperation | null)[];\n easing?: string | string[];\n offset?: number | (number | null)[];\n}\n\ninterface PushEventInit extends ExtendableEventInit {\n data?: PushMessageDataInit;\n}\n\ninterface PushSubscriptionChangeInit extends ExtendableEventInit {\n newSubscription?: PushSubscription;\n oldSubscription?: PushSubscription;\n}\n\ninterface PushSubscriptionJSON {\n endpoint?: string;\n expirationTime?: number | null;\n keys?: Record;\n}\n\ninterface PushSubscriptionOptionsInit {\n applicationServerKey?: BufferSource | string;\n userVisibleOnly?: boolean;\n}\n\ninterface QueuingStrategy {\n highWaterMark?: number;\n size?: WritableStreamChunkCallback;\n}\n\ninterface RTCAnswerOptions extends RTCOfferAnswerOptions {\n}\n\ninterface RTCCertificateExpiration {\n expires?: number;\n}\n\ninterface RTCConfiguration {\n bundlePolicy?: RTCBundlePolicy;\n certificates?: RTCCertificate[];\n iceCandidatePoolSize?: number;\n iceServers?: RTCIceServer[];\n iceTransportPolicy?: RTCIceTransportPolicy;\n peerIdentity?: string;\n rtcpMuxPolicy?: RTCRtcpMuxPolicy;\n}\n\ninterface RTCDTMFToneChangeEventInit extends EventInit {\n tone: string;\n}\n\ninterface RTCDataChannelEventInit extends EventInit {\n channel: RTCDataChannel;\n}\n\ninterface RTCDataChannelInit {\n id?: number;\n maxPacketLifeTime?: number;\n maxRetransmits?: number;\n negotiated?: boolean;\n ordered?: boolean;\n priority?: RTCPriorityType;\n protocol?: string;\n}\n\ninterface RTCDtlsFingerprint {\n algorithm?: string;\n value?: string;\n}\n\ninterface RTCDtlsParameters {\n fingerprints?: RTCDtlsFingerprint[];\n role?: RTCDtlsRole;\n}\n\ninterface RTCErrorEventInit extends EventInit {\n error?: RTCError | null;\n}\n\ninterface RTCIceCandidateAttributes extends RTCStats {\n addressSourceUrl?: string;\n candidateType?: RTCStatsIceCandidateType;\n ipAddress?: string;\n portNumber?: number;\n priority?: number;\n transport?: string;\n}\n\ninterface RTCIceCandidateComplete {\n}\n\ninterface RTCIceCandidateDictionary {\n foundation?: string;\n ip?: string;\n msMTurnSessionId?: string;\n port?: number;\n priority?: number;\n protocol?: RTCIceProtocol;\n relatedAddress?: string;\n relatedPort?: number;\n tcpType?: RTCIceTcpCandidateType;\n type?: RTCIceCandidateType;\n}\n\ninterface RTCIceCandidateInit {\n candidate?: string;\n sdpMLineIndex?: number | null;\n sdpMid?: string | null;\n usernameFragment?: string;\n}\n\ninterface RTCIceCandidatePair {\n local?: RTCIceCandidate;\n remote?: RTCIceCandidate;\n}\n\ninterface RTCIceCandidatePairStats extends RTCStats {\n availableIncomingBitrate?: number;\n availableOutgoingBitrate?: number;\n bytesReceived?: number;\n bytesSent?: number;\n localCandidateId?: string;\n nominated?: boolean;\n priority?: number;\n readable?: boolean;\n remoteCandidateId?: string;\n roundTripTime?: number;\n state?: RTCStatsIceCandidatePairState;\n transportId?: string;\n writable?: boolean;\n}\n\ninterface RTCIceGatherOptions {\n gatherPolicy?: RTCIceGatherPolicy;\n iceservers?: RTCIceServer[];\n portRange?: MSPortRange;\n}\n\ninterface RTCIceParameters {\n password?: string;\n usernameFragment?: string;\n}\n\ninterface RTCIceServer {\n credential?: string | RTCOAuthCredential;\n credentialType?: RTCIceCredentialType;\n urls: string | string[];\n username?: string;\n}\n\ninterface RTCIdentityAssertionResult {\n assertion: string;\n idp: RTCIdentityProviderDetails;\n}\n\ninterface RTCIdentityProvider {\n generateAssertion: GenerateAssertionCallback;\n validateAssertion: ValidateAssertionCallback;\n}\n\ninterface RTCIdentityProviderDetails {\n domain: string;\n protocol?: string;\n}\n\ninterface RTCIdentityProviderOptions {\n peerIdentity?: string;\n protocol?: string;\n usernameHint?: string;\n}\n\ninterface RTCIdentityValidationResult {\n contents: string;\n identity: string;\n}\n\ninterface RTCInboundRTPStreamStats extends RTCRTPStreamStats {\n bytesReceived?: number;\n fractionLost?: number;\n jitter?: number;\n packetsLost?: number;\n packetsReceived?: number;\n}\n\ninterface RTCMediaStreamTrackStats extends RTCStats {\n audioLevel?: number;\n echoReturnLoss?: number;\n echoReturnLossEnhancement?: number;\n frameHeight?: number;\n frameWidth?: number;\n framesCorrupted?: number;\n framesDecoded?: number;\n framesDropped?: number;\n framesPerSecond?: number;\n framesReceived?: number;\n framesSent?: number;\n remoteSource?: boolean;\n ssrcIds?: string[];\n trackIdentifier?: string;\n}\n\ninterface RTCOAuthCredential {\n accessToken: string;\n macKey: string;\n}\n\ninterface RTCOfferAnswerOptions {\n voiceActivityDetection?: boolean;\n}\n\ninterface RTCOfferOptions extends RTCOfferAnswerOptions {\n iceRestart?: boolean;\n offerToReceiveAudio?: boolean;\n offerToReceiveVideo?: boolean;\n}\n\ninterface RTCOutboundRTPStreamStats extends RTCRTPStreamStats {\n bytesSent?: number;\n packetsSent?: number;\n roundTripTime?: number;\n targetBitrate?: number;\n}\n\ninterface RTCPeerConnectionIceErrorEventInit extends EventInit {\n errorCode: number;\n hostCandidate?: string;\n statusText?: string;\n url?: string;\n}\n\ninterface RTCPeerConnectionIceEventInit extends EventInit {\n candidate?: RTCIceCandidate | null;\n url?: string | null;\n}\n\ninterface RTCRTPStreamStats extends RTCStats {\n associateStatsId?: string;\n codecId?: string;\n firCount?: number;\n isRemote?: boolean;\n mediaTrackId?: string;\n mediaType?: string;\n nackCount?: number;\n pliCount?: number;\n sliCount?: number;\n ssrc?: string;\n transportId?: string;\n}\n\ninterface RTCRtcpFeedback {\n parameter?: string;\n type?: string;\n}\n\ninterface RTCRtcpParameters {\n cname?: string;\n reducedSize?: boolean;\n}\n\ninterface RTCRtpCapabilities {\n codecs: RTCRtpCodecCapability[];\n headerExtensions: RTCRtpHeaderExtensionCapability[];\n}\n\ninterface RTCRtpCodecCapability {\n channels?: number;\n clockRate: number;\n mimeType: string;\n sdpFmtpLine?: string;\n}\n\ninterface RTCRtpCodecParameters {\n channels?: number;\n clockRate: number;\n mimeType: string;\n payloadType: number;\n sdpFmtpLine?: string;\n}\n\ninterface RTCRtpCodingParameters {\n rid?: string;\n}\n\ninterface RTCRtpContributingSource {\n audioLevel?: number;\n source: number;\n timestamp: number;\n}\n\ninterface RTCRtpDecodingParameters extends RTCRtpCodingParameters {\n}\n\ninterface RTCRtpEncodingParameters extends RTCRtpCodingParameters {\n active?: boolean;\n codecPayloadType?: number;\n dtx?: RTCDtxStatus;\n maxBitrate?: number;\n maxFramerate?: number;\n priority?: RTCPriorityType;\n ptime?: number;\n scaleResolutionDownBy?: number;\n}\n\ninterface RTCRtpFecParameters {\n mechanism?: string;\n ssrc?: number;\n}\n\ninterface RTCRtpHeaderExtension {\n kind?: string;\n preferredEncrypt?: boolean;\n preferredId?: number;\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionCapability {\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionParameters {\n encrypted?: boolean;\n id: number;\n uri: string;\n}\n\ninterface RTCRtpParameters {\n codecs: RTCRtpCodecParameters[];\n headerExtensions: RTCRtpHeaderExtensionParameters[];\n rtcp: RTCRtcpParameters;\n}\n\ninterface RTCRtpReceiveParameters extends RTCRtpParameters {\n encodings: RTCRtpDecodingParameters[];\n}\n\ninterface RTCRtpRtxParameters {\n ssrc?: number;\n}\n\ninterface RTCRtpSendParameters extends RTCRtpParameters {\n degradationPreference?: RTCDegradationPreference;\n encodings: RTCRtpEncodingParameters[];\n transactionId: string;\n}\n\ninterface RTCRtpSynchronizationSource extends RTCRtpContributingSource {\n voiceActivityFlag?: boolean;\n}\n\ninterface RTCRtpTransceiverInit {\n direction?: RTCRtpTransceiverDirection;\n sendEncodings?: RTCRtpEncodingParameters[];\n streams?: MediaStream[];\n}\n\ninterface RTCRtpUnhandled {\n muxId?: string;\n payloadType?: number;\n ssrc?: number;\n}\n\ninterface RTCSessionDescriptionInit {\n sdp?: string;\n type: RTCSdpType;\n}\n\ninterface RTCSrtpKeyParam {\n keyMethod?: string;\n keySalt?: string;\n lifetime?: string;\n mkiLength?: number;\n mkiValue?: number;\n}\n\ninterface RTCSrtpSdesParameters {\n cryptoSuite?: string;\n keyParams?: RTCSrtpKeyParam[];\n sessionParams?: string[];\n tag?: number;\n}\n\ninterface RTCSsrcRange {\n max?: number;\n min?: number;\n}\n\ninterface RTCStats {\n id: string;\n timestamp: number;\n type: RTCStatsType;\n}\n\ninterface RTCStatsEventInit extends EventInit {\n report: RTCStatsReport;\n}\n\ninterface RTCStatsReport {\n}\n\ninterface RTCTrackEventInit extends EventInit {\n receiver: RTCRtpReceiver;\n streams?: MediaStream[];\n track: MediaStreamTrack;\n transceiver: RTCRtpTransceiver;\n}\n\ninterface RTCTransportStats extends RTCStats {\n activeConnection?: boolean;\n bytesReceived?: number;\n bytesSent?: number;\n localCertificateId?: string;\n remoteCertificateId?: string;\n rtcpTransportStatsId?: string;\n selectedCandidatePairId?: string;\n}\n\ninterface RegistrationOptions {\n scope?: string;\n type?: WorkerType;\n updateViaCache?: ServiceWorkerUpdateViaCache;\n}\n\ninterface RequestInit {\n body?: BodyInit | null;\n cache?: RequestCache;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n integrity?: string;\n keepalive?: boolean;\n method?: string;\n mode?: RequestMode;\n redirect?: RequestRedirect;\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n signal?: AbortSignal | null;\n window?: any;\n}\n\ninterface ResponseInit {\n headers?: HeadersInit;\n status?: number;\n statusText?: string;\n}\n\ninterface RsaHashedImportParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {\n hash: KeyAlgorithm;\n}\n\ninterface RsaHashedKeyGenParams extends RsaKeyGenParams {\n hash: string | Algorithm;\n}\n\ninterface RsaKeyAlgorithm extends KeyAlgorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaKeyGenParams extends Algorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaOaepParams extends Algorithm {\n label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface RsaOtherPrimesInfo {\n d?: string;\n r?: string;\n t?: string;\n}\n\ninterface RsaPssParams extends Algorithm {\n saltLength: number;\n}\n\ninterface ScopedCredentialDescriptor {\n id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n transports?: Transport[];\n type: ScopedCredentialType;\n}\n\ninterface ScopedCredentialOptions {\n excludeList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface ScopedCredentialParameters {\n algorithm: string | Algorithm;\n type: ScopedCredentialType;\n}\n\ninterface ScrollIntoViewOptions extends ScrollOptions {\n block?: ScrollLogicalPosition;\n inline?: ScrollLogicalPosition;\n}\n\ninterface ScrollOptions {\n behavior?: ScrollBehavior;\n}\n\ninterface ScrollToOptions extends ScrollOptions {\n left?: number;\n top?: number;\n}\n\ninterface SecurityPolicyViolationEventInit extends EventInit {\n blockedURI?: string;\n columnNumber?: number;\n documentURI?: string;\n effectiveDirective?: string;\n lineNumber?: number;\n originalPolicy?: string;\n referrer?: string;\n sourceFile?: string;\n statusCode?: number;\n violatedDirective?: string;\n}\n\ninterface ServiceWorkerMessageEventInit extends EventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: ServiceWorker | MessagePort | null;\n}\n\ninterface SpeechSynthesisEventInit extends EventInit {\n charIndex?: number;\n charLength?: number;\n elapsedTime?: number;\n name?: string;\n utterance?: SpeechSynthesisUtterance | null;\n}\n\ninterface StereoPannerOptions extends AudioNodeOptions {\n pan?: number;\n}\n\ninterface StorageEstimate {\n quota?: number;\n usage?: number;\n}\n\ninterface StorageEventInit extends EventInit {\n key?: string | null;\n newValue?: string | null;\n oldValue?: string | null;\n storageArea?: Storage | null;\n url?: string;\n}\n\ninterface StoreExceptionsInformation extends ExceptionInformation {\n detailURI?: string | null;\n explanationString?: string | null;\n siteName?: string | null;\n}\n\ninterface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface SyncEventInit extends ExtendableEventInit {\n lastChance?: boolean;\n tag: string;\n}\n\ninterface TextDecodeOptions {\n stream?: boolean;\n}\n\ninterface TextDecoderOptions {\n fatal?: boolean;\n ignoreBOM?: boolean;\n}\n\ninterface TouchEventInit extends EventModifierInit {\n changedTouches?: Touch[];\n targetTouches?: Touch[];\n touches?: Touch[];\n}\n\ninterface TouchInit {\n altitudeAngle?: number;\n azimuthAngle?: number;\n clientX?: number;\n clientY?: number;\n force?: number;\n identifier: number;\n pageX?: number;\n pageY?: number;\n radiusX?: number;\n radiusY?: number;\n rotationAngle?: number;\n screenX?: number;\n screenY?: number;\n target: EventTarget;\n touchType?: TouchType;\n}\n\ninterface TrackEventInit extends EventInit {\n track?: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ninterface TransitionEventInit extends EventInit {\n elapsedTime?: number;\n propertyName?: string;\n pseudoElement?: string;\n}\n\ninterface UIEventInit extends EventInit {\n detail?: number;\n view?: Window | null;\n}\n\ninterface UnderlyingSink {\n abort?: WritableStreamErrorCallback;\n close?: WritableStreamDefaultControllerCallback;\n start: WritableStreamDefaultControllerCallback;\n write?: WritableStreamChunkCallback;\n}\n\ninterface VRDisplayEventInit extends EventInit {\n display: VRDisplay;\n reason?: VRDisplayEventReason;\n}\n\ninterface VRLayer {\n leftBounds?: number[] | Float32Array | null;\n rightBounds?: number[] | Float32Array | null;\n source?: HTMLCanvasElement | null;\n}\n\ninterface VRStageParameters {\n sittingToStandingTransform?: Float32Array;\n sizeX?: number;\n sizeY?: number;\n}\n\ninterface WaveShaperOptions extends AudioNodeOptions {\n curve?: number[] | Float32Array;\n oversample?: OverSampleType;\n}\n\ninterface WebAuthnExtensions {\n}\n\ninterface WebGLContextAttributes {\n alpha?: boolean;\n antialias?: boolean;\n depth?: boolean;\n failIfMajorPerformanceCaveat?: boolean;\n premultipliedAlpha?: boolean;\n preserveDrawingBuffer?: boolean;\n stencil?: boolean;\n}\n\ninterface WebGLContextEventInit extends EventInit {\n statusMessage?: string;\n}\n\ninterface WheelEventInit extends MouseEventInit {\n deltaMode?: number;\n deltaX?: number;\n deltaY?: number;\n deltaZ?: number;\n}\n\ninterface WorkletOptions {\n credentials?: RequestCredentials;\n}\n\ninterface EventListener {\n (evt: Event): void;\n}\n\ninterface ANGLE_instanced_arrays {\n drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void;\n drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void;\n vertexAttribDivisorANGLE(index: number, divisor: number): void;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n}\n\ndeclare var ANGLE_instanced_arrays: {\n prototype: ANGLE_instanced_arrays;\n new(): ANGLE_instanced_arrays;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n};\n\ninterface AbortController {\n readonly signal: AbortSignal;\n abort(): void;\n}\n\ndeclare var AbortController: {\n prototype: AbortController;\n new(): AbortController;\n};\n\ninterface AbortSignalEventMap {\n \"abort\": ProgressEvent;\n}\n\ninterface AbortSignal extends EventTarget {\n readonly aborted: boolean;\n onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AbortSignal: {\n prototype: AbortSignal;\n new(): AbortSignal;\n};\n\ninterface AbstractWorkerEventMap {\n \"error\": ErrorEvent;\n}\n\ninterface AbstractWorker {\n onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AesCfbParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCmacParams extends Algorithm {\n length: number;\n}\n\ninterface AnalyserNode extends AudioNode {\n fftSize: number;\n readonly frequencyBinCount: number;\n maxDecibels: number;\n minDecibels: number;\n smoothingTimeConstant: number;\n getByteFrequencyData(array: Uint8Array): void;\n getByteTimeDomainData(array: Uint8Array): void;\n getFloatFrequencyData(array: Float32Array): void;\n getFloatTimeDomainData(array: Float32Array): void;\n}\n\ndeclare var AnalyserNode: {\n prototype: AnalyserNode;\n new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode;\n};\n\ninterface Animatable {\n animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation;\n getAnimations(): Animation[];\n}\n\ninterface AnimationEventMap {\n \"cancel\": AnimationPlaybackEvent;\n \"finish\": AnimationPlaybackEvent;\n}\n\ninterface Animation extends EventTarget {\n currentTime: number | null;\n effect: AnimationEffect | null;\n readonly finished: Promise;\n id: string;\n oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\n onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\n readonly pending: boolean;\n readonly playState: AnimationPlayState;\n playbackRate: number;\n readonly ready: Promise;\n startTime: number | null;\n timeline: AnimationTimeline | null;\n cancel(): void;\n finish(): void;\n pause(): void;\n play(): void;\n reverse(): void;\n updatePlaybackRate(playbackRate: number): void;\n addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Animation: {\n prototype: Animation;\n new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation;\n};\n\ninterface AnimationEffect {\n getComputedTiming(): ComputedEffectTiming;\n getTiming(): EffectTiming;\n updateTiming(timing?: OptionalEffectTiming): void;\n}\n\ndeclare var AnimationEffect: {\n prototype: AnimationEffect;\n new(): AnimationEffect;\n};\n\ninterface AnimationEvent extends Event {\n readonly animationName: string;\n readonly elapsedTime: number;\n readonly pseudoElement: string;\n}\n\ndeclare var AnimationEvent: {\n prototype: AnimationEvent;\n new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent;\n};\n\ninterface AnimationPlaybackEvent extends Event {\n readonly currentTime: number | null;\n readonly timelineTime: number | null;\n}\n\ndeclare var AnimationPlaybackEvent: {\n prototype: AnimationPlaybackEvent;\n new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent;\n};\n\ninterface AnimationTimeline {\n readonly currentTime: number | null;\n}\n\ndeclare var AnimationTimeline: {\n prototype: AnimationTimeline;\n new(): AnimationTimeline;\n};\n\ninterface ApplicationCacheEventMap {\n \"cached\": Event;\n \"checking\": Event;\n \"downloading\": Event;\n \"error\": Event;\n \"noupdate\": Event;\n \"obsolete\": Event;\n \"progress\": ProgressEvent;\n \"updateready\": Event;\n}\n\ninterface ApplicationCache extends EventTarget {\n oncached: ((this: ApplicationCache, ev: Event) => any) | null;\n onchecking: ((this: ApplicationCache, ev: Event) => any) | null;\n ondownloading: ((this: ApplicationCache, ev: Event) => any) | null;\n onerror: ((this: ApplicationCache, ev: Event) => any) | null;\n onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null;\n onobsolete: ((this: ApplicationCache, ev: Event) => any) | null;\n onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null;\n onupdateready: ((this: ApplicationCache, ev: Event) => any) | null;\n readonly status: number;\n abort(): void;\n swapCache(): void;\n update(): void;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ApplicationCache: {\n prototype: ApplicationCache;\n new(): ApplicationCache;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n};\n\ninterface AssignedNodesOptions {\n flatten?: boolean;\n}\n\ninterface Attr extends Node {\n readonly name: string;\n readonly ownerElement: Element | null;\n readonly prefix: string | null;\n readonly specified: boolean;\n value: string;\n}\n\ndeclare var Attr: {\n prototype: Attr;\n new(): Attr;\n};\n\ninterface AudioBuffer {\n readonly duration: number;\n readonly length: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n getChannelData(channel: number): Float32Array;\n}\n\ndeclare var AudioBuffer: {\n prototype: AudioBuffer;\n new(options: AudioBufferOptions): AudioBuffer;\n};\n\ninterface AudioBufferSourceNode extends AudioScheduledSourceNode {\n buffer: AudioBuffer | null;\n readonly detune: AudioParam;\n loop: boolean;\n loopEnd: number;\n loopStart: number;\n readonly playbackRate: AudioParam;\n start(when?: number, offset?: number, duration?: number): void;\n addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioBufferSourceNode: {\n prototype: AudioBufferSourceNode;\n new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode;\n};\n\ninterface AudioContext extends BaseAudioContext {\n readonly baseLatency: number;\n readonly outputLatency: number;\n close(): Promise;\n createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;\n createMediaStreamDestination(): MediaStreamAudioDestinationNode;\n createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode;\n createMediaStreamTrackSource(mediaStreamTrack: MediaStreamTrack): MediaStreamTrackAudioSourceNode;\n getOutputTimestamp(): AudioTimestamp;\n suspend(): Promise;\n addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioContext: {\n prototype: AudioContext;\n new(contextOptions?: AudioContextOptions): AudioContext;\n};\n\ninterface AudioDestinationNode extends AudioNode {\n readonly maxChannelCount: number;\n}\n\ndeclare var AudioDestinationNode: {\n prototype: AudioDestinationNode;\n new(): AudioDestinationNode;\n};\n\ninterface AudioListener {\n readonly forwardX: AudioParam;\n readonly forwardY: AudioParam;\n readonly forwardZ: AudioParam;\n readonly positionX: AudioParam;\n readonly positionY: AudioParam;\n readonly positionZ: AudioParam;\n readonly upX: AudioParam;\n readonly upY: AudioParam;\n readonly upZ: AudioParam;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n}\n\ndeclare var AudioListener: {\n prototype: AudioListener;\n new(): AudioListener;\n};\n\ninterface AudioNode extends EventTarget {\n channelCount: number;\n channelCountMode: ChannelCountMode;\n channelInterpretation: ChannelInterpretation;\n readonly context: BaseAudioContext;\n readonly numberOfInputs: number;\n readonly numberOfOutputs: number;\n connect(destinationNode: AudioNode, output?: number, input?: number): AudioNode;\n connect(destinationParam: AudioParam, output?: number): void;\n disconnect(): void;\n disconnect(output: number): void;\n disconnect(destinationNode: AudioNode): void;\n disconnect(destinationNode: AudioNode, output: number): void;\n disconnect(destinationNode: AudioNode, output: number, input: number): void;\n disconnect(destinationParam: AudioParam): void;\n disconnect(destinationParam: AudioParam, output: number): void;\n}\n\ndeclare var AudioNode: {\n prototype: AudioNode;\n new(): AudioNode;\n};\n\ninterface AudioParam {\n automationRate: AutomationRate;\n readonly defaultValue: number;\n readonly maxValue: number;\n readonly minValue: number;\n value: number;\n cancelAndHoldAtTime(cancelTime: number): AudioParam;\n cancelScheduledValues(cancelTime: number): AudioParam;\n exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;\n linearRampToValueAtTime(value: number, endTime: number): AudioParam;\n setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam;\n setValueAtTime(value: number, startTime: number): AudioParam;\n setValueCurveAtTime(values: number[] | Float32Array, startTime: number, duration: number): AudioParam;\n}\n\ndeclare var AudioParam: {\n prototype: AudioParam;\n new(): AudioParam;\n};\n\ninterface AudioParamMap {\n forEach(callbackfn: (value: AudioParam, key: string, parent: AudioParamMap) => void, thisArg?: any): void;\n}\n\ndeclare var AudioParamMap: {\n prototype: AudioParamMap;\n new(): AudioParamMap;\n};\n\ninterface AudioProcessingEvent extends Event {\n readonly inputBuffer: AudioBuffer;\n readonly outputBuffer: AudioBuffer;\n readonly playbackTime: number;\n}\n\ndeclare var AudioProcessingEvent: {\n prototype: AudioProcessingEvent;\n new(type: string, eventInitDict: AudioProcessingEventInit): AudioProcessingEvent;\n};\n\ninterface AudioScheduledSourceNodeEventMap {\n \"ended\": Event;\n}\n\ninterface AudioScheduledSourceNode extends AudioNode {\n onended: ((this: AudioScheduledSourceNode, ev: Event) => any) | null;\n start(when?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioScheduledSourceNode: {\n prototype: AudioScheduledSourceNode;\n new(): AudioScheduledSourceNode;\n};\n\ninterface AudioTrack {\n enabled: boolean;\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var AudioTrack: {\n prototype: AudioTrack;\n new(): AudioTrack;\n};\n\ninterface AudioTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface AudioTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: AudioTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n getTrackById(id: string): AudioTrack | null;\n item(index: number): AudioTrack;\n addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: AudioTrack;\n}\n\ndeclare var AudioTrackList: {\n prototype: AudioTrackList;\n new(): AudioTrackList;\n};\n\ninterface AudioWorklet extends Worklet {\n}\n\ndeclare var AudioWorklet: {\n prototype: AudioWorklet;\n new(): AudioWorklet;\n};\n\ninterface AudioWorkletNodeEventMap {\n \"processorerror\": Event;\n}\n\ninterface AudioWorkletNode extends AudioNode {\n onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null;\n readonly parameters: AudioParamMap;\n readonly port: MessagePort;\n addEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioWorkletNode: {\n prototype: AudioWorkletNode;\n new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;\n};\n\ninterface BarProp {\n readonly visible: boolean;\n}\n\ndeclare var BarProp: {\n prototype: BarProp;\n new(): BarProp;\n};\n\ninterface BaseAudioContextEventMap {\n \"statechange\": Event;\n}\n\ninterface BaseAudioContext extends EventTarget {\n readonly audioWorklet: AudioWorklet;\n readonly currentTime: number;\n readonly destination: AudioDestinationNode;\n readonly listener: AudioListener;\n onstatechange: ((this: BaseAudioContext, ev: Event) => any) | null;\n readonly sampleRate: number;\n readonly state: AudioContextState;\n createAnalyser(): AnalyserNode;\n createBiquadFilter(): BiquadFilterNode;\n createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;\n createBufferSource(): AudioBufferSourceNode;\n createChannelMerger(numberOfInputs?: number): ChannelMergerNode;\n createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode;\n createConstantSource(): ConstantSourceNode;\n createConvolver(): ConvolverNode;\n createDelay(maxDelayTime?: number): DelayNode;\n createDynamicsCompressor(): DynamicsCompressorNode;\n createGain(): GainNode;\n createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode;\n createOscillator(): OscillatorNode;\n createPanner(): PannerNode;\n createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave;\n createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;\n createStereoPanner(): StereoPannerNode;\n createWaveShaper(): WaveShaperNode;\n decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise;\n resume(): Promise;\n addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BaseAudioContext: {\n prototype: BaseAudioContext;\n new(): BaseAudioContext;\n};\n\ninterface BeforeUnloadEvent extends Event {\n returnValue: any;\n}\n\ndeclare var BeforeUnloadEvent: {\n prototype: BeforeUnloadEvent;\n new(): BeforeUnloadEvent;\n};\n\ninterface BhxBrowser {\n readonly lastError: DOMException;\n checkMatchesGlobExpression(pattern: string, value: string): boolean;\n checkMatchesUriExpression(pattern: string, value: string): boolean;\n clearLastError(): void;\n currentWindowId(): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n getExtensionId(): string;\n getThisAddress(): any;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericListenerHandler(eventHandler: Function): void;\n setLastError(parameters: string): void;\n webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void;\n}\n\ndeclare var BhxBrowser: {\n prototype: BhxBrowser;\n new(): BhxBrowser;\n};\n\ninterface BiquadFilterNode extends AudioNode {\n readonly Q: AudioParam;\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n readonly gain: AudioParam;\n type: BiquadFilterType;\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var BiquadFilterNode: {\n prototype: BiquadFilterNode;\n new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode;\n};\n\ninterface Blob {\n readonly size: number;\n readonly type: string;\n slice(start?: number, end?: number, contentType?: string): Blob;\n}\n\ndeclare var Blob: {\n prototype: Blob;\n new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;\n};\n\ninterface Body {\n readonly body: ReadableStream | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise;\n blob(): Promise;\n formData(): Promise;\n json(): Promise;\n text(): Promise;\n}\n\ninterface BroadcastChannelEventMap {\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface BroadcastChannel extends EventTarget {\n /**\n * Returns the channel name (as passed to the constructor).\n */\n readonly name: string;\n onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\n /**\n * Closes the BroadcastChannel object, opening it up to garbage collection.\n */\n close(): void;\n /**\n * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.\n */\n postMessage(message: any): void;\n addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BroadcastChannel: {\n prototype: BroadcastChannel;\n new(name: string): BroadcastChannel;\n};\n\ninterface BroadcastChannelEventMap {\n message: MessageEvent;\n messageerror: MessageEvent;\n}\n\ninterface ByteLengthQueuingStrategy {\n highWaterMark: number;\n size(chunk?: any): number;\n}\n\ndeclare var ByteLengthQueuingStrategy: {\n prototype: ByteLengthQueuingStrategy;\n new(strategy: QueuingStrategy): ByteLengthQueuingStrategy;\n};\n\ninterface CDATASection extends Text {\n}\n\ndeclare var CDATASection: {\n prototype: CDATASection;\n new(): CDATASection;\n};\n\ninterface CSS {\n escape(value: string): string;\n supports(property: string, value?: string): boolean;\n}\ndeclare var CSS: CSS;\n\ninterface CSSConditionRule extends CSSGroupingRule {\n conditionText: string;\n}\n\ndeclare var CSSConditionRule: {\n prototype: CSSConditionRule;\n new(): CSSConditionRule;\n};\n\ninterface CSSFontFaceRule extends CSSRule {\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSFontFaceRule: {\n prototype: CSSFontFaceRule;\n new(): CSSFontFaceRule;\n};\n\ninterface CSSGroupingRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n deleteRule(index: number): void;\n insertRule(rule: string, index: number): number;\n}\n\ndeclare var CSSGroupingRule: {\n prototype: CSSGroupingRule;\n new(): CSSGroupingRule;\n};\n\ninterface CSSImportRule extends CSSRule {\n readonly href: string;\n readonly media: MediaList;\n readonly styleSheet: CSSStyleSheet;\n}\n\ndeclare var CSSImportRule: {\n prototype: CSSImportRule;\n new(): CSSImportRule;\n};\n\ninterface CSSKeyframeRule extends CSSRule {\n keyText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSKeyframeRule: {\n prototype: CSSKeyframeRule;\n new(): CSSKeyframeRule;\n};\n\ninterface CSSKeyframesRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n name: string;\n appendRule(rule: string): void;\n deleteRule(select: string): void;\n findRule(select: string): CSSKeyframeRule | null;\n}\n\ndeclare var CSSKeyframesRule: {\n prototype: CSSKeyframesRule;\n new(): CSSKeyframesRule;\n};\n\ninterface CSSMediaRule extends CSSConditionRule {\n readonly media: MediaList;\n}\n\ndeclare var CSSMediaRule: {\n prototype: CSSMediaRule;\n new(): CSSMediaRule;\n};\n\ninterface CSSNamespaceRule extends CSSRule {\n readonly namespaceURI: string;\n readonly prefix: string;\n}\n\ndeclare var CSSNamespaceRule: {\n prototype: CSSNamespaceRule;\n new(): CSSNamespaceRule;\n};\n\ninterface CSSPageRule extends CSSRule {\n readonly pseudoClass: string;\n readonly selector: string;\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSPageRule: {\n prototype: CSSPageRule;\n new(): CSSPageRule;\n};\n\ninterface CSSRule {\n cssText: string;\n readonly parentRule: CSSRule | null;\n readonly parentStyleSheet: CSSStyleSheet | null;\n readonly type: number;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n}\n\ndeclare var CSSRule: {\n prototype: CSSRule;\n new(): CSSRule;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n};\n\ninterface CSSRuleList {\n readonly length: number;\n item(index: number): CSSRule | null;\n [index: number]: CSSRule;\n}\n\ndeclare var CSSRuleList: {\n prototype: CSSRuleList;\n new(): CSSRuleList;\n};\n\ninterface CSSStyleDeclaration {\n alignContent: string | null;\n alignItems: string | null;\n alignSelf: string | null;\n alignmentBaseline: string | null;\n animation: string | null;\n animationDelay: string | null;\n animationDirection: string | null;\n animationDuration: string | null;\n animationFillMode: string | null;\n animationIterationCount: string | null;\n animationName: string | null;\n animationPlayState: string | null;\n animationTimingFunction: string | null;\n backfaceVisibility: string | null;\n background: string | null;\n backgroundAttachment: string | null;\n backgroundClip: string | null;\n backgroundColor: string | null;\n backgroundImage: string | null;\n backgroundOrigin: string | null;\n backgroundPosition: string | null;\n backgroundPositionX: string | null;\n backgroundPositionY: string | null;\n backgroundRepeat: string | null;\n backgroundSize: string | null;\n baselineShift: string | null;\n border: string | null;\n borderBottom: string | null;\n borderBottomColor: string | null;\n borderBottomLeftRadius: string | null;\n borderBottomRightRadius: string | null;\n borderBottomStyle: string | null;\n borderBottomWidth: string | null;\n borderCollapse: string | null;\n borderColor: string | null;\n borderImage: string | null;\n borderImageOutset: string | null;\n borderImageRepeat: string | null;\n borderImageSlice: string | null;\n borderImageSource: string | null;\n borderImageWidth: string | null;\n borderLeft: string | null;\n borderLeftColor: string | null;\n borderLeftStyle: string | null;\n borderLeftWidth: string | null;\n borderRadius: string | null;\n borderRight: string | null;\n borderRightColor: string | null;\n borderRightStyle: string | null;\n borderRightWidth: string | null;\n borderSpacing: string | null;\n borderStyle: string | null;\n borderTop: string | null;\n borderTopColor: string | null;\n borderTopLeftRadius: string | null;\n borderTopRightRadius: string | null;\n borderTopStyle: string | null;\n borderTopWidth: string | null;\n borderWidth: string | null;\n bottom: string | null;\n boxShadow: string | null;\n boxSizing: string | null;\n breakAfter: string | null;\n breakBefore: string | null;\n breakInside: string | null;\n captionSide: string | null;\n clear: string | null;\n clip: string | null;\n clipPath: string | null;\n clipRule: string | null;\n color: string | null;\n colorInterpolationFilters: string | null;\n columnCount: any;\n columnFill: string | null;\n columnGap: any;\n columnRule: string | null;\n columnRuleColor: any;\n columnRuleStyle: string | null;\n columnRuleWidth: any;\n columnSpan: string | null;\n columnWidth: any;\n columns: string | null;\n content: string | null;\n counterIncrement: string | null;\n counterReset: string | null;\n cssFloat: string | null;\n cssText: string;\n cursor: string | null;\n direction: string | null;\n display: string | null;\n dominantBaseline: string | null;\n emptyCells: string | null;\n enableBackground: string | null;\n fill: string | null;\n fillOpacity: string | null;\n fillRule: string | null;\n filter: string | null;\n flex: string | null;\n flexBasis: string | null;\n flexDirection: string | null;\n flexFlow: string | null;\n flexGrow: string | null;\n flexShrink: string | null;\n flexWrap: string | null;\n floodColor: string | null;\n floodOpacity: string | null;\n font: string | null;\n fontFamily: string | null;\n fontFeatureSettings: string | null;\n fontSize: string | null;\n fontSizeAdjust: string | null;\n fontStretch: string | null;\n fontStyle: string | null;\n fontVariant: string | null;\n fontWeight: string | null;\n gap: string | null;\n glyphOrientationHorizontal: string | null;\n glyphOrientationVertical: string | null;\n grid: string | null;\n gridArea: string | null;\n gridAutoColumns: string | null;\n gridAutoFlow: string | null;\n gridAutoRows: string | null;\n gridColumn: string | null;\n gridColumnEnd: string | null;\n gridColumnGap: string | null;\n gridColumnStart: string | null;\n gridGap: string | null;\n gridRow: string | null;\n gridRowEnd: string | null;\n gridRowGap: string | null;\n gridRowStart: string | null;\n gridTemplate: string | null;\n gridTemplateAreas: string | null;\n gridTemplateColumns: string | null;\n gridTemplateRows: string | null;\n height: string | null;\n imeMode: string | null;\n justifyContent: string | null;\n justifyItems: string | null;\n justifySelf: string | null;\n kerning: string | null;\n layoutGrid: string | null;\n layoutGridChar: string | null;\n layoutGridLine: string | null;\n layoutGridMode: string | null;\n layoutGridType: string | null;\n left: string | null;\n readonly length: number;\n letterSpacing: string | null;\n lightingColor: string | null;\n lineBreak: string | null;\n lineHeight: string | null;\n listStyle: string | null;\n listStyleImage: string | null;\n listStylePosition: string | null;\n listStyleType: string | null;\n margin: string | null;\n marginBottom: string | null;\n marginLeft: string | null;\n marginRight: string | null;\n marginTop: string | null;\n marker: string | null;\n markerEnd: string | null;\n markerMid: string | null;\n markerStart: string | null;\n mask: string | null;\n maskImage: string | null;\n maxHeight: string | null;\n maxWidth: string | null;\n minHeight: string | null;\n minWidth: string | null;\n msContentZoomChaining: string | null;\n msContentZoomLimit: string | null;\n msContentZoomLimitMax: any;\n msContentZoomLimitMin: any;\n msContentZoomSnap: string | null;\n msContentZoomSnapPoints: string | null;\n msContentZoomSnapType: string | null;\n msContentZooming: string | null;\n msFlowFrom: string | null;\n msFlowInto: string | null;\n msFontFeatureSettings: string | null;\n msGridColumn: any;\n msGridColumnAlign: string | null;\n msGridColumnSpan: any;\n msGridColumns: string | null;\n msGridRow: any;\n msGridRowAlign: string | null;\n msGridRowSpan: any;\n msGridRows: string | null;\n msHighContrastAdjust: string | null;\n msHyphenateLimitChars: string | null;\n msHyphenateLimitLines: any;\n msHyphenateLimitZone: any;\n msHyphens: string | null;\n msImeAlign: string | null;\n msOverflowStyle: string | null;\n msScrollChaining: string | null;\n msScrollLimit: string | null;\n msScrollLimitXMax: any;\n msScrollLimitXMin: any;\n msScrollLimitYMax: any;\n msScrollLimitYMin: any;\n msScrollRails: string | null;\n msScrollSnapPointsX: string | null;\n msScrollSnapPointsY: string | null;\n msScrollSnapType: string | null;\n msScrollSnapX: string | null;\n msScrollSnapY: string | null;\n msScrollTranslation: string | null;\n msTextCombineHorizontal: string | null;\n msTextSizeAdjust: any;\n msTouchAction: string | null;\n msTouchSelect: string | null;\n msUserSelect: string | null;\n msWrapFlow: string;\n msWrapMargin: any;\n msWrapThrough: string;\n objectFit: string | null;\n objectPosition: string | null;\n opacity: string | null;\n order: string | null;\n orphans: string | null;\n outline: string | null;\n outlineColor: string | null;\n outlineOffset: string | null;\n outlineStyle: string | null;\n outlineWidth: string | null;\n overflow: string | null;\n overflowX: string | null;\n overflowY: string | null;\n padding: string | null;\n paddingBottom: string | null;\n paddingLeft: string | null;\n paddingRight: string | null;\n paddingTop: string | null;\n pageBreakAfter: string | null;\n pageBreakBefore: string | null;\n pageBreakInside: string | null;\n readonly parentRule: CSSRule;\n penAction: string | null;\n perspective: string | null;\n perspectiveOrigin: string | null;\n pointerEvents: string | null;\n position: string | null;\n quotes: string | null;\n resize: string | null;\n right: string | null;\n rotate: string | null;\n rowGap: string | null;\n rubyAlign: string | null;\n rubyOverhang: string | null;\n rubyPosition: string | null;\n scale: string | null;\n stopColor: string | null;\n stopOpacity: string | null;\n stroke: string | null;\n strokeDasharray: string | null;\n strokeDashoffset: string | null;\n strokeLinecap: string | null;\n strokeLinejoin: string | null;\n strokeMiterlimit: string | null;\n strokeOpacity: string | null;\n strokeWidth: string | null;\n tableLayout: string | null;\n textAlign: string | null;\n textAlignLast: string | null;\n textAnchor: string | null;\n textCombineUpright: string | null;\n textDecoration: string | null;\n textIndent: string | null;\n textJustify: string | null;\n textKashida: string | null;\n textKashidaSpace: string | null;\n textOverflow: string | null;\n textShadow: string | null;\n textTransform: string | null;\n textUnderlinePosition: string | null;\n top: string | null;\n touchAction: string | null;\n transform: string | null;\n transformOrigin: string | null;\n transformStyle: string | null;\n transition: string | null;\n transitionDelay: string | null;\n transitionDuration: string | null;\n transitionProperty: string | null;\n transitionTimingFunction: string | null;\n translate: string | null;\n unicodeBidi: string | null;\n userSelect: string | null;\n verticalAlign: string | null;\n visibility: string | null;\n webkitAlignContent: string | null;\n webkitAlignItems: string | null;\n webkitAlignSelf: string | null;\n webkitAnimation: string | null;\n webkitAnimationDelay: string | null;\n webkitAnimationDirection: string | null;\n webkitAnimationDuration: string | null;\n webkitAnimationFillMode: string | null;\n webkitAnimationIterationCount: string | null;\n webkitAnimationName: string | null;\n webkitAnimationPlayState: string | null;\n webkitAnimationTimingFunction: string | null;\n webkitAppearance: string | null;\n webkitBackfaceVisibility: string | null;\n webkitBackgroundClip: string | null;\n webkitBackgroundOrigin: string | null;\n webkitBackgroundSize: string | null;\n webkitBorderBottomLeftRadius: string | null;\n webkitBorderBottomRightRadius: string | null;\n webkitBorderImage: string | null;\n webkitBorderRadius: string | null;\n webkitBorderTopLeftRadius: string | null;\n webkitBorderTopRightRadius: string | null;\n webkitBoxAlign: string | null;\n webkitBoxDirection: string | null;\n webkitBoxFlex: string | null;\n webkitBoxOrdinalGroup: string | null;\n webkitBoxOrient: string | null;\n webkitBoxPack: string | null;\n webkitBoxSizing: string | null;\n webkitColumnBreakAfter: string | null;\n webkitColumnBreakBefore: string | null;\n webkitColumnBreakInside: string | null;\n webkitColumnCount: any;\n webkitColumnGap: any;\n webkitColumnRule: string | null;\n webkitColumnRuleColor: any;\n webkitColumnRuleStyle: string | null;\n webkitColumnRuleWidth: any;\n webkitColumnSpan: string | null;\n webkitColumnWidth: any;\n webkitColumns: string | null;\n webkitFilter: string | null;\n webkitFlex: string | null;\n webkitFlexBasis: string | null;\n webkitFlexDirection: string | null;\n webkitFlexFlow: string | null;\n webkitFlexGrow: string | null;\n webkitFlexShrink: string | null;\n webkitFlexWrap: string | null;\n webkitJustifyContent: string | null;\n webkitOrder: string | null;\n webkitPerspective: string | null;\n webkitPerspectiveOrigin: string | null;\n webkitTapHighlightColor: string | null;\n webkitTextFillColor: string | null;\n webkitTextSizeAdjust: any;\n webkitTextStroke: string | null;\n webkitTextStrokeColor: string | null;\n webkitTextStrokeWidth: string | null;\n webkitTransform: string | null;\n webkitTransformOrigin: string | null;\n webkitTransformStyle: string | null;\n webkitTransition: string | null;\n webkitTransitionDelay: string | null;\n webkitTransitionDuration: string | null;\n webkitTransitionProperty: string | null;\n webkitTransitionTimingFunction: string | null;\n webkitUserModify: string | null;\n webkitUserSelect: string | null;\n webkitWritingMode: string | null;\n whiteSpace: string | null;\n widows: string | null;\n width: string | null;\n wordBreak: string | null;\n wordSpacing: string | null;\n wordWrap: string | null;\n writingMode: string | null;\n zIndex: string | null;\n zoom: string | null;\n getPropertyPriority(propertyName: string): string;\n getPropertyValue(propertyName: string): string;\n item(index: number): string;\n removeProperty(propertyName: string): string;\n setProperty(propertyName: string, value: string | null, priority?: string | null): void;\n [index: number]: string;\n}\n\ndeclare var CSSStyleDeclaration: {\n prototype: CSSStyleDeclaration;\n new(): CSSStyleDeclaration;\n};\n\ninterface CSSStyleRule extends CSSRule {\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSStyleRule: {\n prototype: CSSStyleRule;\n new(): CSSStyleRule;\n};\n\ninterface CSSStyleSheet extends StyleSheet {\n readonly cssRules: CSSRuleList;\n /** @deprecated */\n cssText: string;\n /** @deprecated */\n readonly id: string;\n /** @deprecated */\n readonly imports: StyleSheetList;\n /** @deprecated */\n readonly isAlternate: boolean;\n /** @deprecated */\n readonly isPrefAlternate: boolean;\n readonly ownerRule: CSSRule | null;\n /** @deprecated */\n readonly owningElement: Element;\n /** @deprecated */\n readonly pages: any;\n /** @deprecated */\n readonly readOnly: boolean;\n readonly rules: CSSRuleList;\n /** @deprecated */\n addImport(bstrURL: string, lIndex?: number): number;\n /** @deprecated */\n addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number;\n addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number;\n deleteRule(index?: number): void;\n insertRule(rule: string, index?: number): number;\n /** @deprecated */\n removeImport(lIndex: number): void;\n removeRule(lIndex: number): void;\n}\n\ndeclare var CSSStyleSheet: {\n prototype: CSSStyleSheet;\n new(): CSSStyleSheet;\n};\n\ninterface CSSSupportsRule extends CSSConditionRule {\n}\n\ndeclare var CSSSupportsRule: {\n prototype: CSSSupportsRule;\n new(): CSSSupportsRule;\n};\n\ninterface Cache {\n add(request: RequestInfo): Promise;\n addAll(requests: RequestInfo[]): Promise;\n delete(request: RequestInfo, options?: CacheQueryOptions): Promise;\n keys(request?: RequestInfo, options?: CacheQueryOptions): Promise>;\n match(request: RequestInfo, options?: CacheQueryOptions): Promise;\n matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise>;\n put(request: RequestInfo, response: Response): Promise;\n}\n\ndeclare var Cache: {\n prototype: Cache;\n new(): Cache;\n};\n\ninterface CacheStorage {\n delete(cacheName: string): Promise;\n has(cacheName: string): Promise;\n keys(): Promise;\n match(request: RequestInfo, options?: CacheQueryOptions): Promise;\n open(cacheName: string): Promise;\n}\n\ndeclare var CacheStorage: {\n prototype: CacheStorage;\n new(): CacheStorage;\n};\n\ninterface Canvas2DContextAttributes {\n alpha?: boolean;\n storage?: boolean;\n willReadFrequently?: boolean;\n [attribute: string]: boolean | string | undefined;\n}\n\ninterface CanvasGradient {\n addColorStop(offset: number, color: string): void;\n}\n\ndeclare var CanvasGradient: {\n prototype: CanvasGradient;\n new(): CanvasGradient;\n};\n\ninterface CanvasPathMethods {\n arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;\n bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;\n closePath(): void;\n ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n lineTo(x: number, y: number): void;\n moveTo(x: number, y: number): void;\n quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;\n rect(x: number, y: number, w: number, h: number): void;\n}\n\ninterface CanvasPattern {\n setTransform(matrix: SVGMatrix): void;\n}\n\ndeclare var CanvasPattern: {\n prototype: CanvasPattern;\n new(): CanvasPattern;\n};\n\ninterface CanvasRenderingContext2D extends CanvasPathMethods {\n readonly canvas: HTMLCanvasElement;\n fillStyle: string | CanvasGradient | CanvasPattern;\n font: string;\n globalAlpha: number;\n globalCompositeOperation: string;\n imageSmoothingEnabled: boolean;\n lineCap: string;\n lineDashOffset: number;\n lineJoin: string;\n lineWidth: number;\n miterLimit: number;\n mozImageSmoothingEnabled: boolean;\n msFillRule: CanvasFillRule;\n oImageSmoothingEnabled: boolean;\n shadowBlur: number;\n shadowColor: string;\n shadowOffsetX: number;\n shadowOffsetY: number;\n strokeStyle: string | CanvasGradient | CanvasPattern;\n textAlign: string;\n textBaseline: string;\n webkitImageSmoothingEnabled: boolean;\n beginPath(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n clip(fillRule?: CanvasFillRule): void;\n clip(path: Path2D, fillRule?: CanvasFillRule): void;\n createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;\n createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;\n drawFocusIfNeeded(element: Element): void;\n drawFocusIfNeeded(path: Path2D, element: Element): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void;\n fill(fillRule?: CanvasFillRule): void;\n fill(path: Path2D, fillRule?: CanvasFillRule): void;\n fillRect(x: number, y: number, w: number, h: number): void;\n fillText(text: string, x: number, y: number, maxWidth?: number): void;\n getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;\n getLineDash(): number[];\n isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n measureText(text: string): TextMetrics;\n putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void;\n restore(): void;\n rotate(angle: number): void;\n save(): void;\n scale(x: number, y: number): void;\n setLineDash(segments: number[]): void;\n setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n stroke(path?: Path2D): void;\n strokeRect(x: number, y: number, w: number, h: number): void;\n strokeText(text: string, x: number, y: number, maxWidth?: number): void;\n transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n translate(x: number, y: number): void;\n}\n\ndeclare var CanvasRenderingContext2D: {\n prototype: CanvasRenderingContext2D;\n new(): CanvasRenderingContext2D;\n};\n\ninterface ChannelMergerNode extends AudioNode {\n}\n\ndeclare var ChannelMergerNode: {\n prototype: ChannelMergerNode;\n new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode;\n};\n\ninterface ChannelSplitterNode extends AudioNode {\n}\n\ndeclare var ChannelSplitterNode: {\n prototype: ChannelSplitterNode;\n new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode;\n};\n\ninterface CharacterData extends Node, ChildNode {\n data: string;\n readonly length: number;\n appendData(arg: string): void;\n deleteData(offset: number, count: number): void;\n insertData(offset: number, arg: string): void;\n replaceData(offset: number, count: number, arg: string): void;\n substringData(offset: number, count: number): string;\n}\n\ndeclare var CharacterData: {\n prototype: CharacterData;\n new(): CharacterData;\n};\n\ninterface ChildNode {\n remove(): void;\n}\n\ninterface ClientRect {\n bottom: number;\n readonly height: number;\n left: number;\n right: number;\n top: number;\n readonly width: number;\n}\n\ndeclare var ClientRect: {\n prototype: ClientRect;\n new(): ClientRect;\n};\n\ninterface ClientRectList {\n readonly length: number;\n item(index: number): ClientRect;\n [index: number]: ClientRect;\n}\n\ndeclare var ClientRectList: {\n prototype: ClientRectList;\n new(): ClientRectList;\n};\n\ninterface ClipboardEvent extends Event {\n readonly clipboardData: DataTransfer;\n}\n\ndeclare var ClipboardEvent: {\n prototype: ClipboardEvent;\n new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;\n};\n\ninterface ClipboardEventInit extends EventInit {\n data?: string;\n dataType?: string;\n}\n\ninterface CloseEvent extends Event {\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n /** @deprecated */\n initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;\n}\n\ndeclare var CloseEvent: {\n prototype: CloseEvent;\n new(type: string, eventInitDict?: CloseEventInit): CloseEvent;\n};\n\ninterface Comment extends CharacterData {\n text: string;\n}\n\ndeclare var Comment: {\n prototype: Comment;\n new(data?: string): Comment;\n};\n\ninterface CompositionEvent extends UIEvent {\n readonly data: string;\n readonly locale: string;\n initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void;\n}\n\ndeclare var CompositionEvent: {\n prototype: CompositionEvent;\n new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent;\n};\n\ninterface ConcatParams extends Algorithm {\n algorithmId: Uint8Array;\n hash?: string | Algorithm;\n partyUInfo: Uint8Array;\n partyVInfo: Uint8Array;\n privateInfo?: Uint8Array;\n publicInfo?: Uint8Array;\n}\n\ninterface Console {\n memory: any;\n assert(condition?: boolean, message?: string, ...data: any[]): void;\n clear(): void;\n count(label?: string): void;\n debug(message?: any, ...optionalParams: any[]): void;\n dir(value?: any, ...optionalParams: any[]): void;\n dirxml(value: any): void;\n error(message?: any, ...optionalParams: any[]): void;\n exception(message?: string, ...optionalParams: any[]): void;\n group(groupTitle?: string, ...optionalParams: any[]): void;\n groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;\n groupEnd(): void;\n info(message?: any, ...optionalParams: any[]): void;\n log(message?: any, ...optionalParams: any[]): void;\n markTimeline(label?: string): void;\n msIsIndependentlyComposed(element: Element): boolean;\n profile(reportName?: string): void;\n profileEnd(): void;\n select(element: Element): void;\n table(...tabularData: any[]): void;\n time(label?: string): void;\n timeEnd(label?: string): void;\n timeStamp(label?: string): void;\n timeline(label?: string): void;\n timelineEnd(label?: string): void;\n trace(message?: any, ...optionalParams: any[]): void;\n warn(message?: any, ...optionalParams: any[]): void;\n}\n\ndeclare var Console: {\n prototype: Console;\n new(): Console;\n};\n\ninterface ConstantSourceNode extends AudioScheduledSourceNode {\n readonly offset: AudioParam;\n addEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ConstantSourceNode: {\n prototype: ConstantSourceNode;\n new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode;\n};\n\ninterface ConvolverNode extends AudioNode {\n buffer: AudioBuffer | null;\n normalize: boolean;\n}\n\ndeclare var ConvolverNode: {\n prototype: ConvolverNode;\n new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode;\n};\n\ninterface Coordinates {\n readonly accuracy: number;\n readonly altitude: number | null;\n readonly altitudeAccuracy: number | null;\n readonly heading: number | null;\n readonly latitude: number;\n readonly longitude: number;\n readonly speed: number | null;\n}\n\ninterface CountQueuingStrategy {\n highWaterMark: number;\n size(): number;\n}\n\ndeclare var CountQueuingStrategy: {\n prototype: CountQueuingStrategy;\n new(strategy: QueuingStrategy): CountQueuingStrategy;\n};\n\ninterface Crypto {\n readonly subtle: SubtleCrypto;\n getRandomValues(array: T): T;\n}\n\ndeclare var Crypto: {\n prototype: Crypto;\n new(): Crypto;\n};\n\ninterface CryptoKey {\n readonly algorithm: KeyAlgorithm;\n readonly extractable: boolean;\n readonly type: string;\n readonly usages: string[];\n}\n\ndeclare var CryptoKey: {\n prototype: CryptoKey;\n new(): CryptoKey;\n};\n\ninterface CryptoKeyPair {\n privateKey: CryptoKey;\n publicKey: CryptoKey;\n}\n\ndeclare var CryptoKeyPair: {\n prototype: CryptoKeyPair;\n new(): CryptoKeyPair;\n};\n\ninterface CustomElementRegistry {\n define(name: string, constructor: Function, options?: ElementDefinitionOptions): void;\n get(name: string): any;\n whenDefined(name: string): PromiseLike;\n}\n\ninterface CustomEvent extends Event {\n readonly detail: T;\n initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void;\n}\n\ndeclare var CustomEvent: {\n prototype: CustomEvent;\n new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent;\n};\n\ninterface DOMError {\n readonly name: string;\n toString(): string;\n}\n\ndeclare var DOMError: {\n prototype: DOMError;\n new(): DOMError;\n};\n\ninterface DOMException {\n readonly code: number;\n readonly message: string;\n readonly name: string;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n}\n\ndeclare var DOMException: {\n prototype: DOMException;\n new(message?: string, name?: string): DOMException;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n};\n\ninterface DOMImplementation {\n createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document;\n createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;\n createHTMLDocument(title?: string): Document;\n hasFeature(feature: string | null, version: string | null): boolean;\n}\n\ndeclare var DOMImplementation: {\n prototype: DOMImplementation;\n new(): DOMImplementation;\n};\n\ninterface DOML2DeprecatedColorProperty {\n color: string;\n}\n\ninterface DOML2DeprecatedSizeProperty {\n size: number;\n}\n\ninterface DOMMatrix extends DOMMatrixReadOnly {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n m11: number;\n m12: number;\n m13: number;\n m14: number;\n m21: number;\n m22: number;\n m23: number;\n m24: number;\n m31: number;\n m32: number;\n m33: number;\n m34: number;\n m41: number;\n m42: number;\n m43: number;\n m44: number;\n invertSelf(): DOMMatrix;\n multiplySelf(other?: DOMMatrixInit): DOMMatrix;\n preMultiplySelf(other?: DOMMatrixInit): DOMMatrix;\n rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\n rotateFromVectorSelf(x?: number, y?: number): DOMMatrix;\n rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\n scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n setMatrixValue(transformList: string): DOMMatrix;\n skewXSelf(sx?: number): DOMMatrix;\n skewYSelf(sy?: number): DOMMatrix;\n translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix;\n}\n\ndeclare var DOMMatrix: {\n prototype: DOMMatrix;\n new(init?: string | number[]): DOMMatrix;\n fromFloat32Array(array32: Float32Array): DOMMatrix;\n fromFloat64Array(array64: Float64Array): DOMMatrix;\n fromMatrix(other?: DOMMatrixInit): DOMMatrix;\n};\n\ntype SVGMatrix = DOMMatrix;\ndeclare var SVGMatrix: typeof DOMMatrix;\n\ntype WebKitCSSMatrix = DOMMatrix;\ndeclare var WebKitCSSMatrix: typeof DOMMatrix;\n\ninterface DOMMatrixReadOnly {\n readonly a: number;\n readonly b: number;\n readonly c: number;\n readonly d: number;\n readonly e: number;\n readonly f: number;\n readonly is2D: boolean;\n readonly isIdentity: boolean;\n readonly m11: number;\n readonly m12: number;\n readonly m13: number;\n readonly m14: number;\n readonly m21: number;\n readonly m22: number;\n readonly m23: number;\n readonly m24: number;\n readonly m31: number;\n readonly m32: number;\n readonly m33: number;\n readonly m34: number;\n readonly m41: number;\n readonly m42: number;\n readonly m43: number;\n readonly m44: number;\n flipX(): DOMMatrix;\n flipY(): DOMMatrix;\n inverse(): DOMMatrix;\n multiply(other?: DOMMatrixInit): DOMMatrix;\n rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\n rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\n rotateFromVector(x?: number, y?: number): DOMMatrix;\n scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n skewX(sx?: number): DOMMatrix;\n skewY(sy?: number): DOMMatrix;\n toFloat32Array(): Float32Array;\n toFloat64Array(): Float64Array;\n toJSON(): any;\n transformPoint(point?: DOMPointInit): DOMPoint;\n translate(tx?: number, ty?: number, tz?: number): DOMMatrix;\n}\n\ndeclare var DOMMatrixReadOnly: {\n prototype: DOMMatrixReadOnly;\n new(init?: string | number[]): DOMMatrixReadOnly;\n fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly;\n fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly;\n fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly;\n};\n\ninterface DOMParser {\n parseFromString(source: string, mimeType: string): Document;\n}\n\ndeclare var DOMParser: {\n prototype: DOMParser;\n new(): DOMParser;\n};\n\ninterface DOMPoint extends DOMPointReadOnly {\n w: number;\n x: number;\n y: number;\n z: number;\n}\n\ndeclare var DOMPoint: {\n prototype: DOMPoint;\n new(x?: number, y?: number, z?: number, w?: number): DOMPoint;\n fromPoint(other?: DOMPointInit): DOMPoint;\n};\n\ntype SVGPoint = DOMPoint;\ndeclare var SVGPoint: typeof DOMPoint;\n\ninterface DOMPointReadOnly {\n readonly w: number;\n readonly x: number;\n readonly y: number;\n readonly z: number;\n matrixTransform(matrix?: DOMMatrixInit): DOMPoint;\n toJSON(): any;\n}\n\ndeclare var DOMPointReadOnly: {\n prototype: DOMPointReadOnly;\n new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly;\n fromPoint(other?: DOMPointInit): DOMPointReadOnly;\n};\n\ninterface DOMQuad {\n readonly p1: DOMPoint;\n readonly p2: DOMPoint;\n readonly p3: DOMPoint;\n readonly p4: DOMPoint;\n getBounds(): DOMRect;\n toJSON(): any;\n}\n\ndeclare var DOMQuad: {\n prototype: DOMQuad;\n new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad;\n fromQuad(other?: DOMQuadInit): DOMQuad;\n fromRect(other?: DOMRectInit): DOMQuad;\n};\n\ninterface DOMRect extends DOMRectReadOnly {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var DOMRect: {\n prototype: DOMRect;\n new(x?: number, y?: number, width?: number, height?: number): DOMRect;\n fromRect(other?: DOMRectInit): DOMRect;\n};\n\ntype SVGRect = DOMRect;\ndeclare var SVGRect: typeof DOMRect;\n\ninterface DOMRectList {\n readonly length: number;\n item(index: number): DOMRect | null;\n [index: number]: DOMRect;\n}\n\ndeclare var DOMRectList: {\n prototype: DOMRectList;\n new(): DOMRectList;\n};\n\ninterface DOMRectReadOnly {\n readonly bottom: number;\n readonly height: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n toJSON(): any;\n}\n\ndeclare var DOMRectReadOnly: {\n prototype: DOMRectReadOnly;\n new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly;\n fromRect(other?: DOMRectInit): DOMRectReadOnly;\n};\n\ninterface DOMSettableTokenList extends DOMTokenList {\n value: string;\n}\n\ndeclare var DOMSettableTokenList: {\n prototype: DOMSettableTokenList;\n new(): DOMSettableTokenList;\n};\n\ninterface DOMStringList {\n /**\n * Returns the number of strings in strings.\n */\n readonly length: number;\n /**\n * Returns true if strings contains string, and false\n * otherwise.\n */\n contains(string: string): boolean;\n /**\n * Returns the string with index index from strings.\n */\n item(index: number): string | null;\n [index: number]: string;\n}\n\ndeclare var DOMStringList: {\n prototype: DOMStringList;\n new(): DOMStringList;\n};\n\ninterface DOMStringMap {\n [name: string]: string | undefined;\n}\n\ndeclare var DOMStringMap: {\n prototype: DOMStringMap;\n new(): DOMStringMap;\n};\n\ninterface DOMTokenList {\n readonly length: number;\n add(...tokens: string[]): void;\n contains(token: string): boolean;\n item(index: number): string | null;\n remove(...tokens: string[]): void;\n replace(oldToken: string, newToken: string): void;\n toString(): string;\n toggle(token: string, force?: boolean): boolean;\n [index: number]: string;\n}\n\ndeclare var DOMTokenList: {\n prototype: DOMTokenList;\n new(): DOMTokenList;\n};\n\ninterface DataCue extends TextTrackCue {\n data: ArrayBuffer;\n addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var DataCue: {\n prototype: DataCue;\n new(): DataCue;\n};\n\ninterface DataTransfer {\n dropEffect: string;\n effectAllowed: string;\n readonly files: FileList;\n readonly items: DataTransferItemList;\n readonly types: string[];\n clearData(format?: string): boolean;\n getData(format: string): string;\n setData(format: string, data: string): boolean;\n setDragImage(image: Element, x: number, y: number): void;\n}\n\ndeclare var DataTransfer: {\n prototype: DataTransfer;\n new(): DataTransfer;\n};\n\ninterface DataTransferItem {\n readonly kind: string;\n readonly type: string;\n getAsFile(): File | null;\n getAsString(_callback: FunctionStringCallback | null): void;\n webkitGetAsEntry(): any;\n}\n\ndeclare var DataTransferItem: {\n prototype: DataTransferItem;\n new(): DataTransferItem;\n};\n\ninterface DataTransferItemList {\n readonly length: number;\n add(data: File): DataTransferItem | null;\n add(data: string, type: string): DataTransferItem | null;\n clear(): void;\n item(index: number): DataTransferItem;\n remove(index: number): void;\n [name: number]: DataTransferItem;\n}\n\ndeclare var DataTransferItemList: {\n prototype: DataTransferItemList;\n new(): DataTransferItemList;\n};\n\ninterface DeferredPermissionRequest {\n readonly id: number;\n readonly type: MSWebViewPermissionType;\n readonly uri: string;\n allow(): void;\n deny(): void;\n}\n\ndeclare var DeferredPermissionRequest: {\n prototype: DeferredPermissionRequest;\n new(): DeferredPermissionRequest;\n};\n\ninterface DelayNode extends AudioNode {\n readonly delayTime: AudioParam;\n}\n\ndeclare var DelayNode: {\n prototype: DelayNode;\n new(context: BaseAudioContext, options?: DelayOptions): DelayNode;\n};\n\ninterface DeviceAcceleration {\n readonly x: number | null;\n readonly y: number | null;\n readonly z: number | null;\n}\n\ndeclare var DeviceAcceleration: {\n prototype: DeviceAcceleration;\n new(): DeviceAcceleration;\n};\n\ninterface DeviceLightEvent extends Event {\n readonly value: number;\n}\n\ndeclare var DeviceLightEvent: {\n prototype: DeviceLightEvent;\n new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;\n};\n\ninterface DeviceMotionEvent extends Event {\n readonly acceleration: DeviceAcceleration | null;\n readonly accelerationIncludingGravity: DeviceAcceleration | null;\n readonly interval: number | null;\n readonly rotationRate: DeviceRotationRate | null;\n initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void;\n}\n\ndeclare var DeviceMotionEvent: {\n prototype: DeviceMotionEvent;\n new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;\n};\n\ninterface DeviceOrientationEvent extends Event {\n readonly absolute: boolean;\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void;\n}\n\ndeclare var DeviceOrientationEvent: {\n prototype: DeviceOrientationEvent;\n new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;\n};\n\ninterface DeviceRotationRate {\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n}\n\ndeclare var DeviceRotationRate: {\n prototype: DeviceRotationRate;\n new(): DeviceRotationRate;\n};\n\ninterface DhImportKeyParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyAlgorithm extends KeyAlgorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface DhKeyGenParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DocumentEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforedeactivate\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"fullscreenchange\": Event;\n \"fullscreenerror\": Event;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSManipulationStateChanged\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"mssitemodejumplistitemremoved\": Event;\n \"msthumbnailclick\": Event;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"pointerlockchange\": Event;\n \"pointerlockerror\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectionchange\": Event;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"stop\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"volumechange\": Event;\n \"waiting\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent {\n /**\n * Sets or gets the URL for the current document.\n */\n readonly URL: string;\n /**\n * Gets the URL for the document, stripped of any character encoding.\n */\n readonly URLUnencoded: string;\n /**\n * Gets the object that has the focus when the parent document has focus.\n */\n readonly activeElement: Element;\n /**\n * Sets or gets the color of all active links in the document.\n */\n /** @deprecated */\n alinkColor: string;\n /**\n * Returns a reference to the collection of elements contained by the object.\n */\n /** @deprecated */\n readonly all: HTMLAllCollection;\n /**\n * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order.\n */\n /** @deprecated */\n readonly anchors: HTMLCollectionOf;\n /**\n * Retrieves a collection of all applet objects in the document.\n */\n /** @deprecated */\n readonly applets: HTMLCollectionOf;\n /**\n * Deprecated. Sets or retrieves a value that indicates the background color behind the object.\n */\n /** @deprecated */\n bgColor: string;\n /**\n * Specifies the beginning and end of the document body.\n */\n body: HTMLElement;\n readonly characterSet: string;\n /**\n * Gets or sets the character set used to encode the object.\n */\n charset: string;\n /**\n * Gets a value that indicates whether standards-compliant mode is switched on for the object.\n */\n readonly compatMode: string;\n cookie: string;\n readonly currentScript: HTMLScriptElement | SVGScriptElement | null;\n readonly defaultView: Window;\n /**\n * Sets or gets a value that indicates whether the document can be edited.\n */\n designMode: string;\n /**\n * Sets or retrieves a value that indicates the reading order of the object.\n */\n dir: string;\n /**\n * Gets an object representing the document type declaration associated with the current document.\n */\n readonly doctype: DocumentType;\n /**\n * Gets a reference to the root node of the document.\n */\n readonly documentElement: HTMLElement;\n /**\n * Sets or gets the security domain of the document.\n */\n domain: string;\n /**\n * Retrieves a collection of all embed objects in the document.\n */\n readonly embeds: HTMLCollectionOf;\n /**\n * Sets or gets the foreground (text) color of the document.\n */\n /** @deprecated */\n fgColor: string;\n /**\n * Retrieves a collection, in source order, of all form objects in the document.\n */\n readonly forms: HTMLCollectionOf;\n readonly fullscreenElement: Element | null;\n readonly fullscreenEnabled: boolean;\n readonly head: HTMLHeadElement;\n readonly hidden: boolean;\n /**\n * Retrieves a collection, in source order, of img objects in the document.\n */\n readonly images: HTMLCollectionOf;\n /**\n * Gets the implementation object of the current document.\n */\n readonly implementation: DOMImplementation;\n /**\n * Returns the character encoding used to create the webpage that is loaded into the document object.\n */\n readonly inputEncoding: string | null;\n /**\n * Gets the date that the page was last modified, if the page supplies one.\n */\n readonly lastModified: string;\n /**\n * Sets or gets the color of the document links.\n */\n /** @deprecated */\n linkColor: string;\n /**\n * Retrieves a collection of all a objects that specify the href property and all area objects in the document.\n */\n readonly links: HTMLCollectionOf;\n /**\n * Contains information about the current URL.\n */\n location: Location;\n msCSSOMElementFloatMetrics: boolean;\n msCapsLockWarningOff: boolean;\n /**\n * Fires when the user aborts the download.\n * @param ev The event.\n */\n onabort: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the object is set as the active element.\n * @param ev The event.\n */\n onactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the object is set as the active element.\n * @param ev The event.\n */\n onbeforeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the activeElement is changed from the current object to another object in the parent document.\n * @param ev The event.\n */\n onbeforedeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the object loses the input focus.\n * @param ev The focus event.\n */\n onblur: ((this: Document, ev: FocusEvent) => any) | null;\n /**\n * Occurs when playback is possible, but would require further buffering.\n * @param ev The event.\n */\n oncanplay: ((this: Document, ev: Event) => any) | null;\n oncanplaythrough: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the contents of the object or selection have changed.\n * @param ev The event.\n */\n onchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the left mouse button on the object\n * @param ev The mouse event.\n */\n onclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user clicks the right mouse button in the client area, opening the context menu.\n * @param ev The mouse event.\n */\n oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null;\n /**\n * Fires when the user double-clicks the object.\n * @param ev The mouse event.\n */\n ondblclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the activeElement is changed from the current object to another object in the parent document.\n * @param ev The UI Event\n */\n ondeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires on the source object continuously during a drag operation.\n * @param ev The event.\n */\n ondrag: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user releases the mouse at the close of a drag operation.\n * @param ev The event.\n */\n ondragend: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element when the user drags the object to a valid drop target.\n * @param ev The drag event.\n */\n ondragenter: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.\n * @param ev The drag event.\n */\n ondragleave: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element continuously while the user drags the object over a valid drop target.\n * @param ev The event.\n */\n ondragover: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user starts to drag a text selection or selected object.\n * @param ev The event.\n */\n ondragstart: ((this: Document, ev: DragEvent) => any) | null;\n ondrop: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Occurs when the duration attribute is updated.\n * @param ev The event.\n */\n ondurationchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the media element is reset to its initial state.\n * @param ev The event.\n */\n onemptied: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the end of playback is reached.\n * @param ev The event\n */\n onended: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when an error occurs during object loading.\n * @param ev The event.\n */\n onerror: ((this: Document, ev: ErrorEvent) => any) | null;\n /**\n * Fires when the object receives focus.\n * @param ev The event.\n */\n onfocus: ((this: Document, ev: FocusEvent) => any) | null;\n onfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onfullscreenerror: ((this: Document, ev: Event) => any) | null;\n oninput: ((this: Document, ev: Event) => any) | null;\n oninvalid: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user presses a key.\n * @param ev The keyboard event\n */\n onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user presses an alphanumeric key.\n * @param ev The event.\n */\n onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user releases a key.\n * @param ev The keyboard event\n */\n onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires immediately after the browser loads the object.\n * @param ev The event.\n */\n onload: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when media data is loaded at the current playback position.\n * @param ev The event.\n */\n onloadeddata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the duration and dimensions of the media have been determined.\n * @param ev The event.\n */\n onloadedmetadata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when Internet Explorer begins looking for media data.\n * @param ev The event.\n */\n onloadstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the object with either mouse button.\n * @param ev The mouse event.\n */\n onmousedown: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse over the object.\n * @param ev The mouse event.\n */\n onmousemove: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer outside the boundaries of the object.\n * @param ev The mouse event.\n */\n onmouseout: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer into the object.\n * @param ev The mouse event.\n */\n onmouseover: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user releases a mouse button while the mouse is over the object.\n * @param ev The mouse event.\n */\n onmouseup: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the wheel button is rotated.\n * @param ev The mouse event\n */\n onmousewheel: ((this: Document, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: Document, ev: Event) => any) | null;\n onmsgesturechange: ((this: Document, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null;\n onmsgestureend: ((this: Document, ev: Event) => any) | null;\n onmsgesturehold: ((this: Document, ev: Event) => any) | null;\n onmsgesturestart: ((this: Document, ev: Event) => any) | null;\n onmsgesturetap: ((this: Document, ev: Event) => any) | null;\n onmsinertiastart: ((this: Document, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null;\n onmspointercancel: ((this: Document, ev: Event) => any) | null;\n onmspointerdown: ((this: Document, ev: Event) => any) | null;\n onmspointerenter: ((this: Document, ev: Event) => any) | null;\n onmspointerleave: ((this: Document, ev: Event) => any) | null;\n onmspointermove: ((this: Document, ev: Event) => any) | null;\n onmspointerout: ((this: Document, ev: Event) => any) | null;\n onmspointerover: ((this: Document, ev: Event) => any) | null;\n onmspointerup: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when an item is removed from a Jump List of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmsthumbnailclick: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback is paused.\n * @param ev The event.\n */\n onpause: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the play method is requested.\n * @param ev The event.\n */\n onplay: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the audio or video has started playing.\n * @param ev The event.\n */\n onplaying: ((this: Document, ev: Event) => any) | null;\n onpointerlockchange: ((this: Document, ev: Event) => any) | null;\n onpointerlockerror: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate progress while downloading media data.\n * @param ev The event.\n */\n onprogress: ((this: Document, ev: ProgressEvent) => any) | null;\n /**\n * Occurs when the playback rate is increased or decreased.\n * @param ev The event.\n */\n onratechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the state of the object has changed.\n * @param ev The event\n */\n onreadystatechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user resets a form.\n * @param ev The event.\n */\n onreset: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user repositions the scroll box in the scroll bar on the object.\n * @param ev The event.\n */\n onscroll: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Occurs when the seek operation ends.\n * @param ev The event.\n */\n onseeked: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the current playback position is moved.\n * @param ev The event.\n */\n onseeking: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the current selection changes.\n * @param ev The event.\n */\n onselect: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the selection state of a document changes.\n * @param ev The event.\n */\n onselectionchange: ((this: Document, ev: Event) => any) | null;\n onselectstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the download has stopped.\n * @param ev The event.\n */\n onstalled: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the Stop button or leaves the Web page.\n * @param ev The event.\n */\n onstop: ((this: Document, ev: Event) => any) | null;\n onsubmit: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs if the load operation has been intentionally halted.\n * @param ev The event.\n */\n onsuspend: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate the current playback position.\n * @param ev The event.\n */\n ontimeupdate: ((this: Document, ev: Event) => any) | null;\n onvisibilitychange: (this: Document, ev: Event) => any;\n /**\n * Occurs when the volume is changed, or playback is muted or unmuted.\n * @param ev The event.\n */\n onvolumechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback stops because the next frame of a video resource is not available.\n * @param ev The event.\n */\n onwaiting: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null;\n readonly plugins: HTMLCollectionOf;\n readonly pointerLockElement: Element;\n /**\n * Retrieves a value that indicates the current state of the object.\n */\n readonly readyState: DocumentReadyState;\n /**\n * Gets the URL of the location that referred the user to the current page.\n */\n readonly referrer: string;\n /**\n * Gets the root svg element in the document hierarchy.\n */\n readonly rootElement: SVGSVGElement;\n /**\n * Retrieves a collection of all script objects in the document.\n */\n readonly scripts: HTMLCollectionOf;\n readonly scrollingElement: Element | null;\n /**\n * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document.\n */\n readonly styleSheets: StyleSheetList;\n readonly timeline: DocumentTimeline;\n /**\n * Contains the title of the document.\n */\n title: string;\n readonly visibilityState: VisibilityState;\n /**\n * Sets or gets the color of the links that the user has visited.\n */\n /** @deprecated */\n vlinkColor: string;\n readonly webkitCurrentFullScreenElement: Element | null;\n readonly webkitFullscreenElement: Element | null;\n readonly webkitFullscreenEnabled: boolean;\n readonly webkitIsFullScreen: boolean;\n readonly xmlEncoding: string | null;\n xmlStandalone: boolean;\n /**\n * Gets or sets the version attribute specified in the declaration of an XML document.\n */\n xmlVersion: string | null;\n adoptNode(source: T): T;\n /** @deprecated */\n captureEvents(): void;\n caretRangeFromPoint(x: number, y: number): Range;\n /** @deprecated */\n clear(): void;\n /**\n * Closes an output stream and forces the sent data to display.\n */\n close(): void;\n /**\n * Creates an attribute object with a specified name.\n * @param name String that sets the attribute object's name.\n */\n createAttribute(name: string): Attr;\n createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;\n createCDATASection(data: string): CDATASection;\n /**\n * Creates a comment object with the specified data.\n * @param data Sets the comment object's data.\n */\n createComment(data: string): Comment;\n /**\n * Creates a new document.\n */\n createDocumentFragment(): DocumentFragment;\n /**\n * Creates an instance of the element for the specified tag.\n * @param tagName The name of an element.\n */\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];\n createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", qualifiedName: string): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"a\"): SVGAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"circle\"): SVGCircleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"clipPath\"): SVGClipPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"componentTransferFunction\"): SVGComponentTransferFunctionElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"defs\"): SVGDefsElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"desc\"): SVGDescElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"ellipse\"): SVGEllipseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feBlend\"): SVGFEBlendElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feColorMatrix\"): SVGFEColorMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComponentTransfer\"): SVGFEComponentTransferElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComposite\"): SVGFECompositeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feConvolveMatrix\"): SVGFEConvolveMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDiffuseLighting\"): SVGFEDiffuseLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDisplacementMap\"): SVGFEDisplacementMapElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDistantLight\"): SVGFEDistantLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFlood\"): SVGFEFloodElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncA\"): SVGFEFuncAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncB\"): SVGFEFuncBElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncG\"): SVGFEFuncGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncR\"): SVGFEFuncRElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feGaussianBlur\"): SVGFEGaussianBlurElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feImage\"): SVGFEImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMerge\"): SVGFEMergeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMergeNode\"): SVGFEMergeNodeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMorphology\"): SVGFEMorphologyElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feOffset\"): SVGFEOffsetElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"fePointLight\"): SVGFEPointLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpecularLighting\"): SVGFESpecularLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpotLight\"): SVGFESpotLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTile\"): SVGFETileElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTurbulence\"): SVGFETurbulenceElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"filter\"): SVGFilterElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"foreignObject\"): SVGForeignObjectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"g\"): SVGGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"image\"): SVGImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"gradient\"): SVGGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"line\"): SVGLineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"linearGradient\"): SVGLinearGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"marker\"): SVGMarkerElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"mask\"): SVGMaskElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"path\"): SVGPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"metadata\"): SVGMetadataElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"pattern\"): SVGPatternElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polygon\"): SVGPolygonElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polyline\"): SVGPolylineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"radialGradient\"): SVGRadialGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"rect\"): SVGRectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"svg\"): SVGSVGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"script\"): SVGScriptElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"stop\"): SVGStopElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"style\"): SVGStyleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"switch\"): SVGSwitchElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"symbol\"): SVGSymbolElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"tspan\"): SVGTSpanElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textContent\"): SVGTextContentElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"text\"): SVGTextElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPath\"): SVGTextPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPositioning\"): SVGTextPositioningElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"title\"): SVGTitleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"use\"): SVGUseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"view\"): SVGViewElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: string): SVGElement;\n createElementNS(namespaceURI: string | null, qualifiedName: string): Element;\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver: Node): XPathNSResolver;\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list\n * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator;\n createProcessingInstruction(target: string, data: string): ProcessingInstruction;\n /**\n * Returns an empty range object that has both of its boundary points positioned at the beginning of the document.\n */\n createRange(): Range;\n /**\n * Creates a text string from the specified value.\n * @param data String that specifies the nodeValue property of the text node.\n */\n createTextNode(data: string): Text;\n createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch;\n createTouchList(...touches: Touch[]): TouchList;\n /**\n * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow.\n * @param filter A custom NodeFilter function to use.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker;\n /**\n * Returns the element for the specified x coordinate and the specified y coordinate.\n * @param x The x-offset\n * @param y The y-offset\n */\n elementFromPoint(x: number, y: number): Element;\n elementsFromPoint(x: number, y: number): Element[];\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n /**\n * Executes a command on the current document, current selection, or the given range.\n * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.\n * @param showUI Display the user interface, defaults to false.\n * @param value Value to assign.\n */\n execCommand(commandId: string, showUI?: boolean, value?: any): boolean;\n /**\n * Displays help information for the given command identifier.\n * @param commandId Displays help information for the given command identifier.\n */\n execCommandShowHelp(commandId: string): boolean;\n exitFullscreen(): void;\n exitPointerLock(): void;\n /**\n * Causes the element to receive the focus and executes the code specified by the onfocus event.\n */\n /** @deprecated */\n focus(): void;\n getAnimations(): Animation[];\n /**\n * Returns a reference to the first object with the specified value of the ID or NAME attribute.\n * @param elementId String that specifies the ID value. Case-insensitive.\n */\n getElementById(elementId: string): HTMLElement | null;\n getElementsByClassName(classNames: string): HTMLCollectionOf;\n /**\n * Gets a collection of objects based on the value of the NAME or ID attribute.\n * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.\n */\n getElementsByName(elementName: string): NodeListOf;\n /**\n * Retrieves a collection of objects based on the specified element name.\n * @param name Specifies the name of an element.\n */\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n /**\n * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.\n */\n getSelection(): Selection;\n /**\n * Gets a value indicating whether the object currently has focus.\n */\n hasFocus(): boolean;\n importNode(importedNode: T, deep: boolean): T;\n msElementsFromPoint(x: number, y: number): NodeListOf;\n msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf;\n /**\n * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method.\n * @param url Specifies a MIME type for the document.\n * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.\n * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, \"fullscreen=yes, toolbar=yes\"). The following values are supported.\n * @param replace Specifies whether the existing entry for the document is replaced in the history list.\n */\n open(url?: string, name?: string, features?: string, replace?: boolean): Document;\n /**\n * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.\n * @param commandId Specifies a command identifier.\n */\n queryCommandEnabled(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the specified command is in the indeterminate state.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandIndeterm(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates the current state of the command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandState(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the current command is supported on the current range.\n * @param commandId Specifies a command identifier.\n */\n queryCommandSupported(commandId: string): boolean;\n /**\n * Retrieves the string associated with a command.\n * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers.\n */\n queryCommandText(commandId: string): string;\n /**\n * Returns the current value of the document, range, or current selection for the given command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandValue(commandId: string): string;\n /** @deprecated */\n releaseEvents(): void;\n updateSettings(): void;\n webkitCancelFullScreen(): void;\n webkitExitFullscreen(): void;\n /**\n * Writes one or more HTML expressions to a document in the specified window.\n * @param content Specifies the text and HTML tags to write.\n */\n write(...content: string[]): void;\n /**\n * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window.\n * @param content The text and HTML tags to write.\n */\n writeln(...content: string[]): void;\n addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Document: {\n prototype: Document;\n new(): Document;\n};\n\ninterface DocumentEvent {\n createEvent(eventInterface: \"AnimationEvent\"): AnimationEvent;\n createEvent(eventInterface: \"AnimationPlaybackEvent\"): AnimationPlaybackEvent;\n createEvent(eventInterface: \"AudioProcessingEvent\"): AudioProcessingEvent;\n createEvent(eventInterface: \"BeforeUnloadEvent\"): BeforeUnloadEvent;\n createEvent(eventInterface: \"ClipboardEvent\"): ClipboardEvent;\n createEvent(eventInterface: \"CloseEvent\"): CloseEvent;\n createEvent(eventInterface: \"CompositionEvent\"): CompositionEvent;\n createEvent(eventInterface: \"CustomEvent\"): CustomEvent;\n createEvent(eventInterface: \"DeviceLightEvent\"): DeviceLightEvent;\n createEvent(eventInterface: \"DeviceMotionEvent\"): DeviceMotionEvent;\n createEvent(eventInterface: \"DeviceOrientationEvent\"): DeviceOrientationEvent;\n createEvent(eventInterface: \"DragEvent\"): DragEvent;\n createEvent(eventInterface: \"ErrorEvent\"): ErrorEvent;\n createEvent(eventInterface: \"Event\"): Event;\n createEvent(eventInterface: \"Events\"): Event;\n createEvent(eventInterface: \"FocusEvent\"): FocusEvent;\n createEvent(eventInterface: \"FocusNavigationEvent\"): FocusNavigationEvent;\n createEvent(eventInterface: \"GamepadEvent\"): GamepadEvent;\n createEvent(eventInterface: \"HashChangeEvent\"): HashChangeEvent;\n createEvent(eventInterface: \"IDBVersionChangeEvent\"): IDBVersionChangeEvent;\n createEvent(eventInterface: \"KeyboardEvent\"): KeyboardEvent;\n createEvent(eventInterface: \"ListeningStateChangedEvent\"): ListeningStateChangedEvent;\n createEvent(eventInterface: \"MSDCCEvent\"): MSDCCEvent;\n createEvent(eventInterface: \"MSDSHEvent\"): MSDSHEvent;\n createEvent(eventInterface: \"MSMediaKeyMessageEvent\"): MSMediaKeyMessageEvent;\n createEvent(eventInterface: \"MSMediaKeyNeededEvent\"): MSMediaKeyNeededEvent;\n createEvent(eventInterface: \"MediaEncryptedEvent\"): MediaEncryptedEvent;\n createEvent(eventInterface: \"MediaKeyMessageEvent\"): MediaKeyMessageEvent;\n createEvent(eventInterface: \"MediaStreamErrorEvent\"): MediaStreamErrorEvent;\n createEvent(eventInterface: \"MediaStreamEvent\"): MediaStreamEvent;\n createEvent(eventInterface: \"MediaStreamTrackEvent\"): MediaStreamTrackEvent;\n createEvent(eventInterface: \"MessageEvent\"): MessageEvent;\n createEvent(eventInterface: \"MouseEvent\"): MouseEvent;\n createEvent(eventInterface: \"MouseEvents\"): MouseEvent;\n createEvent(eventInterface: \"MutationEvent\"): MutationEvent;\n createEvent(eventInterface: \"MutationEvents\"): MutationEvent;\n createEvent(eventInterface: \"OfflineAudioCompletionEvent\"): OfflineAudioCompletionEvent;\n createEvent(eventInterface: \"OverflowEvent\"): OverflowEvent;\n createEvent(eventInterface: \"PageTransitionEvent\"): PageTransitionEvent;\n createEvent(eventInterface: \"PaymentRequestUpdateEvent\"): PaymentRequestUpdateEvent;\n createEvent(eventInterface: \"PermissionRequestedEvent\"): PermissionRequestedEvent;\n createEvent(eventInterface: \"PointerEvent\"): PointerEvent;\n createEvent(eventInterface: \"PopStateEvent\"): PopStateEvent;\n createEvent(eventInterface: \"ProgressEvent\"): ProgressEvent;\n createEvent(eventInterface: \"PromiseRejectionEvent\"): PromiseRejectionEvent;\n createEvent(eventInterface: \"RTCDTMFToneChangeEvent\"): RTCDTMFToneChangeEvent;\n createEvent(eventInterface: \"RTCDataChannelEvent\"): RTCDataChannelEvent;\n createEvent(eventInterface: \"RTCDtlsTransportStateChangedEvent\"): RTCDtlsTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCErrorEvent\"): RTCErrorEvent;\n createEvent(eventInterface: \"RTCIceCandidatePairChangedEvent\"): RTCIceCandidatePairChangedEvent;\n createEvent(eventInterface: \"RTCIceGathererEvent\"): RTCIceGathererEvent;\n createEvent(eventInterface: \"RTCIceTransportStateChangedEvent\"): RTCIceTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceErrorEvent\"): RTCPeerConnectionIceErrorEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceEvent\"): RTCPeerConnectionIceEvent;\n createEvent(eventInterface: \"RTCSsrcConflictEvent\"): RTCSsrcConflictEvent;\n createEvent(eventInterface: \"RTCStatsEvent\"): RTCStatsEvent;\n createEvent(eventInterface: \"RTCTrackEvent\"): RTCTrackEvent;\n createEvent(eventInterface: \"SVGZoomEvent\"): SVGZoomEvent;\n createEvent(eventInterface: \"SVGZoomEvents\"): SVGZoomEvent;\n createEvent(eventInterface: \"SecurityPolicyViolationEvent\"): SecurityPolicyViolationEvent;\n createEvent(eventInterface: \"ServiceWorkerMessageEvent\"): ServiceWorkerMessageEvent;\n createEvent(eventInterface: \"SpeechSynthesisEvent\"): SpeechSynthesisEvent;\n createEvent(eventInterface: \"StorageEvent\"): StorageEvent;\n createEvent(eventInterface: \"TextEvent\"): TextEvent;\n createEvent(eventInterface: \"TouchEvent\"): TouchEvent;\n createEvent(eventInterface: \"TrackEvent\"): TrackEvent;\n createEvent(eventInterface: \"TransitionEvent\"): TransitionEvent;\n createEvent(eventInterface: \"UIEvent\"): UIEvent;\n createEvent(eventInterface: \"UIEvents\"): UIEvent;\n createEvent(eventInterface: \"VRDisplayEvent\"): VRDisplayEvent;\n createEvent(eventInterface: \"VRDisplayEvent \"): VRDisplayEvent ;\n createEvent(eventInterface: \"WebGLContextEvent\"): WebGLContextEvent;\n createEvent(eventInterface: \"WheelEvent\"): WheelEvent;\n createEvent(eventInterface: string): Event;\n}\n\ninterface DocumentFragment extends Node, ParentNode {\n getElementById(elementId: string): HTMLElement | null;\n}\n\ndeclare var DocumentFragment: {\n prototype: DocumentFragment;\n new(): DocumentFragment;\n};\n\ninterface DocumentOrShadowRoot {\n readonly activeElement: Element | null;\n readonly styleSheets: StyleSheetList;\n elementFromPoint(x: number, y: number): Element | null;\n elementsFromPoint(x: number, y: number): Element[];\n getSelection(): Selection | null;\n}\n\ninterface DocumentTimeline extends AnimationTimeline {\n}\n\ndeclare var DocumentTimeline: {\n prototype: DocumentTimeline;\n new(options?: DocumentTimelineOptions): DocumentTimeline;\n};\n\ninterface DocumentType extends Node, ChildNode {\n readonly entities: NamedNodeMap;\n readonly internalSubset: string | null;\n readonly name: string;\n readonly notations: NamedNodeMap;\n readonly publicId: string;\n readonly systemId: string;\n}\n\ndeclare var DocumentType: {\n prototype: DocumentType;\n new(): DocumentType;\n};\n\ninterface DragEvent extends MouseEvent {\n readonly dataTransfer: DataTransfer;\n initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void;\n msConvertURL(file: File, targetType: string, targetURL?: string): void;\n}\n\ndeclare var DragEvent: {\n prototype: DragEvent;\n new(type: \"drag\" | \"dragend\" | \"dragenter\" | \"dragexit\" | \"dragleave\" | \"dragover\" | \"dragstart\" | \"drop\", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent;\n};\n\ninterface DynamicsCompressorNode extends AudioNode {\n readonly attack: AudioParam;\n readonly knee: AudioParam;\n readonly ratio: AudioParam;\n readonly reduction: number;\n readonly release: AudioParam;\n readonly threshold: AudioParam;\n}\n\ndeclare var DynamicsCompressorNode: {\n prototype: DynamicsCompressorNode;\n new(context: BaseAudioContext, options?: DynamicsCompressorOptions): DynamicsCompressorNode;\n};\n\ninterface EXT_blend_minmax {\n readonly MAX_EXT: number;\n readonly MIN_EXT: number;\n}\n\ninterface EXT_frag_depth {\n}\n\ninterface EXT_sRGB {\n readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number;\n readonly SRGB8_ALPHA8_EXT: number;\n readonly SRGB_ALPHA_EXT: number;\n readonly SRGB_EXT: number;\n}\n\ninterface EXT_shader_texture_lod {\n}\n\ninterface EXT_texture_filter_anisotropic {\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n}\n\ndeclare var EXT_texture_filter_anisotropic: {\n prototype: EXT_texture_filter_anisotropic;\n new(): EXT_texture_filter_anisotropic;\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n};\n\ninterface ElementEventMap extends GlobalEventHandlersEventMap {\n \"ariarequest\": Event;\n \"command\": Event;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSGotPointerCapture\": Event;\n \"MSInertiaStart\": Event;\n \"MSLostPointerCapture\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode, Animatable {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly attributes: NamedNodeMap;\n readonly classList: DOMTokenList;\n className: string;\n readonly clientHeight: number;\n readonly clientLeft: number;\n readonly clientTop: number;\n readonly clientWidth: number;\n id: string;\n innerHTML: string;\n msContentZoomFactor: number;\n readonly msRegionOverflow: string;\n onariarequest: ((this: Element, ev: Event) => any) | null;\n oncommand: ((this: Element, ev: Event) => any) | null;\n onmsgesturechange: ((this: Element, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null;\n onmsgestureend: ((this: Element, ev: Event) => any) | null;\n onmsgesturehold: ((this: Element, ev: Event) => any) | null;\n onmsgesturestart: ((this: Element, ev: Event) => any) | null;\n onmsgesturetap: ((this: Element, ev: Event) => any) | null;\n onmsgotpointercapture: ((this: Element, ev: Event) => any) | null;\n onmsinertiastart: ((this: Element, ev: Event) => any) | null;\n onmslostpointercapture: ((this: Element, ev: Event) => any) | null;\n onmspointercancel: ((this: Element, ev: Event) => any) | null;\n onmspointerdown: ((this: Element, ev: Event) => any) | null;\n onmspointerenter: ((this: Element, ev: Event) => any) | null;\n onmspointerleave: ((this: Element, ev: Event) => any) | null;\n onmspointermove: ((this: Element, ev: Event) => any) | null;\n onmspointerout: ((this: Element, ev: Event) => any) | null;\n onmspointerover: ((this: Element, ev: Event) => any) | null;\n onmspointerup: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null;\n outerHTML: string;\n readonly prefix: string | null;\n readonly scrollHeight: number;\n scrollLeft: number;\n scrollTop: number;\n readonly scrollWidth: number;\n readonly shadowRoot: ShadowRoot | null;\n slot: string;\n readonly tagName: string;\n attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;\n closest(selector: K): HTMLElementTagNameMap[K] | null;\n closest(selector: K): SVGElementTagNameMap[K] | null;\n closest(selector: string): Element | null;\n getAttribute(qualifiedName: string): string | null;\n getAttributeNS(namespaceURI: string, localName: string): string;\n getAttributeNode(name: string): Attr | null;\n getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n getElementsByClassName(classNames: string): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n hasAttribute(name: string): boolean;\n hasAttributeNS(namespaceURI: string, localName: string): boolean;\n hasAttributes(): boolean;\n hasPointerCapture(pointerId: number): boolean;\n insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null;\n insertAdjacentHTML(where: InsertPosition, html: string): void;\n insertAdjacentText(where: InsertPosition, text: string): void;\n matches(selectors: string): boolean;\n msGetRegionContent(): any;\n msGetUntransformedBounds(): ClientRect;\n msMatchesSelector(selectors: string): boolean;\n msReleasePointerCapture(pointerId: number): void;\n msSetPointerCapture(pointerId: number): void;\n msZoomTo(args: MsZoomToOptions): void;\n releasePointerCapture(pointerId: number): void;\n removeAttribute(qualifiedName: string): void;\n removeAttributeNS(namespaceURI: string, localName: string): void;\n removeAttributeNode(oldAttr: Attr): Attr;\n requestFullscreen(): void;\n requestPointerLock(): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x: number, y: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x: number, y: number): void;\n scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x: number, y: number): void;\n setAttribute(qualifiedName: string, value: string): void;\n setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;\n setAttributeNode(newAttr: Attr): Attr;\n setAttributeNodeNS(newAttr: Attr): Attr;\n setPointerCapture(pointerId: number): void;\n webkitMatchesSelector(selectors: string): boolean;\n webkitRequestFullScreen(): void;\n webkitRequestFullscreen(): void;\n addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Element: {\n prototype: Element;\n new(): Element;\n};\n\ninterface ElementCSSInlineStyle {\n readonly style: CSSStyleDeclaration;\n}\n\ninterface ElementCreationOptions {\n is?: string;\n}\n\ninterface ElementDefinitionOptions {\n extends: string;\n}\n\ninterface ElementTraversal {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n readonly nextElementSibling: Element | null;\n readonly previousElementSibling: Element | null;\n}\n\ninterface ErrorEvent extends Event {\n readonly colno: number;\n readonly error: any;\n readonly filename: string;\n readonly lineno: number;\n readonly message: string;\n initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;\n}\n\ndeclare var ErrorEvent: {\n prototype: ErrorEvent;\n new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent;\n};\n\ninterface Event {\n readonly bubbles: boolean;\n cancelBubble: boolean;\n readonly cancelable: boolean;\n readonly composed: boolean;\n readonly currentTarget: EventTarget | null;\n readonly defaultPrevented: boolean;\n readonly eventPhase: number;\n readonly isTrusted: boolean;\n returnValue: boolean;\n readonly srcElement: Element | null;\n readonly target: EventTarget | null;\n readonly timeStamp: number;\n readonly type: string;\n deepPath(): EventTarget[];\n initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;\n preventDefault(): void;\n stopImmediatePropagation(): void;\n stopPropagation(): void;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n}\n\ndeclare var Event: {\n prototype: Event;\n new(typeArg: string, eventInitDict?: EventInit): Event;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n};\n\ninterface EventListenerObject {\n handleEvent(evt: Event): void;\n}\n\ninterface EventSource extends EventTarget {\n readonly CLOSED: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n onerror: (evt: MessageEvent) => any;\n onmessage: (evt: MessageEvent) => any;\n onopen: (evt: MessageEvent) => any;\n readonly readyState: number;\n readonly url: string;\n readonly withCredentials: boolean;\n close(): void;\n}\n\ndeclare var EventSource: {\n prototype: EventSource;\n new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;\n};\n\ninterface EventSourceInit {\n readonly withCredentials: boolean;\n}\n\ninterface EventTarget {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;\n dispatchEvent(evt: Event): boolean;\n removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;\n}\n\ndeclare var EventTarget: {\n prototype: EventTarget;\n new(): EventTarget;\n};\n\ninterface ExtensionScriptApis {\n extensionIdToShortId(extensionId: string): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n genericWebRuntimeCallout(to: any, from: any, payload: string): void;\n getExtensionId(): string;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericPersistentCallbackHandler(callbackHandler: Function): void;\n registerWebRuntimeCallbackHandler(handler: Function): any;\n}\n\ndeclare var ExtensionScriptApis: {\n prototype: ExtensionScriptApis;\n new(): ExtensionScriptApis;\n};\n\ninterface External {\n /** @deprecated */\n AddSearchProvider(): void;\n /** @deprecated */\n IsSearchProviderInstalled(): void;\n}\n\ninterface File extends Blob {\n readonly lastModified: number;\n readonly name: string;\n}\n\ndeclare var File: {\n prototype: File;\n new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;\n};\n\ninterface FileList {\n readonly length: number;\n item(index: number): File | null;\n [index: number]: File;\n}\n\ndeclare var FileList: {\n prototype: FileList;\n new(): FileList;\n};\n\ninterface FileReaderEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n}\n\ninterface FileReader extends EventTarget {\n readonly error: DOMException | null;\n onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onerror: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onload: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: string | ArrayBuffer | null;\n abort(): void;\n readAsArrayBuffer(blob: Blob): void;\n readAsBinaryString(blob: Blob): void;\n readAsDataURL(blob: Blob): void;\n readAsText(blob: Blob, label?: string): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var FileReader: {\n prototype: FileReader;\n new(): FileReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface FocusEvent extends UIEvent {\n readonly relatedTarget: EventTarget;\n initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void;\n}\n\ndeclare var FocusEvent: {\n prototype: FocusEvent;\n new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent;\n};\n\ninterface FocusNavigationEvent extends Event {\n readonly navigationReason: NavigationReason;\n readonly originHeight: number;\n readonly originLeft: number;\n readonly originTop: number;\n readonly originWidth: number;\n requestFocus(): void;\n}\n\ndeclare var FocusNavigationEvent: {\n prototype: FocusNavigationEvent;\n new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent;\n};\n\ninterface FormData {\n append(name: string, value: string | Blob, fileName?: string): void;\n delete(name: string): void;\n get(name: string): FormDataEntryValue | null;\n getAll(name: string): FormDataEntryValue[];\n has(name: string): boolean;\n set(name: string, value: string | Blob, fileName?: string): void;\n forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;\n}\n\ndeclare var FormData: {\n prototype: FormData;\n new(form?: HTMLFormElement): FormData;\n};\n\ninterface GainNode extends AudioNode {\n readonly gain: AudioParam;\n}\n\ndeclare var GainNode: {\n prototype: GainNode;\n new(context: BaseAudioContext, options?: GainOptions): GainNode;\n};\n\ninterface Gamepad {\n readonly axes: number[];\n readonly buttons: GamepadButton[];\n readonly connected: boolean;\n readonly displayId: number;\n readonly hand: GamepadHand;\n readonly hapticActuators: GamepadHapticActuator[];\n readonly id: string;\n readonly index: number;\n readonly mapping: GamepadMappingType;\n readonly pose: GamepadPose | null;\n readonly timestamp: number;\n}\n\ndeclare var Gamepad: {\n prototype: Gamepad;\n new(): Gamepad;\n};\n\ninterface GamepadButton {\n readonly pressed: boolean;\n readonly touched: boolean;\n readonly value: number;\n}\n\ndeclare var GamepadButton: {\n prototype: GamepadButton;\n new(): GamepadButton;\n};\n\ninterface GamepadEvent extends Event {\n readonly gamepad: Gamepad;\n}\n\ndeclare var GamepadEvent: {\n prototype: GamepadEvent;\n new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent;\n};\n\ninterface GamepadHapticActuator {\n readonly type: GamepadHapticActuatorType;\n pulse(value: number, duration: number): Promise;\n}\n\ndeclare var GamepadHapticActuator: {\n prototype: GamepadHapticActuator;\n new(): GamepadHapticActuator;\n};\n\ninterface GamepadPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n}\n\ndeclare var GamepadPose: {\n prototype: GamepadPose;\n new(): GamepadPose;\n};\n\ninterface Geolocation {\n clearWatch(watchId: number): void;\n getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;\n watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;\n}\n\ninterface GetSVGDocument {\n getSVGDocument(): Document;\n}\n\ninterface GlobalEventHandlersEventMap {\n \"animationcancel\": AnimationEvent;\n \"animationend\": AnimationEvent;\n \"animationiteration\": AnimationEvent;\n \"animationstart\": AnimationEvent;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"pointercancel\": PointerEvent;\n \"pointerdown\": PointerEvent;\n \"pointerenter\": PointerEvent;\n \"pointerleave\": PointerEvent;\n \"pointermove\": PointerEvent;\n \"pointerout\": PointerEvent;\n \"pointerover\": PointerEvent;\n \"pointerup\": PointerEvent;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"transitioncancel\": TransitionEvent;\n \"transitionend\": TransitionEvent;\n \"transitionrun\": TransitionEvent;\n \"transitionstart\": TransitionEvent;\n \"wheel\": WheelEvent;\n}\n\ninterface GlobalEventHandlers {\n onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n ontouchcancel: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchend: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchmove: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchstart: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontransitioncancel: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null;\n addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface GlobalFetch {\n fetch(input?: Request | string, init?: RequestInit): Promise;\n}\n\ninterface HTMLAllCollection {\n /**\n * Returns the number of elements in the collection.\n */\n readonly length: number;\n /**\n * element = collection(index)\n */\n item(nameOrIndex?: string): HTMLCollection | Element | null;\n /**\n * element = collection(name)\n */\n namedItem(name: string): HTMLCollection | Element | null;\n [index: number]: Element;\n}\n\ndeclare var HTMLAllCollection: {\n prototype: HTMLAllCollection;\n new(): HTMLAllCollection;\n};\n\ninterface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {\n Methods: string;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n /** @deprecated */\n coords: string;\n download: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n readonly mimeType: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n readonly nameProp: string;\n readonly protocolLong: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n type: string;\n urn: string;\n addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAnchorElement: {\n prototype: HTMLAnchorElement;\n new(): HTMLAnchorElement;\n};\n\ninterface HTMLAppletElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n /** @deprecated */\n alt: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n /** @deprecated */\n object: string;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAppletElement: {\n prototype: HTMLAppletElement;\n new(): HTMLAppletElement;\n};\n\ninterface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n coords: string;\n download: string;\n /**\n * Sets or gets whether clicks in this region cause action.\n */\n /** @deprecated */\n noHref: boolean;\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the shape of the object.\n */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAreaElement: {\n prototype: HTMLAreaElement;\n new(): HTMLAreaElement;\n};\n\ninterface HTMLAreasCollection extends HTMLCollectionBase {\n}\n\ndeclare var HTMLAreasCollection: {\n prototype: HTMLAreasCollection;\n new(): HTMLAreasCollection;\n};\n\ninterface HTMLAudioElement extends HTMLMediaElement {\n addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAudioElement: {\n prototype: HTMLAudioElement;\n new(): HTMLAudioElement;\n};\n\ninterface HTMLBRElement extends HTMLElement {\n /**\n * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document.\n */\n /** @deprecated */\n clear: string;\n addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBRElement: {\n prototype: HTMLBRElement;\n new(): HTMLBRElement;\n};\n\ninterface HTMLBaseElement extends HTMLElement {\n /**\n * Gets or sets the baseline URL on which relative links are based.\n */\n href: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseElement: {\n prototype: HTMLBaseElement;\n new(): HTMLBaseElement;\n};\n\ninterface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /**\n * Sets or retrieves the font size of the object.\n */\n /** @deprecated */\n size: number;\n addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseFontElement: {\n prototype: HTMLBaseFontElement;\n new(): HTMLBaseFontElement;\n};\n\ninterface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLBodyElement extends HTMLElement, WindowEventHandlers {\n /** @deprecated */\n aLink: string;\n /** @deprecated */\n background: string;\n /** @deprecated */\n bgColor: string;\n bgProperties: string;\n /** @deprecated */\n link: string;\n /** @deprecated */\n noWrap: boolean;\n onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null;\n onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null;\n /** @deprecated */\n text: string;\n /** @deprecated */\n vLink: string;\n addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBodyElement: {\n prototype: HTMLBodyElement;\n new(): HTMLBodyElement;\n};\n\ninterface HTMLButtonElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets the classification and default behavior of the button.\n */\n type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the default or selected value of the control.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLButtonElement: {\n prototype: HTMLButtonElement;\n new(): HTMLButtonElement;\n};\n\ninterface HTMLCanvasElement extends HTMLElement {\n /**\n * Gets or sets the height of a canvas element on a document.\n */\n height: number;\n /**\n * Gets or sets the width of a canvas element on a document.\n */\n width: number;\n /**\n * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.\n * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext(\"2d\"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext(\"experimental-webgl\");\n */\n getContext(contextId: \"2d\", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null;\n getContext(contextId: \"webgl\" | \"experimental-webgl\", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null;\n getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null;\n /**\n * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.\n */\n msToBlob(): Blob;\n toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void;\n /**\n * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element.\n * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.\n */\n toDataURL(type?: string, ...args: any[]): string;\n addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLCanvasElement: {\n prototype: HTMLCanvasElement;\n new(): HTMLCanvasElement;\n};\n\ninterface HTMLCollectionBase {\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Retrieves an object from various collections.\n */\n item(index: number): Element;\n [index: number]: Element;\n}\n\ninterface HTMLCollection extends HTMLCollectionBase {\n /**\n * Retrieves a select object or an object from an options collection.\n */\n namedItem(name: string): Element | null;\n}\n\ndeclare var HTMLCollection: {\n prototype: HTMLCollection;\n new(): HTMLCollection;\n};\n\ninterface HTMLCollectionOf extends HTMLCollectionBase {\n item(index: number): T;\n namedItem(name: string): T;\n forEach(callbackfn: (value: T, key: number, parent: HTMLCollectionOf) => void, thisArg?: any): void;\n [index: number]: T;\n}\n\ninterface HTMLDListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDListElement: {\n prototype: HTMLDListElement;\n new(): HTMLDListElement;\n};\n\ninterface HTMLDataElement extends HTMLElement {\n value: string;\n addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataElement: {\n prototype: HTMLDataElement;\n new(): HTMLDataElement;\n};\n\ninterface HTMLDataListElement extends HTMLElement {\n readonly options: HTMLCollectionOf;\n addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataListElement: {\n prototype: HTMLDataListElement;\n new(): HTMLDataListElement;\n};\n\ninterface HTMLDetailsElement extends HTMLElement {\n open: boolean;\n addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDetailsElement: {\n prototype: HTMLDetailsElement;\n new(): HTMLDetailsElement;\n};\n\ninterface HTMLDialogElement extends HTMLElement {\n open: boolean;\n returnValue: string;\n close(returnValue?: string): void;\n show(): void;\n showModal(): void;\n addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDialogElement: {\n prototype: HTMLDialogElement;\n new(): HTMLDialogElement;\n};\n\ninterface HTMLDirectoryElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDirectoryElement: {\n prototype: HTMLDirectoryElement;\n new(): HTMLDirectoryElement;\n};\n\ninterface HTMLDivElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n noWrap: boolean;\n addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDivElement: {\n prototype: HTMLDivElement;\n new(): HTMLDivElement;\n};\n\ninterface HTMLDocument extends Document {\n addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDocument: {\n prototype: HTMLDocument;\n new(): HTMLDocument;\n};\n\ninterface HTMLElementEventMap extends ElementEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforecopy\": Event;\n \"beforecut\": Event;\n \"beforedeactivate\": Event;\n \"beforepaste\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"copy\": ClipboardEvent;\n \"cuechange\": Event;\n \"cut\": ClipboardEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSManipulationStateChanged\": Event;\n \"paste\": ClipboardEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n}\n\ninterface HTMLElement extends Element, ElementCSSInlineStyle {\n accessKey: string;\n contentEditable: string;\n readonly dataset: DOMStringMap;\n dir: string;\n draggable: boolean;\n hidden: boolean;\n hideFocus: boolean;\n innerText: string;\n readonly isContentEditable: boolean;\n lang: string;\n readonly offsetHeight: number;\n readonly offsetLeft: number;\n readonly offsetParent: Element;\n readonly offsetTop: number;\n readonly offsetWidth: number;\n onabort: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecut: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null;\n onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oncanplay: ((this: HTMLElement, ev: Event) => any) | null;\n oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null;\n onchange: ((this: HTMLElement, ev: Event) => any) | null;\n onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null;\n oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n oncuechange: ((this: HTMLElement, ev: Event) => any) | null;\n oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n ondeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondurationchange: ((this: HTMLElement, ev: Event) => any) | null;\n onemptied: ((this: HTMLElement, ev: Event) => any) | null;\n onended: ((this: HTMLElement, ev: Event) => any) | null;\n onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null;\n onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oninput: ((this: HTMLElement, ev: Event) => any) | null;\n oninvalid: ((this: HTMLElement, ev: Event) => any) | null;\n onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onload: ((this: HTMLElement, ev: Event) => any) | null;\n onloadeddata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadstart: ((this: HTMLElement, ev: Event) => any) | null;\n onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null;\n onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n onpause: ((this: HTMLElement, ev: Event) => any) | null;\n onplay: ((this: HTMLElement, ev: Event) => any) | null;\n onplaying: ((this: HTMLElement, ev: Event) => any) | null;\n onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null;\n onratechange: ((this: HTMLElement, ev: Event) => any) | null;\n onreset: ((this: HTMLElement, ev: Event) => any) | null;\n onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onseeked: ((this: HTMLElement, ev: Event) => any) | null;\n onseeking: ((this: HTMLElement, ev: Event) => any) | null;\n onselect: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onselectstart: ((this: HTMLElement, ev: Event) => any) | null;\n onstalled: ((this: HTMLElement, ev: Event) => any) | null;\n onsubmit: ((this: HTMLElement, ev: Event) => any) | null;\n onsuspend: ((this: HTMLElement, ev: Event) => any) | null;\n ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null;\n onvolumechange: ((this: HTMLElement, ev: Event) => any) | null;\n onwaiting: ((this: HTMLElement, ev: Event) => any) | null;\n outerText: string;\n spellcheck: boolean;\n tabIndex: number;\n title: string;\n blur(): void;\n click(): void;\n dragDrop(): boolean;\n focus(): void;\n msGetInputContext(): MSInputMethodContext;\n addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLElement: {\n prototype: HTMLElement;\n new(): HTMLElement;\n};\n\ninterface HTMLEmbedElement extends HTMLElement, GetSVGDocument {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n hidden: any;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * Retrieves the palette used for the embedded document.\n */\n readonly palette: string;\n /**\n * Retrieves the URL of the plug-in used to view an embedded document.\n */\n readonly pluginspage: string;\n readonly readyState: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrieves the height and width units of the embed object.\n */\n units: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLEmbedElement: {\n prototype: HTMLEmbedElement;\n new(): HTMLEmbedElement;\n};\n\ninterface HTMLFieldSetElement extends HTMLElement {\n disabled: boolean;\n readonly elements: HTMLCollection;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n name: string;\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFieldSetElement: {\n prototype: HTMLFieldSetElement;\n new(): HTMLFieldSetElement;\n};\n\ninterface HTMLFontElement extends HTMLElement {\n /** @deprecated */\n color: string;\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /** @deprecated */\n size: string;\n addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFontElement: {\n prototype: HTMLFontElement;\n new(): HTMLFontElement;\n};\n\ninterface HTMLFormControlsCollection extends HTMLCollectionBase {\n /**\n * element = collection[name]\n */\n namedItem(name: string): RadioNodeList | Element | null;\n}\n\ndeclare var HTMLFormControlsCollection: {\n prototype: HTMLFormControlsCollection;\n new(): HTMLFormControlsCollection;\n};\n\ninterface HTMLFormElement extends HTMLElement {\n /**\n * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form.\n */\n acceptCharset: string;\n /**\n * Sets or retrieves the URL to which the form content is sent for processing.\n */\n action: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Retrieves a collection, in source order, of all controls in a given form.\n */\n readonly elements: HTMLFormControlsCollection;\n /**\n * Sets or retrieves the MIME encoding for the form.\n */\n encoding: string;\n /**\n * Sets or retrieves the encoding type for the form.\n */\n enctype: string;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Sets or retrieves how to send the form data to the server.\n */\n method: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Designates a form that is not validated when submitted.\n */\n noValidate: boolean;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a form object or an object from an elements collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): any;\n /**\n * Retrieves a form object or an object from an elements collection.\n */\n namedItem(name: string): any;\n reportValidity(): boolean;\n /**\n * Fires when the user resets a form.\n */\n reset(): void;\n /**\n * Fires when a FORM is about to be submitted.\n */\n submit(): void;\n addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLFormElement: {\n prototype: HTMLFormElement;\n new(): HTMLFormElement;\n};\n\ninterface HTMLFrameElement extends HTMLElement {\n /**\n * Retrieves the document object of the page or frame.\n */\n /** @deprecated */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n /** @deprecated */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n /** @deprecated */\n name: string;\n /**\n * Sets or retrieves whether the user can resize the frame.\n */\n /** @deprecated */\n noResize: boolean;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n /** @deprecated */\n src: string;\n addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameElement: {\n prototype: HTMLFrameElement;\n new(): HTMLFrameElement;\n};\n\ninterface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers {\n /**\n * Sets or retrieves the frame widths of the object.\n */\n /** @deprecated */\n cols: string;\n /**\n * Sets or retrieves the frame heights of the object.\n */\n /** @deprecated */\n rows: string;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameSetElement: {\n prototype: HTMLFrameSetElement;\n new(): HTMLFrameSetElement;\n};\n\ninterface HTMLHRElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n color: string;\n /**\n * Sets or retrieves whether the horizontal rule is drawn with 3-D shading.\n */\n /** @deprecated */\n noShade: boolean;\n /** @deprecated */\n size: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHRElement: {\n prototype: HTMLHRElement;\n new(): HTMLHRElement;\n};\n\ninterface HTMLHeadElement extends HTMLElement {\n /** @deprecated */\n profile: string;\n addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadElement: {\n prototype: HTMLHeadElement;\n new(): HTMLHeadElement;\n};\n\ninterface HTMLHeadingElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadingElement: {\n prototype: HTMLHeadingElement;\n new(): HTMLHeadingElement;\n};\n\ninterface HTMLHtmlElement extends HTMLElement {\n /**\n * Sets or retrieves the DTD version that governs the current document.\n */\n /** @deprecated */\n version: string;\n addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHtmlElement: {\n prototype: HTMLHtmlElement;\n new(): HTMLHtmlElement;\n};\n\ninterface HTMLHyperlinkElementUtils {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n toString(): string;\n}\n\ninterface HTMLIFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLIFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n allowFullscreen: boolean;\n allowPaymentRequest: boolean;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n name: string;\n readonly sandbox: DOMTokenList;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrives the content of the page that is to contain.\n */\n srcdoc: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLIFrameElement: {\n prototype: HTMLIFrameElement;\n new(): HTMLIFrameElement;\n};\n\ninterface HTMLImageElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies the properties of a border drawn around an object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves whether the object is fully loaded.\n */\n readonly complete: boolean;\n crossOrigin: string | null;\n readonly currentSrc: string;\n decoding: \"async\" | \"sync\" | \"auto\";\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves whether the image is a server-side image map.\n */\n isMap: boolean;\n /**\n * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /** @deprecated */\n lowsrc: string;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * The original height of the image resource before sizing.\n */\n readonly naturalHeight: number;\n /**\n * The original width of the image resource before sizing.\n */\n readonly naturalWidth: number;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Sets or retrieves the vertical margin for the object.\n */\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n readonly x: number;\n readonly y: number;\n msGetAsCastingSource(): any;\n addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLImageElement: {\n prototype: HTMLImageElement;\n new(): HTMLImageElement;\n};\n\ninterface HTMLInputElement extends HTMLElement {\n /**\n * Sets or retrieves a comma-separated list of content types.\n */\n accept: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n checked: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n defaultChecked: boolean;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Returns a FileList object on a file type input object.\n */\n files: FileList | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n indeterminate: boolean;\n /**\n * Specifies the ID of a pre-defined datalist of options for an input element.\n */\n readonly list: HTMLElement | null;\n /**\n * Defines the maximum acceptable value for an input element with type=\"number\".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field.\n */\n max: string;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n /**\n * Defines the minimum acceptable value for an input element with type=\"number\". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field.\n */\n min: string;\n minLength: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a string containing a regular expression that the user's input must match.\n */\n pattern: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n selectionDirection: string | null;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number | null;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number | null;\n size: number;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n /**\n * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field.\n */\n step: string;\n /**\n * Returns the content type of the object.\n */\n type: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n /** @deprecated */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns the value of the data at the cursor's current position.\n */\n value: string;\n valueAsDate: any;\n /**\n * Returns the input field value as a number.\n */\n valueAsNumber: number;\n webkitdirectory: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Makes the selection equal to the current object.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n /**\n * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value.\n * @param n Value to decrement the value by.\n */\n stepDown(n?: number): void;\n /**\n * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value.\n * @param n Value to increment the value by.\n */\n stepUp(n?: number): void;\n addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLInputElement: {\n prototype: HTMLInputElement;\n new(): HTMLInputElement;\n};\n\ninterface HTMLLIElement extends HTMLElement {\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of a list item.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLIElement: {\n prototype: HTMLLIElement;\n new(): HTMLLIElement;\n};\n\ninterface HTMLLabelElement extends HTMLElement {\n readonly control: HTMLInputElement | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the object to which the given label object is assigned.\n */\n htmlFor: string;\n addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLabelElement: {\n prototype: HTMLLabelElement;\n new(): HTMLLabelElement;\n};\n\ninterface HTMLLegendElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLegendElement: {\n prototype: HTMLLegendElement;\n new(): HTMLLegendElement;\n};\n\ninterface HTMLLinkElement extends HTMLElement, LinkStyle {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves a destination URL or an anchor point.\n */\n href: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n import?: Document;\n integrity: string;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n /** @deprecated */\n target: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLinkElement: {\n prototype: HTMLLinkElement;\n new(): HTMLLinkElement;\n};\n\ninterface HTMLMainElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMainElement: {\n prototype: HTMLMainElement;\n new(): HTMLMainElement;\n};\n\ninterface HTMLMapElement extends HTMLElement {\n /**\n * Retrieves a collection of the area objects defined for the given map object.\n */\n readonly areas: HTMLAreasCollection;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMapElement: {\n prototype: HTMLMapElement;\n new(): HTMLMapElement;\n};\n\ninterface HTMLMarqueeElementEventMap extends HTMLElementEventMap {\n \"bounce\": Event;\n \"finish\": Event;\n \"start\": Event;\n}\n\ninterface HTMLMarqueeElement extends HTMLElement {\n /** @deprecated */\n behavior: string;\n /** @deprecated */\n bgColor: string;\n /** @deprecated */\n direction: string;\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /** @deprecated */\n loop: number;\n /** @deprecated */\n onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n scrollAmount: number;\n /** @deprecated */\n scrollDelay: number;\n /** @deprecated */\n trueSpeed: boolean;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n /** @deprecated */\n start(): void;\n /** @deprecated */\n stop(): void;\n addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMarqueeElement: {\n prototype: HTMLMarqueeElement;\n new(): HTMLMarqueeElement;\n};\n\ninterface HTMLMediaElementEventMap extends HTMLElementEventMap {\n \"encrypted\": MediaEncryptedEvent;\n \"msneedkey\": Event;\n}\n\ninterface HTMLMediaElement extends HTMLElement {\n /**\n * Returns an AudioTrackList object with the audio tracks for a given video element.\n */\n readonly audioTracks: AudioTrackList;\n /**\n * Gets or sets a value that indicates whether to start playing the media automatically.\n */\n autoplay: boolean;\n /**\n * Gets a collection of buffered time ranges.\n */\n readonly buffered: TimeRanges;\n /**\n * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player).\n */\n controls: boolean;\n crossOrigin: string | null;\n /**\n * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement.\n */\n readonly currentSrc: string;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n currentTime: number;\n defaultMuted: boolean;\n /**\n * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource.\n */\n defaultPlaybackRate: number;\n /**\n * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming.\n */\n readonly duration: number;\n /**\n * Gets information about whether the playback has ended or not.\n */\n readonly ended: boolean;\n /**\n * Returns an object representing the current error state of the audio or video element.\n */\n readonly error: MediaError | null;\n /**\n * Gets or sets a flag to specify whether playback should restart after it completes.\n */\n loop: boolean;\n readonly mediaKeys: MediaKeys | null;\n /**\n * Specifies the purpose of the audio or video media, such as background audio or alerts.\n */\n msAudioCategory: string;\n /**\n * Specifies the output device id that the audio will be sent to.\n */\n msAudioDeviceType: string;\n readonly msGraphicsTrustStatus: MSGraphicsTrust;\n /**\n * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element.\n */\n /** @deprecated */\n readonly msKeys: MSMediaKeys;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Specifies whether or not to enable low-latency playback on the media element.\n */\n msRealTime: boolean;\n /**\n * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted.\n */\n muted: boolean;\n /**\n * Gets the current network activity for the element.\n */\n readonly networkState: number;\n onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null;\n /** @deprecated */\n onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null;\n /**\n * Gets a flag that specifies whether playback is paused.\n */\n readonly paused: boolean;\n /**\n * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource.\n */\n playbackRate: number;\n /**\n * Gets TimeRanges for the current media resource that has been played.\n */\n readonly played: TimeRanges;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n preload: string;\n readonly readyState: number;\n /**\n * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.\n */\n readonly seekable: TimeRanges;\n /**\n * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource.\n */\n readonly seeking: boolean;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcObject: MediaStream | MediaSource | Blob | null;\n readonly textTracks: TextTrackList;\n readonly videoTracks: VideoTrackList;\n /**\n * Gets or sets the volume level for audio portions of the media element.\n */\n volume: number;\n addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack;\n /**\n * Returns a string that specifies whether the client can play a given media resource type.\n */\n canPlayType(type: string): CanPlayTypeResult;\n /**\n * Resets the audio or video object and loads a new media resource.\n */\n load(): void;\n /**\n * Clears all effects from the media pipeline.\n */\n msClearEffects(): void;\n msGetAsCastingSource(): any;\n /**\n * Inserts the specified audio effect into media pipeline.\n */\n msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n /** @deprecated */\n msSetMediaKeys(mediaKeys: MSMediaKeys): void;\n /**\n * Specifies the media protection manager for a given media pipeline.\n */\n msSetMediaProtectionManager(mediaProtectionManager?: any): void;\n /**\n * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not.\n */\n pause(): void;\n /**\n * Loads and starts playback of a media resource.\n */\n play(): Promise;\n setMediaKeys(mediaKeys: MediaKeys | null): Promise;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMediaElement: {\n prototype: HTMLMediaElement;\n new(): HTMLMediaElement;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n};\n\ninterface HTMLMenuElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n type: string;\n addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMenuElement: {\n prototype: HTMLMenuElement;\n new(): HTMLMenuElement;\n};\n\ninterface HTMLMetaElement extends HTMLElement {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Gets or sets meta-information to associate with httpEquiv or name.\n */\n content: string;\n /**\n * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header.\n */\n httpEquiv: string;\n /**\n * Sets or retrieves the value specified in the content attribute of the meta object.\n */\n name: string;\n /**\n * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object.\n */\n /** @deprecated */\n scheme: string;\n /**\n * Sets or retrieves the URL property that will be loaded after the specified time has elapsed.\n */\n /** @deprecated */\n url: string;\n addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMetaElement: {\n prototype: HTMLMetaElement;\n new(): HTMLMetaElement;\n};\n\ninterface HTMLMeterElement extends HTMLElement {\n high: number;\n readonly labels: NodeListOf;\n low: number;\n max: number;\n min: number;\n optimum: number;\n value: number;\n addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMeterElement: {\n prototype: HTMLMeterElement;\n new(): HTMLMeterElement;\n};\n\ninterface HTMLModElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n /**\n * Sets or retrieves the date and time of a modification to the object.\n */\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLModElement: {\n prototype: HTMLModElement;\n new(): HTMLModElement;\n};\n\ninterface HTMLOListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /**\n * The starting number.\n */\n start: number;\n type: string;\n addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOListElement: {\n prototype: HTMLOListElement;\n new(): HTMLOListElement;\n};\n\ninterface HTMLObjectElement extends HTMLElement, GetSVGDocument {\n /**\n * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element.\n */\n readonly BaseHref: string;\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n border: string;\n /**\n * Sets or retrieves the URL of the file containing the compiled Java class.\n */\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n /**\n * Sets or retrieves the Internet media type for the code associated with the object.\n */\n /** @deprecated */\n codeType: string;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Sets or retrieves the URL that references the data of the object.\n */\n data: string;\n /** @deprecated */\n declare: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly readyState: number;\n /**\n * Sets or retrieves a message to be displayed while an object is loading.\n */\n /** @deprecated */\n standby: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n typemustmatch: boolean;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLObjectElement: {\n prototype: HTMLObjectElement;\n new(): HTMLObjectElement;\n};\n\ninterface HTMLOptGroupElement extends HTMLElement {\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptGroupElement: {\n prototype: HTMLOptGroupElement;\n new(): HTMLOptGroupElement;\n};\n\ninterface HTMLOptionElement extends HTMLElement {\n /**\n * Sets or retrieves the status of an option.\n */\n defaultSelected: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the ordinal position of an option in a list box.\n */\n readonly index: number;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n /**\n * Sets or retrieves whether the option in the list box is the default item.\n */\n selected: boolean;\n /**\n * Sets or retrieves the text string specified by the option tag.\n */\n text: string;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptionElement: {\n prototype: HTMLOptionElement;\n new(): HTMLOptionElement;\n};\n\ninterface HTMLOptionsCollection extends HTMLCollectionOf {\n /**\n * Returns the number of elements in the collection.\n * When set to a smaller number, truncates the number of option elements in the corresponding container.\n * When set to a greater number, adds new blank option elements to that container.\n */\n length: number;\n /**\n * Returns the index of the first selected item, if any, or −1 if there is no selected\n * item.\n * Can be set, to change the selection.\n */\n selectedIndex: number;\n /**\n * Inserts element before the node given by before.\n * The before argument can be a number, in which case element is inserted before the item with that number, or an element from the\n * collection, in which case element is inserted before that element.\n * If before is omitted, null, or a number out of range, then element will be added at the end of the list.\n * This method will throw a \"HierarchyRequestError\" DOMException if\n * element is an ancestor of the element into which it is to be inserted.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void;\n /**\n * Removes the item with index index from the collection.\n */\n remove(index: number): void;\n}\n\ndeclare var HTMLOptionsCollection: {\n prototype: HTMLOptionsCollection;\n new(): HTMLOptionsCollection;\n};\n\ninterface HTMLOutputElement extends HTMLElement {\n defaultValue: string;\n readonly form: HTMLFormElement | null;\n readonly htmlFor: DOMTokenList;\n readonly labels: NodeListOf;\n name: string;\n readonly type: string;\n readonly validationMessage: string;\n readonly validity: ValidityState;\n value: string;\n readonly willValidate: boolean;\n checkValidity(): boolean;\n reportValidity(): boolean;\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOutputElement: {\n prototype: HTMLOutputElement;\n new(): HTMLOutputElement;\n};\n\ninterface HTMLParagraphElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n clear: string;\n addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParagraphElement: {\n prototype: HTMLParagraphElement;\n new(): HTMLParagraphElement;\n};\n\ninterface HTMLParamElement extends HTMLElement {\n /**\n * Sets or retrieves the name of an input parameter for an element.\n */\n name: string;\n /**\n * Sets or retrieves the content type of the resource designated by the value attribute.\n */\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of an input parameter for an element.\n */\n value: string;\n /**\n * Sets or retrieves the data type of the value attribute.\n */\n /** @deprecated */\n valueType: string;\n addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParamElement: {\n prototype: HTMLParamElement;\n new(): HTMLParamElement;\n};\n\ninterface HTMLPictureElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPictureElement: {\n prototype: HTMLPictureElement;\n new(): HTMLPictureElement;\n};\n\ninterface HTMLPreElement extends HTMLElement {\n /**\n * Sets or gets a value that you can use to implement your own width functionality for the object.\n */\n /** @deprecated */\n width: number;\n addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPreElement: {\n prototype: HTMLPreElement;\n new(): HTMLPreElement;\n};\n\ninterface HTMLProgressElement extends HTMLElement {\n readonly labels: NodeListOf;\n /**\n * Defines the maximum, or \"done\" value for a progress element.\n */\n max: number;\n /**\n * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar).\n */\n readonly position: number;\n /**\n * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLProgressElement: {\n prototype: HTMLProgressElement;\n new(): HTMLProgressElement;\n};\n\ninterface HTMLQuoteElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLQuoteElement: {\n prototype: HTMLQuoteElement;\n new(): HTMLQuoteElement;\n};\n\ninterface HTMLScriptElement extends HTMLElement {\n async: boolean;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /**\n * Sets or retrieves the status of the script.\n */\n defer: boolean;\n /**\n * Sets or retrieves the event for which the script is written.\n */\n /** @deprecated */\n event: string;\n /**\n * Sets or retrieves the object that is bound to the event script.\n */\n /** @deprecated */\n htmlFor: string;\n integrity: string;\n noModule: boolean;\n /**\n * Retrieves the URL to an external file that contains the source code or data.\n */\n src: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n /**\n * Sets or retrieves the MIME type for the associated scripting engine.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLScriptElement: {\n prototype: HTMLScriptElement;\n new(): HTMLScriptElement;\n};\n\ninterface HTMLSelectElement extends HTMLElement {\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n length: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly options: HTMLOptionsCollection;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the index of the selected option in a select object.\n */\n selectedIndex: number;\n readonly selectedOptions: HTMLCollectionOf;\n /**\n * Sets or retrieves the number of rows in the list box.\n */\n size: number;\n /**\n * Retrieves the type of select control based on the value of the MULTIPLE attribute.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Adds an element to the areas, controlRange, or options collection.\n * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.\n * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(index: number): Element | null;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made.\n */\n namedItem(name: string): HTMLOptionElement | null;\n /**\n * Removes an element from the collection.\n * @param index Number that specifies the zero-based index of the element to remove from the collection.\n */\n remove(): void;\n remove(index: number): void;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: Element;\n}\n\ndeclare var HTMLSelectElement: {\n prototype: HTMLSelectElement;\n new(): HTMLSelectElement;\n};\n\ninterface HTMLSlotElement extends HTMLElement {\n name: string;\n assignedNodes(options?: AssignedNodesOptions): Node[];\n addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface HTMLSourceElement extends HTMLElement {\n /**\n * Gets or sets the intended media type of the media source.\n */\n media: string;\n /** @deprecated */\n msKeySystem: string;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Gets or sets the MIME type of a media resource.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSourceElement: {\n prototype: HTMLSourceElement;\n new(): HTMLSourceElement;\n};\n\ninterface HTMLSpanElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSpanElement: {\n prototype: HTMLSpanElement;\n new(): HTMLSpanElement;\n};\n\ninterface HTMLStyleElement extends HTMLElement, LinkStyle {\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Retrieves the CSS language in which the style sheet is written.\n */\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLStyleElement: {\n prototype: HTMLStyleElement;\n new(): HTMLStyleElement;\n};\n\ninterface HTMLSummaryElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSummaryElement: {\n prototype: HTMLSummaryElement;\n new(): HTMLSummaryElement;\n};\n\ninterface HTMLTableCaptionElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the caption or legend.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCaptionElement: {\n prototype: HTMLTableCaptionElement;\n new(): HTMLTableCaptionElement;\n};\n\ninterface HTMLTableCellElement extends HTMLElement {\n /**\n * Sets or retrieves abbreviated text for the object.\n */\n abbr: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a comma-delimited list of conceptual categories associated with the object.\n */\n /** @deprecated */\n axis: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves the position of the object in the cells collection of a row.\n */\n readonly cellIndex: number;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number columns in the table that the object should span.\n */\n colSpan: number;\n /**\n * Sets or retrieves a list of header cells that provide information for the object.\n */\n headers: string;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n /** @deprecated */\n noWrap: boolean;\n /**\n * Sets or retrieves how many rows in a table the cell should span.\n */\n rowSpan: number;\n /**\n * Sets or retrieves the group of cells in a table to which the object's information applies.\n */\n scope: string;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCellElement: {\n prototype: HTMLTableCellElement;\n new(): HTMLTableCellElement;\n};\n\ninterface HTMLTableColElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the object relative to the display or table.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of columns in the group.\n */\n span: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableColElement: {\n prototype: HTMLTableColElement;\n new(): HTMLTableColElement;\n};\n\ninterface HTMLTableDataCellElement extends HTMLTableCellElement {\n addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableDataCellElement: {\n prototype: HTMLTableDataCellElement;\n new(): HTMLTableDataCellElement;\n};\n\ninterface HTMLTableElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves the caption object of a table.\n */\n caption: HTMLTableCaptionElement | null;\n /**\n * Sets or retrieves the amount of space between the border of the cell and the content of the cell.\n */\n /** @deprecated */\n cellPadding: string;\n /**\n * Sets or retrieves the amount of space between cells in a table.\n */\n /** @deprecated */\n cellSpacing: string;\n /**\n * Sets or retrieves the way the border frame around the table is displayed.\n */\n /** @deprecated */\n frame: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /**\n * Sets or retrieves which dividing lines (inner borders) are displayed.\n */\n /** @deprecated */\n rules: string;\n /**\n * Sets or retrieves a description and/or structure of the object.\n */\n /** @deprecated */\n summary: string;\n /**\n * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order.\n */\n readonly tBodies: HTMLCollectionOf;\n /**\n * Retrieves the tFoot object of the table.\n */\n tFoot: HTMLTableSectionElement | null;\n /**\n * Retrieves the tHead object of the table.\n */\n tHead: HTMLTableSectionElement | null;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n /**\n * Creates an empty caption element in the table.\n */\n createCaption(): HTMLTableCaptionElement;\n /**\n * Creates an empty tBody element in the table.\n */\n createTBody(): HTMLTableSectionElement;\n /**\n * Creates an empty tFoot element in the table.\n */\n createTFoot(): HTMLTableSectionElement;\n /**\n * Returns the tHead element object if successful, or null otherwise.\n */\n createTHead(): HTMLTableSectionElement;\n /**\n * Deletes the caption element and its contents from the table.\n */\n deleteCaption(): void;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Deletes the tFoot element and its contents from the table.\n */\n deleteTFoot(): void;\n /**\n * Deletes the tHead element and its contents from the table.\n */\n deleteTHead(): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableElement: {\n prototype: HTMLTableElement;\n new(): HTMLTableElement;\n};\n\ninterface HTMLTableHeaderCellElement extends HTMLTableCellElement {\n scope: string;\n addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableHeaderCellElement: {\n prototype: HTMLTableHeaderCellElement;\n new(): HTMLTableHeaderCellElement;\n};\n\ninterface HTMLTableRowElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves a collection of all cells in the table row.\n */\n readonly cells: HTMLCollectionOf;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Retrieves the position of the object in the rows collection for the table.\n */\n readonly rowIndex: number;\n /**\n * Retrieves the position of the object in the collection.\n */\n readonly sectionRowIndex: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified cell from the table row, as well as from the cells collection.\n * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted.\n */\n deleteCell(index?: number): void;\n /**\n * Creates a new cell in the table row, and adds the cell to the cells collection.\n * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.\n */\n insertCell(index?: number): HTMLTableDataCellElement;\n addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableRowElement: {\n prototype: HTMLTableRowElement;\n new(): HTMLTableRowElement;\n};\n\ninterface HTMLTableSectionElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableSectionElement: {\n prototype: HTMLTableSectionElement;\n new(): HTMLTableSectionElement;\n};\n\ninterface HTMLTemplateElement extends HTMLElement {\n readonly content: DocumentFragment;\n addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTemplateElement: {\n prototype: HTMLTemplateElement;\n new(): HTMLTemplateElement;\n};\n\ninterface HTMLTextAreaElement extends HTMLElement {\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n cols: number;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n dirName: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n minLength: number;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n /**\n * Sets or retrieves the value indicated whether the content of the object is read-only.\n */\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n rows: number;\n selectionDirection: string;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number;\n readonly textLength: number;\n /**\n * Retrieves the type of control.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Retrieves or sets the text in the entry field of the textArea element.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Sets or retrieves how to handle wordwrapping in the object.\n */\n wrap: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Highlights the input area of a form element.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n setRangeText(replacement: string): void;\n setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTextAreaElement: {\n prototype: HTMLTextAreaElement;\n new(): HTMLTextAreaElement;\n};\n\ninterface HTMLTimeElement extends HTMLElement {\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTimeElement: {\n prototype: HTMLTimeElement;\n new(): HTMLTimeElement;\n};\n\ninterface HTMLTitleElement extends HTMLElement {\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTitleElement: {\n prototype: HTMLTitleElement;\n new(): HTMLTitleElement;\n};\n\ninterface HTMLTrackElement extends HTMLElement {\n default: boolean;\n kind: string;\n label: string;\n readonly readyState: number;\n src: string;\n srclang: string;\n readonly track: TextTrack;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTrackElement: {\n prototype: HTMLTrackElement;\n new(): HTMLTrackElement;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n};\n\ninterface HTMLUListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUListElement: {\n prototype: HTMLUListElement;\n new(): HTMLUListElement;\n};\n\ninterface HTMLUnknownElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUnknownElement: {\n prototype: HTMLUnknownElement;\n new(): HTMLUnknownElement;\n};\n\ninterface HTMLVideoElementEventMap extends HTMLMediaElementEventMap {\n \"MSVideoFormatChanged\": Event;\n \"MSVideoFrameStepCompleted\": Event;\n \"MSVideoOptimalLayoutChanged\": Event;\n}\n\ninterface HTMLVideoElement extends HTMLMediaElement {\n /**\n * Gets or sets the height of the video element.\n */\n height: number;\n msHorizontalMirror: boolean;\n readonly msIsLayoutOptimalForPlayback: boolean;\n readonly msIsStereo3D: boolean;\n msStereo3DPackingMode: string;\n msStereo3DRenderMode: string;\n msZoom: boolean;\n onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n /**\n * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available.\n */\n poster: string;\n /**\n * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoHeight: number;\n /**\n * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoWidth: number;\n readonly webkitDisplayingFullscreen: boolean;\n readonly webkitSupportsFullscreen: boolean;\n /**\n * Gets or sets the width of the video element.\n */\n width: number;\n getVideoPlaybackQuality(): VideoPlaybackQuality;\n msFrameStep(forward: boolean): void;\n msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void;\n webkitEnterFullScreen(): void;\n webkitEnterFullscreen(): void;\n webkitExitFullScreen(): void;\n webkitExitFullscreen(): void;\n addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLVideoElement: {\n prototype: HTMLVideoElement;\n new(): HTMLVideoElement;\n};\n\ninterface HashChangeEvent extends Event {\n readonly newURL: string;\n readonly oldURL: string;\n}\n\ndeclare var HashChangeEvent: {\n prototype: HashChangeEvent;\n new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent;\n};\n\ninterface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;\n}\n\ndeclare var Headers: {\n prototype: Headers;\n new(init?: HeadersInit): Headers;\n};\n\ninterface History {\n readonly length: number;\n scrollRestoration: ScrollRestoration;\n readonly state: any;\n back(distance?: any): void;\n forward(distance?: any): void;\n go(delta?: any): void;\n pushState(data: any, title?: string, url?: string | null): void;\n replaceState(data: any, title?: string, url?: string | null): void;\n}\n\ndeclare var History: {\n prototype: History;\n new(): History;\n};\n\ninterface HkdfCtrParams extends Algorithm {\n context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n hash: string | Algorithm;\n label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface IDBArrayKey extends Array {\n}\n\ninterface IDBCursor {\n /**\n * Returns the direction (\"next\", \"nextunique\", \"prev\" or \"prevunique\")\n * of the cursor.\n */\n readonly direction: IDBCursorDirection;\n /**\n * Returns the key of the cursor.\n * Throws a \"InvalidStateError\" DOMException if the cursor is advancing or is finished.\n */\n readonly key: IDBValidKey | IDBKeyRange;\n /**\n * Returns the effective key of the cursor.\n * Throws a \"InvalidStateError\" DOMException if the cursor is advancing or is finished.\n */\n readonly primaryKey: IDBValidKey | IDBKeyRange;\n /**\n * Returns the IDBObjectStore or IDBIndex the cursor was opened from.\n */\n readonly source: IDBObjectStore | IDBIndex;\n /**\n * Advances the cursor through the next count records in\n * range.\n */\n advance(count: number): void;\n /**\n * Advances the cursor to the next record in range matching or\n * after key.\n */\n continue(key?: IDBValidKey | IDBKeyRange): void;\n /**\n * Advances the cursor to the next record in range matching\n * or after key and primaryKey. Throws an \"InvalidAccessError\" DOMException if the source is not an index.\n */\n continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void;\n /**\n * Delete the record pointed at by the cursor with a new value.\n * If successful, request's result will be undefined.\n */\n delete(): IDBRequest;\n /**\n * Updated the record pointed at by the cursor with a new value.\n * Throws a \"DataError\" DOMException if the effective object store uses in-line keys and the key would have changed.\n * If successful, request's result will be the record's key.\n */\n update(value: any): IDBRequest;\n}\n\ndeclare var IDBCursor: {\n prototype: IDBCursor;\n new(): IDBCursor;\n};\n\ninterface IDBCursorWithValue extends IDBCursor {\n /**\n * Returns the cursor's current value.\n */\n readonly value: any;\n}\n\ndeclare var IDBCursorWithValue: {\n prototype: IDBCursorWithValue;\n new(): IDBCursorWithValue;\n};\n\ninterface IDBDatabaseEventMap {\n \"abort\": Event;\n \"close\": Event;\n \"error\": Event;\n \"versionchange\": IDBVersionChangeEvent;\n}\n\ninterface IDBDatabase extends EventTarget {\n /**\n * Returns the name of the database.\n */\n readonly name: string;\n /**\n * Returns a list of the names of object stores in the database.\n */\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBDatabase, ev: Event) => any) | null;\n onclose: ((this: IDBDatabase, ev: Event) => any) | null;\n onerror: ((this: IDBDatabase, ev: Event) => any) | null;\n onversionchange: ((this: IDBDatabase, ev: IDBVersionChangeEvent) => any) | null;\n /**\n * Returns the version of the database.\n */\n readonly version: number;\n /**\n * Closes the connection once all running transactions have finished.\n */\n close(): void;\n /**\n * Creates a new object store with the given name and options and returns a new IDBObjectStore.\n * Throws a \"InvalidStateError\" DOMException if not called within an upgrade transaction.\n */\n createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;\n /**\n * Deletes the object store with the given name.\n * Throws a \"InvalidStateError\" DOMException if not called within an upgrade transaction.\n */\n deleteObjectStore(name: string): void;\n /**\n * Returns a new transaction with the given mode (\"readonly\" or \"readwrite\")\n * and scope which can be a single object store name or an array of names.\n */\n transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;\n addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBDatabase: {\n prototype: IDBDatabase;\n new(): IDBDatabase;\n};\n\ninterface IDBEnvironment {\n readonly indexedDB: IDBFactory;\n}\n\ninterface IDBFactory {\n /**\n * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if\n * the keys are equal.\n * Throws a \"DataError\" DOMException if either input is not a valid key.\n */\n cmp(first: any, second: any): number;\n /**\n * Attempts to delete the named database. If the\n * database already exists and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close. If the request\n * is successful request's result will be null.\n */\n deleteDatabase(name: string): IDBOpenDBRequest;\n /**\n * Attempts to open a connection to the named database with the specified version. If the database already exists\n * with a lower version and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close, then an upgrade\n * will occur. If the database already exists with a higher\n * version the request will fail. If the request is\n * successful request's result will\n * be the connection.\n */\n open(name: string, version?: number): IDBOpenDBRequest;\n}\n\ndeclare var IDBFactory: {\n prototype: IDBFactory;\n new(): IDBFactory;\n};\n\ninterface IDBIndex {\n readonly keyPath: string | string[];\n readonly multiEntry: boolean;\n /**\n * Updates the name of the store to newName.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n name: string;\n /**\n * Returns the IDBObjectStore the index belongs to.\n */\n readonly objectStore: IDBObjectStore;\n readonly unique: boolean;\n /**\n * Retrieves the number of records matching the given key or key range in query.\n * If successful, request's result will be the\n * count.\n */\n count(key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the value of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the value, or undefined if there was no matching record.\n */\n get(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the values of the records matching the given key or key range in query (up to count if given).\n * If successful, request's result will be an Array of the values.\n */\n getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the keys of records matching the given key or key range in query (up to count if given).\n * If successful, request's result will be an Array of the keys.\n */\n getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the key of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the key, or undefined if there was no matching record.\n */\n getKey(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Opens a cursor over the records matching query,\n * ordered by direction. If query is null, all records in index are matched.\n * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records.\n */\n openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n /**\n * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched.\n * If successful, request's result will be an IDBCursor, or null if there were no matching records.\n */\n openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n}\n\ndeclare var IDBIndex: {\n prototype: IDBIndex;\n new(): IDBIndex;\n};\n\ninterface IDBKeyRange {\n /**\n * Returns lower bound, or undefined if none.\n */\n readonly lower: any;\n /**\n * Returns true if the lower open flag is set, and false otherwise.\n */\n readonly lowerOpen: boolean;\n /**\n * Returns upper bound, or undefined if none.\n */\n readonly upper: any;\n /**\n * Returns true if the upper open flag is set, and false otherwise.\n */\n readonly upperOpen: boolean;\n /**\n * Returns true if key is included in the range, and false otherwise.\n */\n includes(key: any): boolean;\n}\n\ndeclare var IDBKeyRange: {\n prototype: IDBKeyRange;\n new(): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange spanning from lower to upper.\n * If lowerOpen is true, lower is not included in the range.\n * If upperOpen is true, upper is not included in the range.\n */\n bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange starting at key with no\n * upper bound. If open is true, key is not included in the\n * range.\n */\n lowerBound(lower: any, open?: boolean): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange spanning only key.\n */\n only(value: any): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange with no lower bound and ending at key. If open is true, key is not included in the range.\n */\n upperBound(upper: any, open?: boolean): IDBKeyRange;\n};\n\ninterface IDBObjectStore {\n /**\n * Returns true if the store has a key generator, and false otherwise.\n */\n readonly autoIncrement: boolean;\n /**\n * Returns a list of the names of indexes in the store.\n */\n readonly indexNames: DOMStringList;\n /**\n * Returns the key path of the store, or null if none.\n */\n readonly keyPath: string | string[];\n /**\n * Updates the name of the store to newName.\n * Throws \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n name: string;\n /**\n * Returns the associated transaction.\n */\n readonly transaction: IDBTransaction;\n add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Deletes all records in store.\n * If successful, request's result will\n * be undefined.\n */\n clear(): IDBRequest;\n /**\n * Retrieves the number of records matching the\n * given key or key range in query.\n * If successful, request's result will be the count.\n */\n count(key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be\n * satisfied with the data already in store the upgrade\n * transaction will abort with\n * a \"ConstraintError\" DOMException.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex;\n /**\n * Deletes records in store with the given key or in the given key range in query.\n * If successful, request's result will\n * be undefined.\n */\n delete(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Deletes the index in store with the given name.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n deleteIndex(name: string): void;\n /**\n * Retrieves the value of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the value, or undefined if there was no matching record.\n */\n get(query: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the values of the records matching the\n * given key or key range in query (up to count if given).\n * If successful, request's result will\n * be an Array of the values.\n */\n getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the keys of records matching the\n * given key or key range in query (up to count if given).\n * If successful, request's result will\n * be an Array of the keys.\n */\n getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the key of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the key, or undefined if there was no matching record.\n */\n getKey(query: IDBValidKey | IDBKeyRange): IDBRequest;\n index(name: string): IDBIndex;\n /**\n * Opens a cursor over the records matching query,\n * ordered by direction. If query is null, all records in store are matched.\n * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records.\n */\n openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n /**\n * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched.\n * If successful, request's result will be an IDBCursor pointing at the first matching record, or\n * null if there were no matching records.\n */\n openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest;\n}\n\ndeclare var IDBObjectStore: {\n prototype: IDBObjectStore;\n new(): IDBObjectStore;\n};\n\ninterface IDBOpenDBRequestEventMap extends IDBRequestEventMap {\n \"blocked\": Event;\n \"upgradeneeded\": IDBVersionChangeEvent;\n}\n\ninterface IDBOpenDBRequest extends IDBRequest {\n onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;\n onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;\n addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBOpenDBRequest: {\n prototype: IDBOpenDBRequest;\n new(): IDBOpenDBRequest;\n};\n\ninterface IDBRequestEventMap {\n \"error\": Event;\n \"success\": Event;\n}\n\ninterface IDBRequest extends EventTarget {\n /**\n * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws\n * a \"InvalidStateError\" DOMException if the request is still pending.\n */\n readonly error: DOMException | null;\n onerror: ((this: IDBRequest, ev: Event) => any) | null;\n onsuccess: ((this: IDBRequest, ev: Event) => any) | null;\n /**\n * Returns \"pending\" until a request is complete,\n * then returns \"done\".\n */\n readonly readyState: IDBRequestReadyState;\n /**\n * When a request is completed, returns the result,\n * or undefined if the request failed. Throws a\n * \"InvalidStateError\" DOMException if the request is still pending.\n */\n readonly result: any;\n /**\n * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open\n * request.\n */\n readonly source: IDBObjectStore | IDBIndex | IDBCursor;\n /**\n * Returns the IDBTransaction the request was made within.\n * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise.\n */\n readonly transaction: IDBTransaction | null;\n addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBRequest: {\n prototype: IDBRequest;\n new(): IDBRequest;\n};\n\ninterface IDBTransactionEventMap {\n \"abort\": Event;\n \"complete\": Event;\n \"error\": Event;\n}\n\ninterface IDBTransaction extends EventTarget {\n /**\n * Returns the transaction's connection.\n */\n readonly db: IDBDatabase;\n /**\n * If the transaction was aborted, returns the\n * error (a DOMException) providing the reason.\n */\n readonly error: DOMException;\n /**\n * Returns the mode the transaction was created with\n * (\"readonly\" or \"readwrite\"), or \"versionchange\" for\n * an upgrade transaction.\n */\n readonly mode: IDBTransactionMode;\n /**\n * Returns a list of the names of object stores in the\n * transaction's scope. For an upgrade transaction this is all object stores in the database.\n */\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBTransaction, ev: Event) => any) | null;\n oncomplete: ((this: IDBTransaction, ev: Event) => any) | null;\n onerror: ((this: IDBTransaction, ev: Event) => any) | null;\n /**\n * Aborts the transaction. All pending requests will fail with\n * a \"AbortError\" DOMException and all changes made to the database will be\n * reverted.\n */\n abort(): void;\n /**\n * Returns an IDBObjectStore in the transaction's scope.\n */\n objectStore(name: string): IDBObjectStore;\n addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBTransaction: {\n prototype: IDBTransaction;\n new(): IDBTransaction;\n};\n\ninterface IDBVersionChangeEvent extends Event {\n readonly newVersion: number | null;\n readonly oldVersion: number;\n}\n\ndeclare var IDBVersionChangeEvent: {\n prototype: IDBVersionChangeEvent;\n new(type: string, eventInitDict?: IDBVersionChangeEventInit): IDBVersionChangeEvent;\n};\n\ninterface IIRFilterNode extends AudioNode {\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var IIRFilterNode: {\n prototype: IIRFilterNode;\n new(context: BaseAudioContext, options: IIRFilterOptions): IIRFilterNode;\n};\n\ninterface ImageBitmap {\n readonly height: number;\n readonly width: number;\n close(): void;\n}\n\ninterface ImageBitmapOptions {\n colorSpaceConversion?: \"none\" | \"default\";\n imageOrientation?: \"none\" | \"flipY\";\n premultiplyAlpha?: \"none\" | \"premultiply\" | \"default\";\n resizeHeight?: number;\n resizeQuality?: \"pixelated\" | \"low\" | \"medium\" | \"high\";\n resizeWidth?: number;\n}\n\ninterface ImageData {\n readonly data: Uint8ClampedArray;\n readonly height: number;\n readonly width: number;\n}\n\ndeclare var ImageData: {\n prototype: ImageData;\n new(width: number, height: number): ImageData;\n new(array: Uint8ClampedArray, width: number, height: number): ImageData;\n};\n\ninterface IntersectionObserver {\n readonly root: Element | null;\n readonly rootMargin: string;\n readonly thresholds: number[];\n disconnect(): void;\n observe(target: Element): void;\n takeRecords(): IntersectionObserverEntry[];\n unobserve(target: Element): void;\n}\n\ndeclare var IntersectionObserver: {\n prototype: IntersectionObserver;\n new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;\n};\n\ninterface IntersectionObserverEntry {\n readonly boundingClientRect: ClientRect | DOMRect;\n readonly intersectionRatio: number;\n readonly intersectionRect: ClientRect | DOMRect;\n readonly isIntersecting: boolean;\n readonly rootBounds: ClientRect | DOMRect;\n readonly target: Element;\n readonly time: number;\n}\n\ndeclare var IntersectionObserverEntry: {\n prototype: IntersectionObserverEntry;\n new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry;\n};\n\ninterface KeyboardEvent extends UIEvent {\n readonly altKey: boolean;\n /** @deprecated */\n char: string;\n /** @deprecated */\n readonly charCode: number;\n readonly code: string;\n readonly ctrlKey: boolean;\n readonly key: string;\n /** @deprecated */\n readonly keyCode: number;\n readonly location: number;\n readonly metaKey: boolean;\n readonly repeat: boolean;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly which: number;\n getModifierState(keyArg: string): boolean;\n /** @deprecated */\n initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n}\n\ndeclare var KeyboardEvent: {\n prototype: KeyboardEvent;\n new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n};\n\ninterface KeyframeEffect extends AnimationEffect {\n composite: CompositeOperation;\n iterationComposite: IterationCompositeOperation;\n target: Element | null;\n getKeyframes(): ComputedKeyframe[];\n setKeyframes(keyframes: Keyframe[] | PropertyIndexedKeyframes | null): void;\n}\n\ndeclare var KeyframeEffect: {\n prototype: KeyframeEffect;\n new(target: Element | null, keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeEffectOptions): KeyframeEffect;\n new(source: KeyframeEffect): KeyframeEffect;\n};\n\ninterface LinkStyle {\n readonly sheet: StyleSheet | null;\n}\n\ninterface ListeningStateChangedEvent extends Event {\n readonly label: string;\n readonly state: ListeningState;\n}\n\ndeclare var ListeningStateChangedEvent: {\n prototype: ListeningStateChangedEvent;\n new(): ListeningStateChangedEvent;\n};\n\ninterface Location {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n assign(url: string): void;\n reload(forcedReload?: boolean): void;\n replace(url: string): void;\n toString(): string;\n}\n\ndeclare var Location: {\n prototype: Location;\n new(): Location;\n};\n\ninterface MSAssertion {\n readonly id: string;\n readonly type: MSCredentialType;\n}\n\ndeclare var MSAssertion: {\n prototype: MSAssertion;\n new(): MSAssertion;\n};\n\ninterface MSBlobBuilder {\n append(data: any, endings?: string): void;\n getBlob(contentType?: string): Blob;\n}\n\ndeclare var MSBlobBuilder: {\n prototype: MSBlobBuilder;\n new(): MSBlobBuilder;\n};\n\ninterface MSCredentials {\n getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise;\n makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise;\n}\n\ndeclare var MSCredentials: {\n prototype: MSCredentials;\n new(): MSCredentials;\n};\n\ninterface MSDCCEvent extends Event {\n readonly maxFr: number;\n readonly maxFs: number;\n}\n\ndeclare var MSDCCEvent: {\n prototype: MSDCCEvent;\n new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent;\n};\n\ninterface MSDSHEvent extends Event {\n readonly sources: number[];\n readonly timestamp: number;\n}\n\ndeclare var MSDSHEvent: {\n prototype: MSDSHEvent;\n new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent;\n};\n\ninterface MSFIDOCredentialAssertion extends MSAssertion {\n readonly algorithm: string | Algorithm;\n readonly attestation: any;\n readonly publicKey: string;\n readonly transportHints: MSTransportType[];\n}\n\ndeclare var MSFIDOCredentialAssertion: {\n prototype: MSFIDOCredentialAssertion;\n new(): MSFIDOCredentialAssertion;\n};\n\ninterface MSFIDOSignature {\n readonly authnrData: string;\n readonly clientData: string;\n readonly signature: string;\n}\n\ndeclare var MSFIDOSignature: {\n prototype: MSFIDOSignature;\n new(): MSFIDOSignature;\n};\n\ninterface MSFIDOSignatureAssertion extends MSAssertion {\n readonly signature: MSFIDOSignature;\n}\n\ndeclare var MSFIDOSignatureAssertion: {\n prototype: MSFIDOSignatureAssertion;\n new(): MSFIDOSignatureAssertion;\n};\n\ninterface MSFileSaver {\n msSaveBlob(blob: any, defaultName?: string): boolean;\n msSaveOrOpenBlob(blob: any, defaultName?: string): boolean;\n}\n\ninterface MSGesture {\n target: Element;\n addPointer(pointerId: number): void;\n stop(): void;\n}\n\ndeclare var MSGesture: {\n prototype: MSGesture;\n new(): MSGesture;\n};\n\ninterface MSGestureEvent extends UIEvent {\n readonly clientX: number;\n readonly clientY: number;\n readonly expansion: number;\n readonly gestureObject: any;\n readonly hwTimestamp: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly rotation: number;\n readonly scale: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly translationX: number;\n readonly translationY: number;\n readonly velocityAngular: number;\n readonly velocityExpansion: number;\n readonly velocityX: number;\n readonly velocityY: number;\n initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n}\n\ndeclare var MSGestureEvent: {\n prototype: MSGestureEvent;\n new(): MSGestureEvent;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n};\n\ninterface MSGraphicsTrust {\n readonly constrictionActive: boolean;\n readonly status: string;\n}\n\ndeclare var MSGraphicsTrust: {\n prototype: MSGraphicsTrust;\n new(): MSGraphicsTrust;\n};\n\ninterface MSInputMethodContextEventMap {\n \"MSCandidateWindowHide\": Event;\n \"MSCandidateWindowShow\": Event;\n \"MSCandidateWindowUpdate\": Event;\n}\n\ninterface MSInputMethodContext extends EventTarget {\n readonly compositionEndOffset: number;\n readonly compositionStartOffset: number;\n oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null;\n readonly target: HTMLElement;\n getCandidateWindowClientRect(): ClientRect;\n getCompositionAlternatives(): string[];\n hasComposition(): boolean;\n isCandidateWindowVisible(): boolean;\n addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSInputMethodContext: {\n prototype: MSInputMethodContext;\n new(): MSInputMethodContext;\n};\n\ninterface MSMediaKeyError {\n readonly code: number;\n readonly systemCode: number;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n}\n\ndeclare var MSMediaKeyError: {\n prototype: MSMediaKeyError;\n new(): MSMediaKeyError;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n};\n\ninterface MSMediaKeyMessageEvent extends Event {\n readonly destinationURL: string | null;\n readonly message: Uint8Array;\n}\n\ndeclare var MSMediaKeyMessageEvent: {\n prototype: MSMediaKeyMessageEvent;\n new(): MSMediaKeyMessageEvent;\n};\n\ninterface MSMediaKeyNeededEvent extends Event {\n readonly initData: Uint8Array | null;\n}\n\ndeclare var MSMediaKeyNeededEvent: {\n prototype: MSMediaKeyNeededEvent;\n new(): MSMediaKeyNeededEvent;\n};\n\ninterface MSMediaKeySession extends EventTarget {\n readonly error: MSMediaKeyError | null;\n readonly keySystem: string;\n readonly sessionId: string;\n close(): void;\n update(key: Uint8Array): void;\n}\n\ndeclare var MSMediaKeySession: {\n prototype: MSMediaKeySession;\n new(): MSMediaKeySession;\n};\n\ninterface MSMediaKeys {\n readonly keySystem: string;\n createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession;\n}\n\ndeclare var MSMediaKeys: {\n prototype: MSMediaKeys;\n new(keySystem: string): MSMediaKeys;\n isTypeSupported(keySystem: string, type?: string | null): boolean;\n isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string;\n};\n\ninterface MSNavigatorDoNotTrack {\n confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean;\n confirmWebWideTrackingException(args: ExceptionInformation): boolean;\n removeSiteSpecificTrackingException(args: ExceptionInformation): void;\n removeWebWideTrackingException(args: ExceptionInformation): void;\n storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void;\n storeWebWideTrackingException(args: StoreExceptionsInformation): void;\n}\n\ninterface MSPointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var MSPointerEvent: {\n prototype: MSPointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent;\n};\n\ninterface MSStream {\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n}\n\ndeclare var MSStream: {\n prototype: MSStream;\n new(): MSStream;\n};\n\ninterface MediaDeviceInfo {\n readonly deviceId: string;\n readonly groupId: string;\n readonly kind: MediaDeviceKind;\n readonly label: string;\n}\n\ndeclare var MediaDeviceInfo: {\n prototype: MediaDeviceInfo;\n new(): MediaDeviceInfo;\n};\n\ninterface MediaDevicesEventMap {\n \"devicechange\": Event;\n}\n\ninterface MediaDevices extends EventTarget {\n ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;\n enumerateDevices(): Promise;\n getSupportedConstraints(): MediaTrackSupportedConstraints;\n getUserMedia(constraints: MediaStreamConstraints): Promise;\n addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaDevices: {\n prototype: MediaDevices;\n new(): MediaDevices;\n};\n\ninterface MediaElementAudioSourceNode extends AudioNode {\n readonly mediaElement: HTMLMediaElement;\n}\n\ndeclare var MediaElementAudioSourceNode: {\n prototype: MediaElementAudioSourceNode;\n new(context: AudioContext, options: MediaElementAudioSourceOptions): MediaElementAudioSourceNode;\n};\n\ninterface MediaEncryptedEvent extends Event {\n readonly initData: ArrayBuffer | null;\n readonly initDataType: string;\n}\n\ndeclare var MediaEncryptedEvent: {\n prototype: MediaEncryptedEvent;\n new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent;\n};\n\ninterface MediaError {\n readonly code: number;\n readonly message: string;\n readonly msExtendedCode: number;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n}\n\ndeclare var MediaError: {\n prototype: MediaError;\n new(): MediaError;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n};\n\ninterface MediaKeyMessageEvent extends Event {\n readonly message: ArrayBuffer;\n readonly messageType: MediaKeyMessageType;\n}\n\ndeclare var MediaKeyMessageEvent: {\n prototype: MediaKeyMessageEvent;\n new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent;\n};\n\ninterface MediaKeySession extends EventTarget {\n readonly closed: Promise;\n readonly expiration: number;\n readonly keyStatuses: MediaKeyStatusMap;\n readonly sessionId: string;\n close(): Promise;\n generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n load(sessionId: string): Promise;\n remove(): Promise;\n update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeySession: {\n prototype: MediaKeySession;\n new(): MediaKeySession;\n};\n\ninterface MediaKeyStatusMap {\n readonly size: number;\n forEach(callback: Function, thisArg?: any): void;\n get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus;\n has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean;\n}\n\ndeclare var MediaKeyStatusMap: {\n prototype: MediaKeyStatusMap;\n new(): MediaKeyStatusMap;\n};\n\ninterface MediaKeySystemAccess {\n readonly keySystem: string;\n createMediaKeys(): Promise;\n getConfiguration(): MediaKeySystemConfiguration;\n}\n\ndeclare var MediaKeySystemAccess: {\n prototype: MediaKeySystemAccess;\n new(): MediaKeySystemAccess;\n};\n\ninterface MediaKeys {\n createSession(sessionType?: MediaKeySessionType): MediaKeySession;\n setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeys: {\n prototype: MediaKeys;\n new(): MediaKeys;\n};\n\ninterface MediaList {\n readonly length: number;\n mediaText: string;\n appendMedium(medium: string): void;\n deleteMedium(medium: string): void;\n item(index: number): string | null;\n toString(): number;\n [index: number]: string;\n}\n\ndeclare var MediaList: {\n prototype: MediaList;\n new(): MediaList;\n};\n\ninterface MediaQueryList {\n readonly matches: boolean;\n readonly media: string;\n addListener(listener: MediaQueryListListener): void;\n removeListener(listener: MediaQueryListListener): void;\n}\n\ndeclare var MediaQueryList: {\n prototype: MediaQueryList;\n new(): MediaQueryList;\n};\n\ninterface MediaSource extends EventTarget {\n readonly activeSourceBuffers: SourceBufferList;\n duration: number;\n readonly readyState: ReadyState;\n readonly sourceBuffers: SourceBufferList;\n addSourceBuffer(type: string): SourceBuffer;\n endOfStream(error?: EndOfStreamError): void;\n removeSourceBuffer(sourceBuffer: SourceBuffer): void;\n}\n\ndeclare var MediaSource: {\n prototype: MediaSource;\n new(): MediaSource;\n isTypeSupported(type: string): boolean;\n};\n\ninterface MediaStreamEventMap {\n \"active\": Event;\n \"addtrack\": MediaStreamTrackEvent;\n \"inactive\": Event;\n \"removetrack\": MediaStreamTrackEvent;\n}\n\ninterface MediaStream extends EventTarget {\n readonly active: boolean;\n readonly id: string;\n onactive: ((this: MediaStream, ev: Event) => any) | null;\n onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n oninactive: ((this: MediaStream, ev: Event) => any) | null;\n onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n addTrack(track: MediaStreamTrack): void;\n clone(): MediaStream;\n getAudioTracks(): MediaStreamTrack[];\n getTrackById(trackId: string): MediaStreamTrack | null;\n getTracks(): MediaStreamTrack[];\n getVideoTracks(): MediaStreamTrack[];\n removeTrack(track: MediaStreamTrack): void;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStream: {\n prototype: MediaStream;\n new(): MediaStream;\n new(stream: MediaStream): MediaStream;\n new(tracks: MediaStreamTrack[]): MediaStream;\n};\n\ninterface MediaStreamAudioDestinationNode extends AudioNode {\n readonly stream: MediaStream;\n}\n\ndeclare var MediaStreamAudioDestinationNode: {\n prototype: MediaStreamAudioDestinationNode;\n new(context: AudioContext, options?: AudioNodeOptions): MediaStreamAudioDestinationNode;\n};\n\ninterface MediaStreamAudioSourceNode extends AudioNode {\n readonly mediaStream: MediaStream;\n}\n\ndeclare var MediaStreamAudioSourceNode: {\n prototype: MediaStreamAudioSourceNode;\n new(context: AudioContext, options: MediaStreamAudioSourceOptions): MediaStreamAudioSourceNode;\n};\n\ninterface MediaStreamError {\n readonly constraintName: string | null;\n readonly message: string | null;\n readonly name: string;\n}\n\ndeclare var MediaStreamError: {\n prototype: MediaStreamError;\n new(): MediaStreamError;\n};\n\ninterface MediaStreamErrorEvent extends Event {\n readonly error: MediaStreamError | null;\n}\n\ndeclare var MediaStreamErrorEvent: {\n prototype: MediaStreamErrorEvent;\n new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent;\n};\n\ninterface MediaStreamEvent extends Event {\n readonly stream: MediaStream | null;\n}\n\ndeclare var MediaStreamEvent: {\n prototype: MediaStreamEvent;\n new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent;\n};\n\ninterface MediaStreamTrackEventMap {\n \"ended\": MediaStreamErrorEvent;\n \"isolationchange\": Event;\n \"mute\": Event;\n \"overconstrained\": MediaStreamErrorEvent;\n \"unmute\": Event;\n}\n\ninterface MediaStreamTrack extends EventTarget {\n enabled: boolean;\n readonly id: string;\n readonly isolated: boolean;\n readonly kind: string;\n readonly label: string;\n readonly muted: boolean;\n onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onisolationchange: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n readonly readonly: boolean;\n readonly readyState: MediaStreamTrackState;\n readonly remote: boolean;\n applyConstraints(constraints: MediaTrackConstraints): Promise;\n clone(): MediaStreamTrack;\n getCapabilities(): MediaTrackCapabilities;\n getConstraints(): MediaTrackConstraints;\n getSettings(): MediaTrackSettings;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStreamTrack: {\n prototype: MediaStreamTrack;\n new(): MediaStreamTrack;\n};\n\ninterface MediaStreamTrackAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaStreamTrackAudioSourceNode: {\n prototype: MediaStreamTrackAudioSourceNode;\n new(context: AudioContext, options: MediaStreamTrackAudioSourceOptions): MediaStreamTrackAudioSourceNode;\n};\n\ninterface MediaStreamTrackEvent extends Event {\n readonly track: MediaStreamTrack;\n}\n\ndeclare var MediaStreamTrackEvent: {\n prototype: MediaStreamTrackEvent;\n new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent;\n};\n\ninterface MessageChannel {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\ndeclare var MessageChannel: {\n prototype: MessageChannel;\n new(): MessageChannel;\n};\n\ninterface MessageEvent extends Event {\n readonly data: any;\n readonly origin: string;\n readonly ports: ReadonlyArray;\n readonly source: MessageEventSource;\n initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void;\n}\n\ndeclare var MessageEvent: {\n prototype: MessageEvent;\n new(type: string, eventInitDict?: MessageEventInit): MessageEvent;\n};\n\ninterface MessagePortEventMap {\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface MessagePort extends EventTarget {\n onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;\n /**\n * Disconnects the port, so that it is no longer active.\n */\n close(): void;\n /**\n * Posts a message through the channel. Objects listed in transfer are\n * transferred, not just cloned, meaning that they are no longer usable on the sending side.\n * Throws a \"DataCloneError\" DOMException if\n * transfer contains duplicate objects or port, or if message\n * could not be cloned.\n */\n postMessage(message: any, transfer?: any[]): void;\n /**\n * Begins dispatching messages received on the port.\n */\n start(): void;\n addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MessagePort: {\n prototype: MessagePort;\n new(): MessagePort;\n};\n\ninterface MimeType {\n readonly description: string;\n readonly enabledPlugin: Plugin;\n readonly suffixes: string;\n readonly type: string;\n}\n\ndeclare var MimeType: {\n prototype: MimeType;\n new(): MimeType;\n};\n\ninterface MimeTypeArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(type: string): Plugin;\n [index: number]: Plugin;\n}\n\ndeclare var MimeTypeArray: {\n prototype: MimeTypeArray;\n new(): MimeTypeArray;\n};\n\ninterface MouseEvent extends UIEvent {\n readonly altKey: boolean;\n readonly button: number;\n readonly buttons: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly ctrlKey: boolean;\n /** @deprecated */\n readonly fromElement: Element;\n readonly layerX: number;\n readonly layerY: number;\n readonly metaKey: boolean;\n readonly movementX: number;\n readonly movementY: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly relatedTarget: EventTarget;\n readonly screenX: number;\n readonly screenY: number;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly toElement: Element;\n /** @deprecated */\n readonly which: number;\n readonly x: number;\n readonly y: number;\n getModifierState(keyArg: string): boolean;\n initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;\n}\n\ndeclare var MouseEvent: {\n prototype: MouseEvent;\n new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;\n};\n\ninterface MutationEvent extends Event {\n readonly attrChange: number;\n readonly attrName: string;\n readonly newValue: string;\n readonly prevValue: string;\n readonly relatedNode: Node;\n initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n}\n\ndeclare var MutationEvent: {\n prototype: MutationEvent;\n new(): MutationEvent;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n};\n\ninterface MutationObserver {\n disconnect(): void;\n observe(target: Node, options: MutationObserverInit): void;\n takeRecords(): MutationRecord[];\n}\n\ndeclare var MutationObserver: {\n prototype: MutationObserver;\n new(callback: MutationCallback): MutationObserver;\n};\n\ninterface MutationRecord {\n readonly addedNodes: NodeList;\n readonly attributeName: string | null;\n readonly attributeNamespace: string | null;\n readonly nextSibling: Node | null;\n readonly oldValue: string | null;\n readonly previousSibling: Node | null;\n readonly removedNodes: NodeList;\n readonly target: Node;\n readonly type: MutationRecordType;\n}\n\ndeclare var MutationRecord: {\n prototype: MutationRecord;\n new(): MutationRecord;\n};\n\ninterface NamedNodeMap {\n readonly length: number;\n getNamedItem(qualifiedName: string): Attr | null;\n getNamedItemNS(namespace: string | null, localName: string): Attr | null;\n item(index: number): Attr | null;\n removeNamedItem(qualifiedName: string): Attr;\n removeNamedItemNS(namespace: string | null, localName: string): Attr;\n setNamedItem(attr: Attr): Attr | null;\n setNamedItemNS(attr: Attr): Attr | null;\n [index: number]: Attr;\n}\n\ndeclare var NamedNodeMap: {\n prototype: NamedNodeMap;\n new(): NamedNodeMap;\n};\n\ninterface NavigationPreloadManager {\n disable(): Promise;\n enable(): Promise;\n getState(): Promise;\n setHeaderValue(value: string): Promise;\n}\n\ndeclare var NavigationPreloadManager: {\n prototype: NavigationPreloadManager;\n new(): NavigationPreloadManager;\n};\n\ninterface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage {\n readonly activeVRDisplays: ReadonlyArray;\n readonly authentication: WebAuthentication;\n readonly cookieEnabled: boolean;\n readonly doNotTrack: string | null;\n gamepadInputEmulation: GamepadInputEmulationType;\n readonly geolocation: Geolocation;\n readonly maxTouchPoints: number;\n readonly mimeTypes: MimeTypeArray;\n readonly msManipulationViewsEnabled: boolean;\n readonly msMaxTouchPoints: number;\n readonly msPointerEnabled: boolean;\n readonly plugins: PluginArray;\n readonly pointerEnabled: boolean;\n readonly serviceWorker: ServiceWorkerContainer;\n readonly webdriver: boolean;\n getGamepads(): (Gamepad | null)[];\n getVRDisplays(): Promise;\n javaEnabled(): boolean;\n msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;\n requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise;\n vibrate(pattern: number | number[]): boolean;\n}\n\ndeclare var Navigator: {\n prototype: Navigator;\n new(): Navigator;\n};\n\ninterface NavigatorBeacon {\n sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean;\n}\n\ninterface NavigatorConcurrentHardware {\n readonly hardwareConcurrency: number;\n}\n\ninterface NavigatorContentUtils {\n}\n\ninterface NavigatorID {\n readonly appCodeName: string;\n readonly appName: string;\n readonly appVersion: string;\n readonly platform: string;\n readonly product: string;\n readonly productSub: string;\n readonly userAgent: string;\n readonly vendor: string;\n readonly vendorSub: string;\n}\n\ninterface NavigatorLanguage {\n readonly language: string;\n readonly languages: ReadonlyArray;\n}\n\ninterface NavigatorOnLine {\n readonly onLine: boolean;\n}\n\ninterface NavigatorStorage {\n readonly storage: StorageManager;\n}\n\ninterface NavigatorStorageUtils {\n}\n\ninterface NavigatorUserMedia {\n readonly mediaDevices: MediaDevices;\n getDisplayMedia(constraints: MediaStreamConstraints): Promise;\n getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;\n}\n\ninterface Node extends EventTarget {\n readonly baseURI: string | null;\n readonly childNodes: NodeListOf;\n readonly firstChild: Node | null;\n readonly isConnected: boolean;\n readonly lastChild: Node | null;\n readonly localName: string | null;\n readonly namespaceURI: string | null;\n readonly nextSibling: Node | null;\n readonly nodeName: string;\n readonly nodeType: number;\n nodeValue: string | null;\n readonly ownerDocument: Document;\n readonly parentElement: HTMLElement | null;\n readonly parentNode: Node | null;\n readonly previousSibling: Node | null;\n textContent: string | null;\n appendChild(newChild: T): T;\n cloneNode(deep?: boolean): Node;\n compareDocumentPosition(other: Node): number;\n contains(child: Node): boolean;\n hasChildNodes(): boolean;\n insertBefore(newChild: T, refChild: Node | null): T;\n isDefaultNamespace(namespaceURI: string | null): boolean;\n isEqualNode(arg: Node): boolean;\n isSameNode(other: Node): boolean;\n lookupNamespaceURI(prefix: string | null): string | null;\n lookupPrefix(namespaceURI: string | null): string | null;\n normalize(): void;\n removeChild(oldChild: T): T;\n replaceChild(newChild: Node, oldChild: T): T;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n}\n\ndeclare var Node: {\n prototype: Node;\n new(): Node;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n};\n\ninterface NodeFilter {\n acceptNode(node: Node): number;\n}\n\ndeclare var NodeFilter: {\n readonly FILTER_ACCEPT: number;\n readonly FILTER_REJECT: number;\n readonly FILTER_SKIP: number;\n readonly SHOW_ALL: number;\n readonly SHOW_ATTRIBUTE: number;\n readonly SHOW_CDATA_SECTION: number;\n readonly SHOW_COMMENT: number;\n readonly SHOW_DOCUMENT: number;\n readonly SHOW_DOCUMENT_FRAGMENT: number;\n readonly SHOW_DOCUMENT_TYPE: number;\n readonly SHOW_ELEMENT: number;\n readonly SHOW_ENTITY: number;\n readonly SHOW_ENTITY_REFERENCE: number;\n readonly SHOW_NOTATION: number;\n readonly SHOW_PROCESSING_INSTRUCTION: number;\n readonly SHOW_TEXT: number;\n};\n\ninterface NodeIterator {\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n detach(): void;\n nextNode(): Node | null;\n previousNode(): Node | null;\n}\n\ndeclare var NodeIterator: {\n prototype: NodeIterator;\n new(): NodeIterator;\n};\n\ninterface NodeList {\n readonly length: number;\n item(index: number): Node;\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: Node, key: number, parent: NodeList) => void, thisArg?: any): void;\n [index: number]: Node;\n}\n\ndeclare var NodeList: {\n prototype: NodeList;\n new(): NodeList;\n};\n\ninterface NodeListOf extends NodeList {\n length: number;\n item(index: number): TNode;\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: TNode, key: number, parent: NodeListOf) => void, thisArg?: any): void;\n [index: number]: TNode;\n}\n\ninterface NodeSelector {\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface NotificationEventMap {\n \"click\": Event;\n \"close\": Event;\n \"error\": Event;\n \"show\": Event;\n}\n\ninterface Notification extends EventTarget {\n readonly actions: ReadonlyArray;\n readonly badge: string;\n readonly body: string;\n readonly data: any;\n readonly dir: NotificationDirection;\n readonly icon: string;\n readonly image: string;\n readonly lang: string;\n onclick: ((this: Notification, ev: Event) => any) | null;\n onclose: ((this: Notification, ev: Event) => any) | null;\n onerror: ((this: Notification, ev: Event) => any) | null;\n onshow: ((this: Notification, ev: Event) => any) | null;\n readonly renotify: boolean;\n readonly requireInteraction: boolean;\n readonly silent: boolean;\n readonly tag: string;\n readonly timestamp: number;\n readonly title: string;\n readonly vibrate: ReadonlyArray;\n close(): void;\n addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Notification: {\n prototype: Notification;\n new(title: string, options?: NotificationOptions): Notification;\n readonly maxActions: number;\n readonly permission: NotificationPermission;\n requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise;\n};\n\ninterface OES_element_index_uint {\n}\n\ndeclare var OES_element_index_uint: {\n prototype: OES_element_index_uint;\n new(): OES_element_index_uint;\n};\n\ninterface OES_standard_derivatives {\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n}\n\ndeclare var OES_standard_derivatives: {\n prototype: OES_standard_derivatives;\n new(): OES_standard_derivatives;\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n};\n\ninterface OES_texture_float {\n}\n\ndeclare var OES_texture_float: {\n prototype: OES_texture_float;\n new(): OES_texture_float;\n};\n\ninterface OES_texture_float_linear {\n}\n\ndeclare var OES_texture_float_linear: {\n prototype: OES_texture_float_linear;\n new(): OES_texture_float_linear;\n};\n\ninterface OES_texture_half_float {\n readonly HALF_FLOAT_OES: number;\n}\n\ndeclare var OES_texture_half_float: {\n prototype: OES_texture_half_float;\n new(): OES_texture_half_float;\n readonly HALF_FLOAT_OES: number;\n};\n\ninterface OES_texture_half_float_linear {\n}\n\ndeclare var OES_texture_half_float_linear: {\n prototype: OES_texture_half_float_linear;\n new(): OES_texture_half_float_linear;\n};\n\ninterface OES_vertex_array_object {\n readonly VERTEX_ARRAY_BINDING_OES: number;\n bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n createVertexArrayOES(): WebGLVertexArrayObjectOES;\n deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES;\n}\n\ninterface OfflineAudioCompletionEvent extends Event {\n readonly renderedBuffer: AudioBuffer;\n}\n\ndeclare var OfflineAudioCompletionEvent: {\n prototype: OfflineAudioCompletionEvent;\n new(type: string, eventInitDict: OfflineAudioCompletionEventInit): OfflineAudioCompletionEvent;\n};\n\ninterface OfflineAudioContextEventMap extends BaseAudioContextEventMap {\n \"complete\": OfflineAudioCompletionEvent;\n}\n\ninterface OfflineAudioContext extends BaseAudioContext {\n readonly length: number;\n oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null;\n startRendering(): Promise;\n suspend(suspendTime: number): Promise;\n addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OfflineAudioContext: {\n prototype: OfflineAudioContext;\n new(contextOptions: OfflineAudioContextOptions): OfflineAudioContext;\n new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext;\n};\n\ninterface OscillatorNode extends AudioScheduledSourceNode {\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n type: OscillatorType;\n setPeriodicWave(periodicWave: PeriodicWave): void;\n addEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OscillatorNode: {\n prototype: OscillatorNode;\n new(context: BaseAudioContext, options?: OscillatorOptions): OscillatorNode;\n};\n\ninterface OverflowEvent extends UIEvent {\n readonly horizontalOverflow: boolean;\n readonly orient: number;\n readonly verticalOverflow: boolean;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n}\n\ndeclare var OverflowEvent: {\n prototype: OverflowEvent;\n new(): OverflowEvent;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n};\n\ninterface PageTransitionEvent extends Event {\n readonly persisted: boolean;\n}\n\ndeclare var PageTransitionEvent: {\n prototype: PageTransitionEvent;\n new(): PageTransitionEvent;\n};\n\ninterface PannerNode extends AudioNode {\n coneInnerAngle: number;\n coneOuterAngle: number;\n coneOuterGain: number;\n distanceModel: DistanceModelType;\n maxDistance: number;\n readonly orientationX: AudioParam;\n readonly orientationY: AudioParam;\n readonly orientationZ: AudioParam;\n panningModel: PanningModelType;\n readonly positionX: AudioParam;\n readonly positionY: AudioParam;\n readonly positionZ: AudioParam;\n refDistance: number;\n rolloffFactor: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n}\n\ndeclare var PannerNode: {\n prototype: PannerNode;\n new(context: BaseAudioContext, options?: PannerOptions): PannerNode;\n};\n\ninterface ParentNode {\n readonly childElementCount: number;\n readonly children: HTMLCollection;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface Path2D extends CanvasPathMethods {\n}\n\ndeclare var Path2D: {\n prototype: Path2D;\n new(d?: Path2D | string): Path2D;\n};\n\ninterface PaymentAddress {\n readonly addressLine: string[];\n readonly city: string;\n readonly country: string;\n readonly dependentLocality: string;\n readonly languageCode: string;\n readonly organization: string;\n readonly phone: string;\n readonly postalCode: string;\n readonly recipient: string;\n readonly region: string;\n readonly sortingCode: string;\n toJSON(): any;\n}\n\ndeclare var PaymentAddress: {\n prototype: PaymentAddress;\n new(): PaymentAddress;\n};\n\ninterface PaymentRequestEventMap {\n \"shippingaddresschange\": Event;\n \"shippingoptionchange\": Event;\n}\n\ninterface PaymentRequest extends EventTarget {\n readonly id: string;\n onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null;\n onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n readonly shippingType: PaymentShippingType | null;\n abort(): Promise;\n canMakePayment(): Promise;\n show(): Promise;\n addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var PaymentRequest: {\n prototype: PaymentRequest;\n new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest;\n};\n\ninterface PaymentRequestUpdateEvent extends Event {\n updateWith(detailsPromise: Promise): void;\n}\n\ndeclare var PaymentRequestUpdateEvent: {\n prototype: PaymentRequestUpdateEvent;\n new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;\n};\n\ninterface PaymentResponse {\n readonly details: any;\n readonly methodName: string;\n readonly payerEmail: string | null;\n readonly payerName: string | null;\n readonly payerPhone: string | null;\n readonly requestId: string;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n complete(result?: PaymentComplete): Promise;\n toJSON(): any;\n}\n\ndeclare var PaymentResponse: {\n prototype: PaymentResponse;\n new(): PaymentResponse;\n};\n\ninterface PerfWidgetExternal {\n readonly activeNetworkRequestCount: number;\n readonly averageFrameTime: number;\n readonly averagePaintTime: number;\n readonly extraInformationEnabled: boolean;\n readonly independentRenderingEnabled: boolean;\n readonly irDisablingContentString: string;\n readonly irStatusAvailable: boolean;\n readonly maxCpuSpeed: number;\n readonly paintRequestsPerSecond: number;\n readonly performanceCounter: number;\n readonly performanceCounterFrequency: number;\n addEventListener(eventType: string, callback: Function): void;\n getMemoryUsage(): number;\n getProcessCpuUsage(): number;\n getRecentCpuUsage(last: number | null): any;\n getRecentFrames(last: number | null): any;\n getRecentMemoryUsage(last: number | null): any;\n getRecentPaintRequests(last: number | null): any;\n removeEventListener(eventType: string, callback: Function): void;\n repositionWindow(x: number, y: number): void;\n resizeWindow(width: number, height: number): void;\n}\n\ndeclare var PerfWidgetExternal: {\n prototype: PerfWidgetExternal;\n new(): PerfWidgetExternal;\n};\n\ninterface PerformanceEventMap {\n \"resourcetimingbufferfull\": Event;\n}\n\ninterface Performance extends EventTarget {\n /** @deprecated */\n readonly navigation: PerformanceNavigation;\n onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null;\n readonly timeOrigin: number;\n /** @deprecated */\n readonly timing: PerformanceTiming;\n clearMarks(markName?: string): void;\n clearMeasures(measureName?: string): void;\n clearResourceTimings(): void;\n getEntries(): PerformanceEntryList;\n getEntriesByName(name: string, type?: string): PerformanceEntryList;\n getEntriesByType(type: string): PerformanceEntryList;\n mark(markName: string): void;\n measure(measureName: string, startMark?: string, endMark?: string): void;\n now(): number;\n setResourceTimingBufferSize(maxSize: number): void;\n toJSON(): any;\n addEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Performance: {\n prototype: Performance;\n new(): Performance;\n};\n\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceEntry: {\n prototype: PerformanceEntry;\n new(): PerformanceEntry;\n};\n\ninterface PerformanceMark extends PerformanceEntry {\n}\n\ndeclare var PerformanceMark: {\n prototype: PerformanceMark;\n new(): PerformanceMark;\n};\n\ninterface PerformanceMeasure extends PerformanceEntry {\n}\n\ndeclare var PerformanceMeasure: {\n prototype: PerformanceMeasure;\n new(): PerformanceMeasure;\n};\n\ninterface PerformanceNavigation {\n readonly redirectCount: number;\n readonly type: number;\n toJSON(): any;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n}\n\ndeclare var PerformanceNavigation: {\n prototype: PerformanceNavigation;\n new(): PerformanceNavigation;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n};\n\ninterface PerformanceNavigationTiming extends PerformanceResourceTiming {\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly redirectCount: number;\n readonly type: NavigationType;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceNavigationTiming: {\n prototype: PerformanceNavigationTiming;\n new(): PerformanceNavigationTiming;\n};\n\ninterface PerformanceObserver {\n disconnect(): void;\n observe(options: PerformanceObserverInit): void;\n takeRecords(): PerformanceEntryList;\n}\n\ndeclare var PerformanceObserver: {\n prototype: PerformanceObserver;\n new(callback: PerformanceObserverCallback): PerformanceObserver;\n};\n\ninterface PerformanceObserverEntryList {\n getEntries(): PerformanceEntryList;\n getEntriesByName(name: string, type?: string): PerformanceEntryList;\n getEntriesByType(type: string): PerformanceEntryList;\n}\n\ndeclare var PerformanceObserverEntryList: {\n prototype: PerformanceObserverEntryList;\n new(): PerformanceObserverEntryList;\n};\n\ninterface PerformanceResourceTiming extends PerformanceEntry {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly decodedBodySize: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly encodedBodySize: number;\n readonly fetchStart: number;\n readonly initiatorType: string;\n readonly nextHopProtocol: string;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly transferSize: number;\n readonly workerStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceResourceTiming: {\n prototype: PerformanceResourceTiming;\n new(): PerformanceResourceTiming;\n};\n\ninterface PerformanceTiming {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly domLoading: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly navigationStart: number;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceTiming: {\n prototype: PerformanceTiming;\n new(): PerformanceTiming;\n};\n\ninterface PeriodicWave {\n}\n\ndeclare var PeriodicWave: {\n prototype: PeriodicWave;\n new(context: BaseAudioContext, options?: PeriodicWaveOptions): PeriodicWave;\n};\n\ninterface PermissionRequest extends DeferredPermissionRequest {\n readonly state: MSWebViewPermissionState;\n defer(): void;\n}\n\ndeclare var PermissionRequest: {\n prototype: PermissionRequest;\n new(): PermissionRequest;\n};\n\ninterface PermissionRequestedEvent extends Event {\n readonly permissionRequest: PermissionRequest;\n}\n\ndeclare var PermissionRequestedEvent: {\n prototype: PermissionRequestedEvent;\n new(): PermissionRequestedEvent;\n};\n\ninterface Plugin {\n readonly description: string;\n readonly filename: string;\n readonly length: number;\n readonly name: string;\n readonly version: string;\n item(index: number): MimeType;\n namedItem(type: string): MimeType;\n [index: number]: MimeType;\n}\n\ndeclare var Plugin: {\n prototype: Plugin;\n new(): Plugin;\n};\n\ninterface PluginArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(name: string): Plugin;\n refresh(reload?: boolean): void;\n [index: number]: Plugin;\n}\n\ndeclare var PluginArray: {\n prototype: PluginArray;\n new(): PluginArray;\n};\n\ninterface PointerEvent extends MouseEvent {\n readonly height: number;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: string;\n readonly pressure: number;\n readonly tangentialPressure: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly twist: number;\n readonly width: number;\n}\n\ndeclare var PointerEvent: {\n prototype: PointerEvent;\n new(type: string, eventInitDict?: PointerEventInit): PointerEvent;\n};\n\ninterface PopStateEvent extends Event {\n readonly state: any;\n}\n\ndeclare var PopStateEvent: {\n prototype: PopStateEvent;\n new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent;\n};\n\ninterface Position {\n readonly coords: Coordinates;\n readonly timestamp: number;\n}\n\ninterface PositionError {\n readonly code: number;\n readonly message: string;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n}\n\ninterface ProcessingInstruction extends CharacterData {\n readonly target: string;\n}\n\ndeclare var ProcessingInstruction: {\n prototype: ProcessingInstruction;\n new(): ProcessingInstruction;\n};\n\ninterface ProgressEvent extends Event {\n readonly lengthComputable: boolean;\n readonly loaded: number;\n readonly total: number;\n}\n\ndeclare var ProgressEvent: {\n prototype: ProgressEvent;\n new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;\n};\n\ninterface PromiseRejectionEvent extends Event {\n readonly promise: PromiseLike;\n readonly reason: any;\n}\n\ndeclare var PromiseRejectionEvent: {\n prototype: PromiseRejectionEvent;\n new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;\n};\n\ninterface PushManager {\n getSubscription(): Promise;\n permissionState(options?: PushSubscriptionOptionsInit): Promise;\n subscribe(options?: PushSubscriptionOptionsInit): Promise;\n}\n\ndeclare var PushManager: {\n prototype: PushManager;\n new(): PushManager;\n readonly supportedContentEncodings: ReadonlyArray;\n};\n\ninterface PushSubscription {\n readonly endpoint: string;\n readonly expirationTime: number | null;\n readonly options: PushSubscriptionOptions;\n getKey(name: PushEncryptionKeyName): ArrayBuffer | null;\n toJSON(): PushSubscriptionJSON;\n unsubscribe(): Promise;\n}\n\ndeclare var PushSubscription: {\n prototype: PushSubscription;\n new(): PushSubscription;\n};\n\ninterface PushSubscriptionOptions {\n readonly applicationServerKey: ArrayBuffer | null;\n readonly userVisibleOnly: boolean;\n}\n\ndeclare var PushSubscriptionOptions: {\n prototype: PushSubscriptionOptions;\n new(): PushSubscriptionOptions;\n};\n\ninterface RTCCertificate {\n readonly expires: number;\n getFingerprints(): RTCDtlsFingerprint[];\n}\n\ndeclare var RTCCertificate: {\n prototype: RTCCertificate;\n new(): RTCCertificate;\n getSupportedAlgorithms(): AlgorithmIdentifier[];\n};\n\ninterface RTCDTMFSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDTMFSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n ontonechange: ((this: RTCDTMFSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDTMFSender: {\n prototype: RTCDTMFSender;\n new(): RTCDTMFSender;\n};\n\ninterface RTCDTMFToneChangeEvent extends Event {\n readonly tone: string;\n}\n\ndeclare var RTCDTMFToneChangeEvent: {\n prototype: RTCDTMFToneChangeEvent;\n new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent;\n};\n\ninterface RTCDataChannelEventMap {\n \"bufferedamountlow\": Event;\n \"close\": Event;\n \"error\": RTCErrorEvent;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface RTCDataChannel extends EventTarget {\n binaryType: string;\n readonly bufferedAmount: number;\n bufferedAmountLowThreshold: number;\n readonly id: number | null;\n readonly label: string;\n readonly maxPacketLifeTime: number | null;\n readonly maxRetransmits: number | null;\n readonly negotiated: boolean;\n onbufferedamountlow: ((this: RTCDataChannel, ev: Event) => any) | null;\n onclose: ((this: RTCDataChannel, ev: Event) => any) | null;\n onerror: ((this: RTCDataChannel, ev: RTCErrorEvent) => any) | null;\n onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null;\n onopen: ((this: RTCDataChannel, ev: Event) => any) | null;\n readonly ordered: boolean;\n readonly priority: RTCPriorityType;\n readonly protocol: string;\n readonly readyState: RTCDataChannelState;\n close(): void;\n send(data: string): void;\n send(data: Blob): void;\n send(data: ArrayBuffer): void;\n send(data: ArrayBufferView): void;\n addEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDataChannel: {\n prototype: RTCDataChannel;\n new(): RTCDataChannel;\n};\n\ninterface RTCDataChannelEvent extends Event {\n readonly channel: RTCDataChannel;\n}\n\ndeclare var RTCDataChannelEvent: {\n prototype: RTCDataChannelEvent;\n new(type: string, eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent;\n};\n\ninterface RTCDtlsTransportEventMap {\n \"error\": RTCErrorEvent;\n \"statechange\": Event;\n}\n\ninterface RTCDtlsTransport extends EventTarget {\n onerror: ((this: RTCDtlsTransport, ev: RTCErrorEvent) => any) | null;\n onstatechange: ((this: RTCDtlsTransport, ev: Event) => any) | null;\n readonly state: RTCDtlsTransportState;\n readonly transport: RTCIceTransport;\n getRemoteCertificates(): ArrayBuffer[];\n addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtlsTransport: {\n prototype: RTCDtlsTransport;\n new(): RTCDtlsTransport;\n};\n\ninterface RTCDtlsTransportStateChangedEvent extends Event {\n readonly state: RTCDtlsTransportState;\n}\n\ndeclare var RTCDtlsTransportStateChangedEvent: {\n prototype: RTCDtlsTransportStateChangedEvent;\n new(): RTCDtlsTransportStateChangedEvent;\n};\n\ninterface RTCDtmfSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDtmfSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n readonly duration: number;\n readonly interToneGap: number;\n ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly sender: RTCRtpSender;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtmfSender: {\n prototype: RTCDtmfSender;\n new(sender: RTCRtpSender): RTCDtmfSender;\n};\n\ninterface RTCError extends Error {\n errorDetail: string;\n httpRequestStatusCode: number;\n message: string;\n name: string;\n receivedAlert: number | null;\n sctpCauseCode: number;\n sdpLineNumber: number;\n sentAlert: number | null;\n}\n\ndeclare var RTCError: {\n prototype: RTCError;\n new(errorDetail?: string, message?: string): RTCError;\n};\n\ninterface RTCErrorEvent extends Event {\n readonly error: RTCError | null;\n}\n\ndeclare var RTCErrorEvent: {\n prototype: RTCErrorEvent;\n new(type: string, eventInitDict: RTCErrorEventInit): RTCErrorEvent;\n};\n\ninterface RTCIceCandidate {\n readonly candidate: string;\n readonly component: RTCIceComponent | null;\n readonly foundation: string | null;\n readonly ip: string | null;\n readonly port: number | null;\n readonly priority: number | null;\n readonly protocol: RTCIceProtocol | null;\n readonly relatedAddress: string | null;\n readonly relatedPort: number | null;\n readonly sdpMLineIndex: number | null;\n readonly sdpMid: string | null;\n readonly tcpType: RTCIceTcpCandidateType | null;\n readonly type: RTCIceCandidateType | null;\n readonly usernameFragment: string | null;\n toJSON(): RTCIceCandidateInit;\n}\n\ndeclare var RTCIceCandidate: {\n prototype: RTCIceCandidate;\n new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate;\n};\n\ninterface RTCIceCandidatePairChangedEvent extends Event {\n readonly pair: RTCIceCandidatePair;\n}\n\ndeclare var RTCIceCandidatePairChangedEvent: {\n prototype: RTCIceCandidatePairChangedEvent;\n new(): RTCIceCandidatePairChangedEvent;\n};\n\ninterface RTCIceGathererEventMap {\n \"error\": Event;\n \"localcandidate\": RTCIceGathererEvent;\n}\n\ninterface RTCIceGatherer extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n onerror: ((this: RTCIceGatherer, ev: Event) => any) | null;\n onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null;\n createAssociatedGatherer(): RTCIceGatherer;\n getLocalCandidates(): RTCIceCandidateDictionary[];\n getLocalParameters(): RTCIceParameters;\n addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceGatherer: {\n prototype: RTCIceGatherer;\n new(options: RTCIceGatherOptions): RTCIceGatherer;\n};\n\ninterface RTCIceGathererEvent extends Event {\n readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete;\n}\n\ndeclare var RTCIceGathererEvent: {\n prototype: RTCIceGathererEvent;\n new(): RTCIceGathererEvent;\n};\n\ninterface RTCIceTransportEventMap {\n \"gatheringstatechange\": Event;\n \"selectedcandidatepairchange\": Event;\n \"statechange\": Event;\n}\n\ninterface RTCIceTransport extends EventTarget {\n readonly component: RTCIceComponent;\n readonly gatheringState: RTCIceGathererState;\n ongatheringstatechange: ((this: RTCIceTransport, ev: Event) => any) | null;\n onselectedcandidatepairchange: ((this: RTCIceTransport, ev: Event) => any) | null;\n onstatechange: ((this: RTCIceTransport, ev: Event) => any) | null;\n readonly role: RTCIceRole;\n readonly state: RTCIceTransportState;\n getLocalCandidates(): RTCIceCandidate[];\n getLocalParameters(): RTCIceParameters | null;\n getRemoteCandidates(): RTCIceCandidate[];\n getRemoteParameters(): RTCIceParameters | null;\n getSelectedCandidatePair(): RTCIceCandidatePair | null;\n addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceTransport: {\n prototype: RTCIceTransport;\n new(): RTCIceTransport;\n};\n\ninterface RTCIceTransportStateChangedEvent extends Event {\n readonly state: RTCIceTransportState;\n}\n\ndeclare var RTCIceTransportStateChangedEvent: {\n prototype: RTCIceTransportStateChangedEvent;\n new(): RTCIceTransportStateChangedEvent;\n};\n\ninterface RTCIdentityAssertion {\n idp: string;\n name: string;\n}\n\ndeclare var RTCIdentityAssertion: {\n prototype: RTCIdentityAssertion;\n new(idp: string, name: string): RTCIdentityAssertion;\n};\n\ninterface RTCPeerConnectionEventMap {\n \"connectionstatechange\": Event;\n \"datachannel\": RTCDataChannelEvent;\n \"icecandidate\": RTCPeerConnectionIceEvent;\n \"icecandidateerror\": RTCPeerConnectionIceErrorEvent;\n \"iceconnectionstatechange\": Event;\n \"icegatheringstatechange\": Event;\n \"negotiationneeded\": Event;\n \"signalingstatechange\": Event;\n \"statsended\": RTCStatsEvent;\n \"track\": RTCTrackEvent;\n}\n\ninterface RTCPeerConnection extends EventTarget {\n readonly canTrickleIceCandidates: boolean | null;\n readonly connectionState: RTCPeerConnectionState;\n readonly currentLocalDescription: RTCSessionDescription | null;\n readonly currentRemoteDescription: RTCSessionDescription | null;\n readonly iceConnectionState: RTCIceConnectionState;\n readonly iceGatheringState: RTCIceGatheringState;\n readonly idpErrorInfo: string | null;\n readonly idpLoginUrl: string | null;\n readonly localDescription: RTCSessionDescription | null;\n onconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n ondatachannel: ((this: RTCPeerConnection, ev: RTCDataChannelEvent) => any) | null;\n onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null;\n onicecandidateerror: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceErrorEvent) => any) | null;\n oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onstatsended: ((this: RTCPeerConnection, ev: RTCStatsEvent) => any) | null;\n ontrack: ((this: RTCPeerConnection, ev: RTCTrackEvent) => any) | null;\n readonly peerIdentity: Promise;\n readonly pendingLocalDescription: RTCSessionDescription | null;\n readonly pendingRemoteDescription: RTCSessionDescription | null;\n readonly remoteDescription: RTCSessionDescription | null;\n readonly sctp: RTCSctpTransport | null;\n readonly signalingState: RTCSignalingState;\n addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise;\n addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender;\n addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver;\n close(): void;\n createAnswer(options?: RTCOfferOptions): Promise;\n createDataChannel(label: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel;\n createOffer(options?: RTCOfferOptions): Promise;\n getConfiguration(): RTCConfiguration;\n getIdentityAssertion(): Promise;\n getReceivers(): RTCRtpReceiver[];\n getSenders(): RTCRtpSender[];\n getStats(selector?: MediaStreamTrack | null): Promise;\n getTransceivers(): RTCRtpTransceiver[];\n removeTrack(sender: RTCRtpSender): void;\n setConfiguration(configuration: RTCConfiguration): void;\n setIdentityProvider(provider: string, options?: RTCIdentityProviderOptions): void;\n setLocalDescription(description: RTCSessionDescriptionInit): Promise;\n setRemoteDescription(description: RTCSessionDescriptionInit): Promise;\n addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCPeerConnection: {\n prototype: RTCPeerConnection;\n new(configuration?: RTCConfiguration): RTCPeerConnection;\n generateCertificate(keygenAlgorithm: AlgorithmIdentifier): Promise;\n getDefaultIceServers(): RTCIceServer[];\n};\n\ninterface RTCPeerConnectionIceErrorEvent extends Event {\n readonly errorCode: number;\n readonly errorText: string;\n readonly hostCandidate: string;\n readonly url: string;\n}\n\ndeclare var RTCPeerConnectionIceErrorEvent: {\n prototype: RTCPeerConnectionIceErrorEvent;\n new(type: string, eventInitDict: RTCPeerConnectionIceErrorEventInit): RTCPeerConnectionIceErrorEvent;\n};\n\ninterface RTCPeerConnectionIceEvent extends Event {\n readonly candidate: RTCIceCandidate | null;\n readonly url: string | null;\n}\n\ndeclare var RTCPeerConnectionIceEvent: {\n prototype: RTCPeerConnectionIceEvent;\n new(type: string, eventInitDict?: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent;\n};\n\ninterface RTCRtpReceiver {\n readonly rtcpTransport: RTCDtlsTransport | null;\n readonly track: MediaStreamTrack;\n readonly transport: RTCDtlsTransport | null;\n getContributingSources(): RTCRtpContributingSource[];\n getParameters(): RTCRtpReceiveParameters;\n getStats(): Promise;\n getSynchronizationSources(): RTCRtpSynchronizationSource[];\n}\n\ndeclare var RTCRtpReceiver: {\n prototype: RTCRtpReceiver;\n new(): RTCRtpReceiver;\n getCapabilities(kind: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpSender {\n readonly dtmf: RTCDTMFSender | null;\n readonly rtcpTransport: RTCDtlsTransport | null;\n readonly track: MediaStreamTrack | null;\n readonly transport: RTCDtlsTransport | null;\n getParameters(): RTCRtpSendParameters;\n getStats(): Promise;\n replaceTrack(withTrack: MediaStreamTrack | null): Promise;\n setParameters(parameters: RTCRtpSendParameters): Promise;\n setStreams(...streams: MediaStream[]): void;\n}\n\ndeclare var RTCRtpSender: {\n prototype: RTCRtpSender;\n new(): RTCRtpSender;\n getCapabilities(kind: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpTransceiver {\n readonly currentDirection: RTCRtpTransceiverDirection | null;\n direction: RTCRtpTransceiverDirection;\n readonly mid: string | null;\n readonly receiver: RTCRtpReceiver;\n readonly sender: RTCRtpSender;\n readonly stopped: boolean;\n setCodecPreferences(codecs: RTCRtpCodecCapability[]): void;\n stop(): void;\n}\n\ndeclare var RTCRtpTransceiver: {\n prototype: RTCRtpTransceiver;\n new(): RTCRtpTransceiver;\n};\n\ninterface RTCSctpTransportEventMap {\n \"statechange\": Event;\n}\n\ninterface RTCSctpTransport {\n readonly maxChannels: number | null;\n readonly maxMessageSize: number;\n onstatechange: ((this: RTCSctpTransport, ev: Event) => any) | null;\n readonly state: RTCSctpTransportState;\n readonly transport: RTCDtlsTransport;\n addEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSctpTransport: {\n prototype: RTCSctpTransport;\n new(): RTCSctpTransport;\n};\n\ninterface RTCSessionDescription {\n readonly sdp: string;\n readonly type: RTCSdpType;\n toJSON(): any;\n}\n\ndeclare var RTCSessionDescription: {\n prototype: RTCSessionDescription;\n new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription;\n};\n\ninterface RTCSrtpSdesTransportEventMap {\n \"error\": Event;\n}\n\ninterface RTCSrtpSdesTransport extends EventTarget {\n onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null;\n readonly transport: RTCIceTransport;\n addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSrtpSdesTransport: {\n prototype: RTCSrtpSdesTransport;\n new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport;\n getLocalParameters(): RTCSrtpSdesParameters[];\n};\n\ninterface RTCSsrcConflictEvent extends Event {\n readonly ssrc: number;\n}\n\ndeclare var RTCSsrcConflictEvent: {\n prototype: RTCSsrcConflictEvent;\n new(): RTCSsrcConflictEvent;\n};\n\ninterface RTCStatsEvent extends Event {\n readonly report: RTCStatsReport;\n}\n\ndeclare var RTCStatsEvent: {\n prototype: RTCStatsEvent;\n new(type: string, eventInitDict: RTCStatsEventInit): RTCStatsEvent;\n};\n\ninterface RTCStatsProvider extends EventTarget {\n getStats(): Promise;\n msGetStats(): Promise;\n}\n\ndeclare var RTCStatsProvider: {\n prototype: RTCStatsProvider;\n new(): RTCStatsProvider;\n};\n\ninterface RTCStatsReport {\n forEach(callbackfn: (value: any, key: string, parent: RTCStatsReport) => void, thisArg?: any): void;\n}\n\ndeclare var RTCStatsReport: {\n prototype: RTCStatsReport;\n new(): RTCStatsReport;\n};\n\ninterface RTCTrackEvent extends Event {\n readonly receiver: RTCRtpReceiver;\n readonly streams: ReadonlyArray;\n readonly track: MediaStreamTrack;\n readonly transceiver: RTCRtpTransceiver;\n}\n\ndeclare var RTCTrackEvent: {\n prototype: RTCTrackEvent;\n new(type: string, eventInitDict: RTCTrackEventInit): RTCTrackEvent;\n};\n\ninterface RadioNodeList extends NodeList {\n value: string;\n}\n\ndeclare var RadioNodeList: {\n prototype: RadioNodeList;\n new(): RadioNodeList;\n};\n\ninterface RandomSource {\n getRandomValues(array: T): T;\n}\n\ndeclare var RandomSource: {\n prototype: RandomSource;\n new(): RandomSource;\n};\n\ninterface Range {\n readonly collapsed: boolean;\n readonly commonAncestorContainer: Node;\n readonly endContainer: Node;\n readonly endOffset: number;\n readonly startContainer: Node;\n readonly startOffset: number;\n cloneContents(): DocumentFragment;\n cloneRange(): Range;\n collapse(toStart?: boolean): void;\n compareBoundaryPoints(how: number, sourceRange: Range): number;\n createContextualFragment(fragment: string): DocumentFragment;\n deleteContents(): void;\n detach(): void;\n expand(Unit: ExpandGranularity): boolean;\n extractContents(): DocumentFragment;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n insertNode(node: Node): void;\n isPointInRange(node: Node, offset: number): boolean;\n selectNode(node: Node): void;\n selectNodeContents(node: Node): void;\n setEnd(node: Node, offset: number): void;\n setEndAfter(node: Node): void;\n setEndBefore(node: Node): void;\n setStart(node: Node, offset: number): void;\n setStartAfter(node: Node): void;\n setStartBefore(node: Node): void;\n surroundContents(newParent: Node): void;\n toString(): string;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n}\n\ndeclare var Range: {\n prototype: Range;\n new(): Range;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n};\n\ninterface ReadableStream {\n readonly locked: boolean;\n cancel(): Promise;\n getReader(): ReadableStreamReader;\n}\n\ndeclare var ReadableStream: {\n prototype: ReadableStream;\n new(): ReadableStream;\n};\n\ninterface ReadableStreamReader {\n cancel(): Promise;\n read(): Promise;\n releaseLock(): void;\n}\n\ndeclare var ReadableStreamReader: {\n prototype: ReadableStreamReader;\n new(): ReadableStreamReader;\n};\n\ninterface Request extends Body {\n /**\n * Returns the cache mode associated with request, which is a string indicating\n * how the the request will interact with the browser's cache when fetching.\n */\n readonly cache: RequestCache;\n /**\n * Returns the credentials mode associated with request, which is a string\n * indicating whether credentials will be sent with the request always, never, or only when sent to a\n * same-origin URL.\n */\n readonly credentials: RequestCredentials;\n /**\n * Returns the kind of resource requested by request, e.g., \"document\" or\n * \"script\".\n */\n readonly destination: RequestDestination;\n /**\n * Returns a Headers object consisting of the headers associated with request.\n * Note that headers added in the network layer by the user agent will not be accounted for in this\n * object, e.g., the \"Host\" header.\n */\n readonly headers: Headers;\n /**\n * Returns request's subresource integrity metadata, which is a cryptographic hash of\n * the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]\n */\n readonly integrity: string;\n /**\n * Returns a boolean indicating whether or not request is for a history\n * navigation (a.k.a. back-foward navigation).\n */\n readonly isHistoryNavigation: boolean;\n /**\n * Returns a boolean indicating whether or not request is for a reload navigation.\n */\n readonly isReloadNavigation: boolean;\n /**\n * Returns a boolean indicating whether or not request can outlive the global in which\n * it was created.\n */\n readonly keepalive: boolean;\n /**\n * Returns request's HTTP method, which is \"GET\" by default.\n */\n readonly method: string;\n /**\n * Returns the mode associated with request, which is a string indicating\n * whether the request will use CORS, or will be restricted to same-origin URLs.\n */\n readonly mode: RequestMode;\n /**\n * Returns the redirect mode associated with request, which is a string\n * indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.\n */\n readonly redirect: RequestRedirect;\n /**\n * Returns the referrer of request. Its value can be a same-origin URL if\n * explicitly set in init, the empty string to indicate no referrer, and\n * \"about:client\" when defaulting to the global's default. This is used during\n * fetching to determine the value of the `Referer` header of the request being made.\n */\n readonly referrer: string;\n /**\n * Returns the referrer policy associated with request. This is used during\n * fetching to compute the value of the request's referrer.\n */\n readonly referrerPolicy: ReferrerPolicy;\n /**\n * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort\n * event handler.\n */\n readonly signal: AbortSignal;\n /**\n * Returns the URL of request as a string.\n */\n readonly url: string;\n clone(): Request;\n}\n\ndeclare var Request: {\n prototype: Request;\n new(input: RequestInfo, init?: RequestInit): Request;\n};\n\ninterface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly trailer: Promise;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\ndeclare var Response: {\n prototype: Response;\n new(body?: BodyInit | null, init?: ResponseInit): Response;\n error(): Response;\n redirect(url: string, status?: number): Response;\n};\n\ninterface SVGAElement extends SVGGraphicsElement, SVGURIReference {\n readonly target: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGAElement: {\n prototype: SVGAElement;\n new(): SVGAElement;\n};\n\ninterface SVGAngle {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n}\n\ndeclare var SVGAngle: {\n prototype: SVGAngle;\n new(): SVGAngle;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n};\n\ninterface SVGAnimatedAngle {\n readonly animVal: SVGAngle;\n readonly baseVal: SVGAngle;\n}\n\ndeclare var SVGAnimatedAngle: {\n prototype: SVGAnimatedAngle;\n new(): SVGAnimatedAngle;\n};\n\ninterface SVGAnimatedBoolean {\n readonly animVal: boolean;\n baseVal: boolean;\n}\n\ndeclare var SVGAnimatedBoolean: {\n prototype: SVGAnimatedBoolean;\n new(): SVGAnimatedBoolean;\n};\n\ninterface SVGAnimatedEnumeration {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedEnumeration: {\n prototype: SVGAnimatedEnumeration;\n new(): SVGAnimatedEnumeration;\n};\n\ninterface SVGAnimatedInteger {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedInteger: {\n prototype: SVGAnimatedInteger;\n new(): SVGAnimatedInteger;\n};\n\ninterface SVGAnimatedLength {\n readonly animVal: SVGLength;\n readonly baseVal: SVGLength;\n}\n\ndeclare var SVGAnimatedLength: {\n prototype: SVGAnimatedLength;\n new(): SVGAnimatedLength;\n};\n\ninterface SVGAnimatedLengthList {\n readonly animVal: SVGLengthList;\n readonly baseVal: SVGLengthList;\n}\n\ndeclare var SVGAnimatedLengthList: {\n prototype: SVGAnimatedLengthList;\n new(): SVGAnimatedLengthList;\n};\n\ninterface SVGAnimatedNumber {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedNumber: {\n prototype: SVGAnimatedNumber;\n new(): SVGAnimatedNumber;\n};\n\ninterface SVGAnimatedNumberList {\n readonly animVal: SVGNumberList;\n readonly baseVal: SVGNumberList;\n}\n\ndeclare var SVGAnimatedNumberList: {\n prototype: SVGAnimatedNumberList;\n new(): SVGAnimatedNumberList;\n};\n\ninterface SVGAnimatedPoints {\n readonly animatedPoints: SVGPointList;\n readonly points: SVGPointList;\n}\n\ninterface SVGAnimatedPreserveAspectRatio {\n readonly animVal: SVGPreserveAspectRatio;\n readonly baseVal: SVGPreserveAspectRatio;\n}\n\ndeclare var SVGAnimatedPreserveAspectRatio: {\n prototype: SVGAnimatedPreserveAspectRatio;\n new(): SVGAnimatedPreserveAspectRatio;\n};\n\ninterface SVGAnimatedRect {\n readonly animVal: SVGRect;\n readonly baseVal: SVGRect;\n}\n\ndeclare var SVGAnimatedRect: {\n prototype: SVGAnimatedRect;\n new(): SVGAnimatedRect;\n};\n\ninterface SVGAnimatedString {\n readonly animVal: string;\n baseVal: string;\n}\n\ndeclare var SVGAnimatedString: {\n prototype: SVGAnimatedString;\n new(): SVGAnimatedString;\n};\n\ninterface SVGAnimatedTransformList {\n readonly animVal: SVGTransformList;\n readonly baseVal: SVGTransformList;\n}\n\ndeclare var SVGAnimatedTransformList: {\n prototype: SVGAnimatedTransformList;\n new(): SVGAnimatedTransformList;\n};\n\ninterface SVGCircleElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGCircleElement: {\n prototype: SVGCircleElement;\n new(): SVGCircleElement;\n};\n\ninterface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes {\n readonly clipPathUnits: SVGAnimatedEnumeration;\n addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGClipPathElement: {\n prototype: SVGClipPathElement;\n new(): SVGClipPathElement;\n};\n\ninterface SVGComponentTransferFunctionElement extends SVGElement {\n readonly amplitude: SVGAnimatedNumber;\n readonly exponent: SVGAnimatedNumber;\n readonly intercept: SVGAnimatedNumber;\n readonly offset: SVGAnimatedNumber;\n readonly slope: SVGAnimatedNumber;\n readonly tableValues: SVGAnimatedNumberList;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGComponentTransferFunctionElement: {\n prototype: SVGComponentTransferFunctionElement;\n new(): SVGComponentTransferFunctionElement;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n};\n\ninterface SVGDefsElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDefsElement: {\n prototype: SVGDefsElement;\n new(): SVGDefsElement;\n};\n\ninterface SVGDescElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDescElement: {\n prototype: SVGDescElement;\n new(): SVGDescElement;\n};\n\ninterface SVGElementEventMap extends ElementEventMap {\n \"click\": MouseEvent;\n \"dblclick\": MouseEvent;\n \"focusin\": FocusEvent;\n \"focusout\": FocusEvent;\n \"load\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n}\n\ninterface SVGElement extends Element, ElementCSSInlineStyle {\n readonly className: any;\n onclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onload: ((this: SVGElement, ev: Event) => any) | null;\n onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null;\n readonly ownerSVGElement: SVGSVGElement | null;\n readonly viewportElement: SVGElement | null;\n /** @deprecated */\n xmlbase: string;\n addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGElement: {\n prototype: SVGElement;\n new(): SVGElement;\n};\n\ninterface SVGElementInstance extends EventTarget {\n readonly childNodes: SVGElementInstanceList;\n readonly correspondingElement: SVGElement;\n readonly correspondingUseElement: SVGUseElement;\n readonly firstChild: SVGElementInstance;\n readonly lastChild: SVGElementInstance;\n readonly nextSibling: SVGElementInstance;\n readonly parentNode: SVGElementInstance;\n readonly previousSibling: SVGElementInstance;\n}\n\ndeclare var SVGElementInstance: {\n prototype: SVGElementInstance;\n new(): SVGElementInstance;\n};\n\ninterface SVGElementInstanceList {\n /** @deprecated */\n readonly length: number;\n /** @deprecated */\n item(index: number): SVGElementInstance;\n}\n\ndeclare var SVGElementInstanceList: {\n prototype: SVGElementInstanceList;\n new(): SVGElementInstanceList;\n};\n\ninterface SVGEllipseElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGEllipseElement: {\n prototype: SVGEllipseElement;\n new(): SVGEllipseElement;\n};\n\ninterface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly mode: SVGAnimatedEnumeration;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEBlendElement: {\n prototype: SVGFEBlendElement;\n new(): SVGFEBlendElement;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n};\n\ninterface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly type: SVGAnimatedEnumeration;\n readonly values: SVGAnimatedNumberList;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEColorMatrixElement: {\n prototype: SVGFEColorMatrixElement;\n new(): SVGFEColorMatrixElement;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEComponentTransferElement: {\n prototype: SVGFEComponentTransferElement;\n new(): SVGFEComponentTransferElement;\n};\n\ninterface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly k1: SVGAnimatedNumber;\n readonly k2: SVGAnimatedNumber;\n readonly k3: SVGAnimatedNumber;\n readonly k4: SVGAnimatedNumber;\n readonly operator: SVGAnimatedEnumeration;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFECompositeElement: {\n prototype: SVGFECompositeElement;\n new(): SVGFECompositeElement;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n};\n\ninterface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly bias: SVGAnimatedNumber;\n readonly divisor: SVGAnimatedNumber;\n readonly edgeMode: SVGAnimatedEnumeration;\n readonly in1: SVGAnimatedString;\n readonly kernelMatrix: SVGAnimatedNumberList;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly orderX: SVGAnimatedInteger;\n readonly orderY: SVGAnimatedInteger;\n readonly preserveAlpha: SVGAnimatedBoolean;\n readonly targetX: SVGAnimatedInteger;\n readonly targetY: SVGAnimatedInteger;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEConvolveMatrixElement: {\n prototype: SVGFEConvolveMatrixElement;\n new(): SVGFEConvolveMatrixElement;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n};\n\ninterface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly diffuseConstant: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDiffuseLightingElement: {\n prototype: SVGFEDiffuseLightingElement;\n new(): SVGFEDiffuseLightingElement;\n};\n\ninterface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly scale: SVGAnimatedNumber;\n readonly xChannelSelector: SVGAnimatedEnumeration;\n readonly yChannelSelector: SVGAnimatedEnumeration;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDisplacementMapElement: {\n prototype: SVGFEDisplacementMapElement;\n new(): SVGFEDisplacementMapElement;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n};\n\ninterface SVGFEDistantLightElement extends SVGElement {\n readonly azimuth: SVGAnimatedNumber;\n readonly elevation: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDistantLightElement: {\n prototype: SVGFEDistantLightElement;\n new(): SVGFEDistantLightElement;\n};\n\ninterface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFloodElement: {\n prototype: SVGFEFloodElement;\n new(): SVGFEFloodElement;\n};\n\ninterface SVGFEFuncAElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncAElement: {\n prototype: SVGFEFuncAElement;\n new(): SVGFEFuncAElement;\n};\n\ninterface SVGFEFuncBElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncBElement: {\n prototype: SVGFEFuncBElement;\n new(): SVGFEFuncBElement;\n};\n\ninterface SVGFEFuncGElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncGElement: {\n prototype: SVGFEFuncGElement;\n new(): SVGFEFuncGElement;\n};\n\ninterface SVGFEFuncRElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncRElement: {\n prototype: SVGFEFuncRElement;\n new(): SVGFEFuncRElement;\n};\n\ninterface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly stdDeviationX: SVGAnimatedNumber;\n readonly stdDeviationY: SVGAnimatedNumber;\n setStdDeviation(stdDeviationX: number, stdDeviationY: number): void;\n addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEGaussianBlurElement: {\n prototype: SVGFEGaussianBlurElement;\n new(): SVGFEGaussianBlurElement;\n};\n\ninterface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEImageElement: {\n prototype: SVGFEImageElement;\n new(): SVGFEImageElement;\n};\n\ninterface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeElement: {\n prototype: SVGFEMergeElement;\n new(): SVGFEMergeElement;\n};\n\ninterface SVGFEMergeNodeElement extends SVGElement {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeNodeElement: {\n prototype: SVGFEMergeNodeElement;\n new(): SVGFEMergeNodeElement;\n};\n\ninterface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly operator: SVGAnimatedEnumeration;\n readonly radiusX: SVGAnimatedNumber;\n readonly radiusY: SVGAnimatedNumber;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMorphologyElement: {\n prototype: SVGFEMorphologyElement;\n new(): SVGFEMorphologyElement;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n};\n\ninterface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly dx: SVGAnimatedNumber;\n readonly dy: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEOffsetElement: {\n prototype: SVGFEOffsetElement;\n new(): SVGFEOffsetElement;\n};\n\ninterface SVGFEPointLightElement extends SVGElement {\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEPointLightElement: {\n prototype: SVGFEPointLightElement;\n new(): SVGFEPointLightElement;\n};\n\ninterface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly specularConstant: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpecularLightingElement: {\n prototype: SVGFESpecularLightingElement;\n new(): SVGFESpecularLightingElement;\n};\n\ninterface SVGFESpotLightElement extends SVGElement {\n readonly limitingConeAngle: SVGAnimatedNumber;\n readonly pointsAtX: SVGAnimatedNumber;\n readonly pointsAtY: SVGAnimatedNumber;\n readonly pointsAtZ: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpotLightElement: {\n prototype: SVGFESpotLightElement;\n new(): SVGFESpotLightElement;\n};\n\ninterface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETileElement: {\n prototype: SVGFETileElement;\n new(): SVGFETileElement;\n};\n\ninterface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly baseFrequencyX: SVGAnimatedNumber;\n readonly baseFrequencyY: SVGAnimatedNumber;\n readonly numOctaves: SVGAnimatedInteger;\n readonly seed: SVGAnimatedNumber;\n readonly stitchTiles: SVGAnimatedEnumeration;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETurbulenceElement: {\n prototype: SVGFETurbulenceElement;\n new(): SVGFETurbulenceElement;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n /** @deprecated */\n readonly filterResX: SVGAnimatedInteger;\n /** @deprecated */\n readonly filterResY: SVGAnimatedInteger;\n readonly filterUnits: SVGAnimatedEnumeration;\n readonly height: SVGAnimatedLength;\n readonly primitiveUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n /** @deprecated */\n setFilterRes(filterResX: number, filterResY: number): void;\n addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFilterElement: {\n prototype: SVGFilterElement;\n new(): SVGFilterElement;\n};\n\ninterface SVGFilterPrimitiveStandardAttributes {\n readonly height: SVGAnimatedLength;\n readonly result: SVGAnimatedString;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n}\n\ninterface SVGFitToViewBox {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly viewBox: SVGAnimatedRect;\n}\n\ninterface SVGForeignObjectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGForeignObjectElement: {\n prototype: SVGForeignObjectElement;\n new(): SVGForeignObjectElement;\n};\n\ninterface SVGGElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGElement: {\n prototype: SVGGElement;\n new(): SVGGElement;\n};\n\ninterface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n readonly gradientTransform: SVGAnimatedTransformList;\n readonly gradientUnits: SVGAnimatedEnumeration;\n readonly spreadMethod: SVGAnimatedEnumeration;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGradientElement: {\n prototype: SVGGradientElement;\n new(): SVGGradientElement;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n};\n\ninterface SVGGraphicsElement extends SVGElement, SVGTests {\n /** @deprecated */\n readonly farthestViewportElement: SVGElement | null;\n /** @deprecated */\n readonly nearestViewportElement: SVGElement | null;\n readonly transform: SVGAnimatedTransformList;\n getBBox(): SVGRect;\n getCTM(): SVGMatrix | null;\n getScreenCTM(): SVGMatrix | null;\n /** @deprecated */\n getTransformToElement(element: SVGElement): SVGMatrix;\n addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGraphicsElement: {\n prototype: SVGGraphicsElement;\n new(): SVGGraphicsElement;\n};\n\ninterface SVGImageElement extends SVGGraphicsElement, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGImageElement: {\n prototype: SVGImageElement;\n new(): SVGImageElement;\n};\n\ninterface SVGLength {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n}\n\ndeclare var SVGLength: {\n prototype: SVGLength;\n new(): SVGLength;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n};\n\ninterface SVGLengthList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGLength): SVGLength;\n clear(): void;\n getItem(index: number): SVGLength;\n initialize(newItem: SVGLength): SVGLength;\n insertItemBefore(newItem: SVGLength, index: number): SVGLength;\n removeItem(index: number): SVGLength;\n replaceItem(newItem: SVGLength, index: number): SVGLength;\n}\n\ndeclare var SVGLengthList: {\n prototype: SVGLengthList;\n new(): SVGLengthList;\n};\n\ninterface SVGLineElement extends SVGGraphicsElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLineElement: {\n prototype: SVGLineElement;\n new(): SVGLineElement;\n};\n\ninterface SVGLinearGradientElement extends SVGGradientElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLinearGradientElement: {\n prototype: SVGLinearGradientElement;\n new(): SVGLinearGradientElement;\n};\n\ninterface SVGMarkerElement extends SVGElement, SVGFitToViewBox {\n readonly markerHeight: SVGAnimatedLength;\n readonly markerUnits: SVGAnimatedEnumeration;\n readonly markerWidth: SVGAnimatedLength;\n readonly orientAngle: SVGAnimatedAngle;\n readonly orientType: SVGAnimatedEnumeration;\n readonly refX: SVGAnimatedLength;\n readonly refY: SVGAnimatedLength;\n setOrientToAngle(angle: SVGAngle): void;\n setOrientToAuto(): void;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMarkerElement: {\n prototype: SVGMarkerElement;\n new(): SVGMarkerElement;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n};\n\ninterface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes {\n readonly height: SVGAnimatedLength;\n readonly maskContentUnits: SVGAnimatedEnumeration;\n readonly maskUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMaskElement: {\n prototype: SVGMaskElement;\n new(): SVGMaskElement;\n};\n\ninterface SVGMetadataElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMetadataElement: {\n prototype: SVGMetadataElement;\n new(): SVGMetadataElement;\n};\n\ninterface SVGNumber {\n value: number;\n}\n\ndeclare var SVGNumber: {\n prototype: SVGNumber;\n new(): SVGNumber;\n};\n\ninterface SVGNumberList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGNumber): SVGNumber;\n clear(): void;\n getItem(index: number): SVGNumber;\n initialize(newItem: SVGNumber): SVGNumber;\n insertItemBefore(newItem: SVGNumber, index: number): SVGNumber;\n removeItem(index: number): SVGNumber;\n replaceItem(newItem: SVGNumber, index: number): SVGNumber;\n}\n\ndeclare var SVGNumberList: {\n prototype: SVGNumberList;\n new(): SVGNumberList;\n};\n\ninterface SVGPathElement extends SVGGraphicsElement {\n /** @deprecated */\n readonly pathSegList: SVGPathSegList;\n /** @deprecated */\n createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs;\n /** @deprecated */\n createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel;\n /** @deprecated */\n createSVGPathSegClosePath(): SVGPathSegClosePath;\n /** @deprecated */\n createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel;\n /** @deprecated */\n createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel;\n /** @deprecated */\n createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel;\n /** @deprecated */\n createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs;\n /** @deprecated */\n createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel;\n /** @deprecated */\n createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs;\n /** @deprecated */\n createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel;\n /** @deprecated */\n getPathSegAtLength(distance: number): number;\n getPointAtLength(distance: number): SVGPoint;\n getTotalLength(): number;\n addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPathElement: {\n prototype: SVGPathElement;\n new(): SVGPathElement;\n};\n\ninterface SVGPathSeg {\n readonly pathSegType: number;\n readonly pathSegTypeAsLetter: string;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n}\n\ndeclare var SVGPathSeg: {\n prototype: SVGPathSeg;\n new(): SVGPathSeg;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n};\n\ninterface SVGPathSegArcAbs extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcAbs: {\n prototype: SVGPathSegArcAbs;\n new(): SVGPathSegArcAbs;\n};\n\ninterface SVGPathSegArcRel extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcRel: {\n prototype: SVGPathSegArcRel;\n new(): SVGPathSegArcRel;\n};\n\ninterface SVGPathSegClosePath extends SVGPathSeg {\n}\n\ndeclare var SVGPathSegClosePath: {\n prototype: SVGPathSegClosePath;\n new(): SVGPathSegClosePath;\n};\n\ninterface SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicAbs: {\n prototype: SVGPathSegCurvetoCubicAbs;\n new(): SVGPathSegCurvetoCubicAbs;\n};\n\ninterface SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicRel: {\n prototype: SVGPathSegCurvetoCubicRel;\n new(): SVGPathSegCurvetoCubicRel;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothAbs: {\n prototype: SVGPathSegCurvetoCubicSmoothAbs;\n new(): SVGPathSegCurvetoCubicSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothRel: {\n prototype: SVGPathSegCurvetoCubicSmoothRel;\n new(): SVGPathSegCurvetoCubicSmoothRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticAbs: {\n prototype: SVGPathSegCurvetoQuadraticAbs;\n new(): SVGPathSegCurvetoQuadraticAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticRel: {\n prototype: SVGPathSegCurvetoQuadraticRel;\n new(): SVGPathSegCurvetoQuadraticRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothAbs: {\n prototype: SVGPathSegCurvetoQuadraticSmoothAbs;\n new(): SVGPathSegCurvetoQuadraticSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothRel: {\n prototype: SVGPathSegCurvetoQuadraticSmoothRel;\n new(): SVGPathSegCurvetoQuadraticSmoothRel;\n};\n\ninterface SVGPathSegLinetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoAbs: {\n prototype: SVGPathSegLinetoAbs;\n new(): SVGPathSegLinetoAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalAbs: {\n prototype: SVGPathSegLinetoHorizontalAbs;\n new(): SVGPathSegLinetoHorizontalAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalRel: {\n prototype: SVGPathSegLinetoHorizontalRel;\n new(): SVGPathSegLinetoHorizontalRel;\n};\n\ninterface SVGPathSegLinetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoRel: {\n prototype: SVGPathSegLinetoRel;\n new(): SVGPathSegLinetoRel;\n};\n\ninterface SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalAbs: {\n prototype: SVGPathSegLinetoVerticalAbs;\n new(): SVGPathSegLinetoVerticalAbs;\n};\n\ninterface SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalRel: {\n prototype: SVGPathSegLinetoVerticalRel;\n new(): SVGPathSegLinetoVerticalRel;\n};\n\ninterface SVGPathSegList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPathSeg): SVGPathSeg;\n clear(): void;\n getItem(index: number): SVGPathSeg;\n initialize(newItem: SVGPathSeg): SVGPathSeg;\n insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg;\n removeItem(index: number): SVGPathSeg;\n replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg;\n}\n\ndeclare var SVGPathSegList: {\n prototype: SVGPathSegList;\n new(): SVGPathSegList;\n};\n\ninterface SVGPathSegMovetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoAbs: {\n prototype: SVGPathSegMovetoAbs;\n new(): SVGPathSegMovetoAbs;\n};\n\ninterface SVGPathSegMovetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoRel: {\n prototype: SVGPathSegMovetoRel;\n new(): SVGPathSegMovetoRel;\n};\n\ninterface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly patternContentUnits: SVGAnimatedEnumeration;\n readonly patternTransform: SVGAnimatedTransformList;\n readonly patternUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPatternElement: {\n prototype: SVGPatternElement;\n new(): SVGPatternElement;\n};\n\ninterface SVGPointList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPoint): SVGPoint;\n clear(): void;\n getItem(index: number): SVGPoint;\n initialize(newItem: SVGPoint): SVGPoint;\n insertItemBefore(newItem: SVGPoint, index: number): SVGPoint;\n removeItem(index: number): SVGPoint;\n replaceItem(newItem: SVGPoint, index: number): SVGPoint;\n}\n\ndeclare var SVGPointList: {\n prototype: SVGPointList;\n new(): SVGPointList;\n};\n\ninterface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolygonElement: {\n prototype: SVGPolygonElement;\n new(): SVGPolygonElement;\n};\n\ninterface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolylineElement: {\n prototype: SVGPolylineElement;\n new(): SVGPolylineElement;\n};\n\ninterface SVGPreserveAspectRatio {\n align: number;\n meetOrSlice: number;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n}\n\ndeclare var SVGPreserveAspectRatio: {\n prototype: SVGPreserveAspectRatio;\n new(): SVGPreserveAspectRatio;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n};\n\ninterface SVGRadialGradientElement extends SVGGradientElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly fx: SVGAnimatedLength;\n readonly fy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRadialGradientElement: {\n prototype: SVGRadialGradientElement;\n new(): SVGRadialGradientElement;\n};\n\ninterface SVGRectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRectElement: {\n prototype: SVGRectElement;\n new(): SVGRectElement;\n};\n\ninterface SVGSVGElementEventMap extends SVGElementEventMap {\n \"SVGAbort\": Event;\n \"SVGError\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"SVGUnload\": Event;\n \"SVGZoom\": SVGZoomEvent;\n}\n\ninterface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n contentScriptType: string;\n /** @deprecated */\n contentStyleType: string;\n currentScale: number;\n readonly currentTranslate: SVGPoint;\n readonly height: SVGAnimatedLength;\n onabort: ((this: SVGSVGElement, ev: Event) => any) | null;\n onerror: ((this: SVGSVGElement, ev: Event) => any) | null;\n onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onunload: ((this: SVGSVGElement, ev: Event) => any) | null;\n onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null;\n /** @deprecated */\n readonly pixelUnitToMillimeterX: number;\n /** @deprecated */\n readonly pixelUnitToMillimeterY: number;\n /** @deprecated */\n readonly screenPixelToMillimeterX: number;\n /** @deprecated */\n readonly screenPixelToMillimeterY: number;\n /** @deprecated */\n readonly viewport: SVGRect;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n checkEnclosure(element: SVGElement, rect: SVGRect): boolean;\n checkIntersection(element: SVGElement, rect: SVGRect): boolean;\n createSVGAngle(): SVGAngle;\n createSVGLength(): SVGLength;\n createSVGMatrix(): SVGMatrix;\n createSVGNumber(): SVGNumber;\n createSVGPoint(): SVGPoint;\n createSVGRect(): SVGRect;\n createSVGTransform(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n deselectAll(): void;\n /** @deprecated */\n forceRedraw(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n /** @deprecated */\n getCurrentTime(): number;\n getElementById(elementId: string): Element;\n getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n /** @deprecated */\n pauseAnimations(): void;\n /** @deprecated */\n setCurrentTime(seconds: number): void;\n /** @deprecated */\n suspendRedraw(maxWaitMilliseconds: number): number;\n /** @deprecated */\n unpauseAnimations(): void;\n /** @deprecated */\n unsuspendRedraw(suspendHandleID: number): void;\n /** @deprecated */\n unsuspendRedrawAll(): void;\n addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSVGElement: {\n prototype: SVGSVGElement;\n new(): SVGSVGElement;\n};\n\ninterface SVGScriptElement extends SVGElement, SVGURIReference {\n type: string;\n addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGScriptElement: {\n prototype: SVGScriptElement;\n new(): SVGScriptElement;\n};\n\ninterface SVGStopElement extends SVGElement {\n readonly offset: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStopElement: {\n prototype: SVGStopElement;\n new(): SVGStopElement;\n};\n\ninterface SVGStringList {\n readonly numberOfItems: number;\n appendItem(newItem: string): string;\n clear(): void;\n getItem(index: number): string;\n initialize(newItem: string): string;\n insertItemBefore(newItem: string, index: number): string;\n removeItem(index: number): string;\n replaceItem(newItem: string, index: number): string;\n}\n\ndeclare var SVGStringList: {\n prototype: SVGStringList;\n new(): SVGStringList;\n};\n\ninterface SVGStyleElement extends SVGElement {\n disabled: boolean;\n media: string;\n title: string;\n type: string;\n addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStyleElement: {\n prototype: SVGStyleElement;\n new(): SVGStyleElement;\n};\n\ninterface SVGSwitchElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSwitchElement: {\n prototype: SVGSwitchElement;\n new(): SVGSwitchElement;\n};\n\ninterface SVGSymbolElement extends SVGElement, SVGFitToViewBox {\n addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSymbolElement: {\n prototype: SVGSymbolElement;\n new(): SVGSymbolElement;\n};\n\ninterface SVGTSpanElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTSpanElement: {\n prototype: SVGTSpanElement;\n new(): SVGTSpanElement;\n};\n\ninterface SVGTests {\n readonly requiredExtensions: SVGStringList;\n /** @deprecated */\n readonly requiredFeatures: SVGStringList;\n readonly systemLanguage: SVGStringList;\n /** @deprecated */\n hasExtension(extension: string): boolean;\n}\n\ninterface SVGTextContentElement extends SVGGraphicsElement {\n readonly lengthAdjust: SVGAnimatedEnumeration;\n readonly textLength: SVGAnimatedLength;\n getCharNumAtPosition(point: SVGPoint): number;\n getComputedTextLength(): number;\n getEndPositionOfChar(charnum: number): SVGPoint;\n getExtentOfChar(charnum: number): SVGRect;\n getNumberOfChars(): number;\n getRotationOfChar(charnum: number): number;\n getStartPositionOfChar(charnum: number): SVGPoint;\n getSubStringLength(charnum: number, nchars: number): number;\n selectSubString(charnum: number, nchars: number): void;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextContentElement: {\n prototype: SVGTextContentElement;\n new(): SVGTextContentElement;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n};\n\ninterface SVGTextElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextElement: {\n prototype: SVGTextElement;\n new(): SVGTextElement;\n};\n\ninterface SVGTextPathElement extends SVGTextContentElement, SVGURIReference {\n readonly method: SVGAnimatedEnumeration;\n readonly spacing: SVGAnimatedEnumeration;\n readonly startOffset: SVGAnimatedLength;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPathElement: {\n prototype: SVGTextPathElement;\n new(): SVGTextPathElement;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n};\n\ninterface SVGTextPositioningElement extends SVGTextContentElement {\n readonly dx: SVGAnimatedLengthList;\n readonly dy: SVGAnimatedLengthList;\n readonly rotate: SVGAnimatedNumberList;\n readonly x: SVGAnimatedLengthList;\n readonly y: SVGAnimatedLengthList;\n addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPositioningElement: {\n prototype: SVGTextPositioningElement;\n new(): SVGTextPositioningElement;\n};\n\ninterface SVGTitleElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTitleElement: {\n prototype: SVGTitleElement;\n new(): SVGTitleElement;\n};\n\ninterface SVGTransform {\n readonly angle: number;\n readonly matrix: SVGMatrix;\n readonly type: number;\n setMatrix(matrix: SVGMatrix): void;\n setRotate(angle: number, cx: number, cy: number): void;\n setScale(sx: number, sy: number): void;\n setSkewX(angle: number): void;\n setSkewY(angle: number): void;\n setTranslate(tx: number, ty: number): void;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n}\n\ndeclare var SVGTransform: {\n prototype: SVGTransform;\n new(): SVGTransform;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n};\n\ninterface SVGTransformList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGTransform): SVGTransform;\n clear(): void;\n consolidate(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n getItem(index: number): SVGTransform;\n initialize(newItem: SVGTransform): SVGTransform;\n insertItemBefore(newItem: SVGTransform, index: number): SVGTransform;\n removeItem(index: number): SVGTransform;\n replaceItem(newItem: SVGTransform, index: number): SVGTransform;\n}\n\ndeclare var SVGTransformList: {\n prototype: SVGTransformList;\n new(): SVGTransformList;\n};\n\ninterface SVGURIReference {\n readonly href: SVGAnimatedString;\n}\n\ninterface SVGUnitTypes {\n readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number;\n readonly SVG_UNIT_TYPE_UNKNOWN: number;\n readonly SVG_UNIT_TYPE_USERSPACEONUSE: number;\n}\ndeclare var SVGUnitTypes: SVGUnitTypes;\n\ninterface SVGUseElement extends SVGGraphicsElement, SVGURIReference {\n readonly animatedInstanceRoot: SVGElementInstance | null;\n readonly height: SVGAnimatedLength;\n readonly instanceRoot: SVGElementInstance | null;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGUseElement: {\n prototype: SVGUseElement;\n new(): SVGUseElement;\n};\n\ninterface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n readonly viewTarget: SVGStringList;\n addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGViewElement: {\n prototype: SVGViewElement;\n new(): SVGViewElement;\n};\n\ninterface SVGZoomAndPan {\n readonly zoomAndPan: number;\n}\n\ndeclare var SVGZoomAndPan: {\n readonly SVG_ZOOMANDPAN_DISABLE: number;\n readonly SVG_ZOOMANDPAN_MAGNIFY: number;\n readonly SVG_ZOOMANDPAN_UNKNOWN: number;\n};\n\ninterface SVGZoomEvent extends UIEvent {\n readonly newScale: number;\n readonly newTranslate: SVGPoint;\n readonly previousScale: number;\n readonly previousTranslate: SVGPoint;\n readonly zoomRectScreen: SVGRect;\n}\n\ndeclare var SVGZoomEvent: {\n prototype: SVGZoomEvent;\n new(): SVGZoomEvent;\n};\n\ninterface ScopedCredential {\n readonly id: ArrayBuffer;\n readonly type: ScopedCredentialType;\n}\n\ndeclare var ScopedCredential: {\n prototype: ScopedCredential;\n new(): ScopedCredential;\n};\n\ninterface ScopedCredentialInfo {\n readonly credential: ScopedCredential;\n readonly publicKey: CryptoKey;\n}\n\ndeclare var ScopedCredentialInfo: {\n prototype: ScopedCredentialInfo;\n new(): ScopedCredentialInfo;\n};\n\ninterface ScreenEventMap {\n \"MSOrientationChange\": Event;\n}\n\ninterface Screen extends EventTarget {\n readonly availHeight: number;\n readonly availWidth: number;\n /** @deprecated */\n bufferDepth: number;\n readonly colorDepth: number;\n readonly deviceXDPI: number;\n readonly deviceYDPI: number;\n readonly fontSmoothingEnabled: boolean;\n readonly height: number;\n readonly logicalXDPI: number;\n readonly logicalYDPI: number;\n readonly msOrientation: string;\n onmsorientationchange: ((this: Screen, ev: Event) => any) | null;\n readonly pixelDepth: number;\n readonly systemXDPI: number;\n readonly systemYDPI: number;\n readonly width: number;\n lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean;\n msLockOrientation(orientations: string | string[]): boolean;\n msUnlockOrientation(): void;\n unlockOrientation(): void;\n addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Screen: {\n prototype: Screen;\n new(): Screen;\n};\n\ninterface ScriptProcessorNodeEventMap {\n \"audioprocess\": AudioProcessingEvent;\n}\n\ninterface ScriptProcessorNode extends AudioNode {\n /** @deprecated */\n readonly bufferSize: number;\n /** @deprecated */\n onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null;\n addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ScriptProcessorNode: {\n prototype: ScriptProcessorNode;\n new(): ScriptProcessorNode;\n};\n\ninterface SecurityPolicyViolationEvent extends Event {\n readonly blockedURI: string;\n readonly columnNumber: number;\n readonly documentURI: string;\n readonly effectiveDirective: string;\n readonly lineNumber: number;\n readonly originalPolicy: string;\n readonly referrer: string;\n readonly sourceFile: string;\n readonly statusCode: number;\n readonly violatedDirective: string;\n}\n\ndeclare var SecurityPolicyViolationEvent: {\n prototype: SecurityPolicyViolationEvent;\n new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent;\n};\n\ninterface Selection {\n readonly anchorNode: Node;\n readonly anchorOffset: number;\n readonly baseNode: Node;\n readonly baseOffset: number;\n readonly extentNode: Node;\n readonly extentOffset: number;\n readonly focusNode: Node;\n readonly focusOffset: number;\n readonly isCollapsed: boolean;\n readonly rangeCount: number;\n readonly type: string;\n addRange(range: Range): void;\n collapse(parentNode: Node, offset: number): void;\n collapseToEnd(): void;\n collapseToStart(): void;\n containsNode(node: Node, partlyContained: boolean): boolean;\n deleteFromDocument(): void;\n empty(): void;\n extend(newNode: Node, offset: number): void;\n getRangeAt(index: number): Range;\n removeAllRanges(): void;\n removeRange(range: Range): void;\n selectAllChildren(parentNode: Node): void;\n setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void;\n setPosition(parentNode: Node, offset: number): void;\n toString(): string;\n}\n\ndeclare var Selection: {\n prototype: Selection;\n new(): Selection;\n};\n\ninterface ServiceUIFrameContext {\n getCachedFrameMessage(key: string): string;\n postFrameMessage(key: string, data: string): void;\n}\ndeclare var ServiceUIFrameContext: ServiceUIFrameContext;\n\ninterface ServiceWorkerEventMap extends AbstractWorkerEventMap {\n \"statechange\": Event;\n}\n\ninterface ServiceWorker extends EventTarget, AbstractWorker {\n onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;\n readonly scriptURL: string;\n readonly state: ServiceWorkerState;\n postMessage(message: any, transfer?: any[]): void;\n addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorker: {\n prototype: ServiceWorker;\n new(): ServiceWorker;\n};\n\ninterface ServiceWorkerContainerEventMap {\n \"controllerchange\": Event;\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface ServiceWorkerContainer extends EventTarget {\n readonly controller: ServiceWorker | null;\n oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;\n onmessage: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n readonly ready: Promise;\n getRegistration(clientURL?: string): Promise;\n getRegistrations(): Promise>;\n register(scriptURL: string, options?: RegistrationOptions): Promise;\n startMessages(): void;\n addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerContainer: {\n prototype: ServiceWorkerContainer;\n new(): ServiceWorkerContainer;\n};\n\ninterface ServiceWorkerMessageEvent extends Event {\n readonly data: any;\n readonly lastEventId: string;\n readonly origin: string;\n readonly ports: ReadonlyArray | null;\n readonly source: ServiceWorker | MessagePort | null;\n}\n\ndeclare var ServiceWorkerMessageEvent: {\n prototype: ServiceWorkerMessageEvent;\n new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent;\n};\n\ninterface ServiceWorkerRegistrationEventMap {\n \"updatefound\": Event;\n}\n\ninterface ServiceWorkerRegistration extends EventTarget {\n readonly active: ServiceWorker | null;\n readonly installing: ServiceWorker | null;\n readonly navigationPreload: NavigationPreloadManager;\n onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null;\n readonly pushManager: PushManager;\n readonly scope: string;\n readonly sync: SyncManager;\n readonly updateViaCache: ServiceWorkerUpdateViaCache;\n readonly waiting: ServiceWorker | null;\n getNotifications(filter?: GetNotificationOptions): Promise;\n showNotification(title: string, options?: NotificationOptions): Promise;\n unregister(): Promise;\n update(): Promise;\n addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerRegistration: {\n prototype: ServiceWorkerRegistration;\n new(): ServiceWorkerRegistration;\n};\n\ninterface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment {\n readonly host: Element;\n innerHTML: string;\n}\n\ninterface ShadowRootInit {\n delegatesFocus?: boolean;\n mode: \"open\" | \"closed\";\n}\n\ninterface SourceBuffer extends EventTarget {\n appendWindowEnd: number;\n appendWindowStart: number;\n readonly audioTracks: AudioTrackList;\n readonly buffered: TimeRanges;\n mode: AppendMode;\n readonly textTracks: TextTrackList;\n timestampOffset: number;\n readonly updating: boolean;\n readonly videoTracks: VideoTrackList;\n abort(): void;\n appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n appendStream(stream: MSStream, maxSize?: number): void;\n remove(start: number, end: number): void;\n}\n\ndeclare var SourceBuffer: {\n prototype: SourceBuffer;\n new(): SourceBuffer;\n};\n\ninterface SourceBufferList extends EventTarget {\n readonly length: number;\n item(index: number): SourceBuffer;\n [index: number]: SourceBuffer;\n}\n\ndeclare var SourceBufferList: {\n prototype: SourceBufferList;\n new(): SourceBufferList;\n};\n\ninterface SpeechSynthesisEventMap {\n \"voiceschanged\": Event;\n}\n\ninterface SpeechSynthesis extends EventTarget {\n onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null;\n readonly paused: boolean;\n readonly pending: boolean;\n readonly speaking: boolean;\n cancel(): void;\n getVoices(): SpeechSynthesisVoice[];\n pause(): void;\n resume(): void;\n speak(utterance: SpeechSynthesisUtterance): void;\n addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesis: {\n prototype: SpeechSynthesis;\n new(): SpeechSynthesis;\n};\n\ninterface SpeechSynthesisEvent extends Event {\n readonly charIndex: number;\n readonly charLength: number;\n readonly elapsedTime: number;\n readonly name: string;\n readonly utterance: SpeechSynthesisUtterance;\n}\n\ndeclare var SpeechSynthesisEvent: {\n prototype: SpeechSynthesisEvent;\n new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent;\n};\n\ninterface SpeechSynthesisUtteranceEventMap {\n \"boundary\": Event;\n \"end\": Event;\n \"error\": Event;\n \"mark\": Event;\n \"pause\": Event;\n \"resume\": Event;\n \"start\": Event;\n}\n\ninterface SpeechSynthesisUtterance extends EventTarget {\n lang: string;\n onboundary: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n pitch: number;\n rate: number;\n text: string;\n voice: SpeechSynthesisVoice;\n volume: number;\n addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesisUtterance: {\n prototype: SpeechSynthesisUtterance;\n new(): SpeechSynthesisUtterance;\n new(text: string): SpeechSynthesisUtterance;\n};\n\ninterface SpeechSynthesisVoice {\n readonly default: boolean;\n readonly lang: string;\n readonly localService: boolean;\n readonly name: string;\n readonly voiceURI: string;\n}\n\ndeclare var SpeechSynthesisVoice: {\n prototype: SpeechSynthesisVoice;\n new(): SpeechSynthesisVoice;\n};\n\ninterface StereoPannerNode extends AudioNode {\n readonly pan: AudioParam;\n}\n\ndeclare var StereoPannerNode: {\n prototype: StereoPannerNode;\n new(context: BaseAudioContext, options?: StereoPannerOptions): StereoPannerNode;\n};\n\ninterface Storage {\n /**\n * Returns the number of key/value pairs currently present in the list associated with the\n * object.\n */\n readonly length: number;\n /**\n * Empties the list associated with the object of all key/value pairs, if there are any.\n */\n clear(): void;\n /**\n * value = storage[key]\n */\n getItem(key: string): string | null;\n /**\n * Returns the name of the nth key in the list, or null if n is greater\n * than or equal to the number of key/value pairs in the object.\n */\n key(index: number): string | null;\n /**\n * delete storage[key]\n */\n removeItem(key: string): void;\n /**\n * storage[key] = value\n */\n setItem(key: string, value: string): void;\n}\n\ndeclare var Storage: {\n prototype: Storage;\n new(): Storage;\n};\n\ninterface StorageEvent extends Event {\n /**\n * Returns the key of the storage item being changed.\n */\n readonly key: string | null;\n /**\n * Returns the new value of the key of the storage item whose value is being changed.\n */\n readonly newValue: string | null;\n /**\n * Returns the old value of the key of the storage item whose value is being changed.\n */\n readonly oldValue: string | null;\n /**\n * Returns the Storage object that was affected.\n */\n readonly storageArea: Storage | null;\n /**\n * Returns the URL of the document whose storage item changed.\n */\n readonly url: string;\n}\n\ndeclare var StorageEvent: {\n prototype: StorageEvent;\n new(type: string, eventInitDict?: StorageEventInit): StorageEvent;\n};\n\ninterface StorageManager {\n estimate(): Promise;\n persist(): Promise;\n persisted(): Promise;\n}\n\ndeclare var StorageManager: {\n prototype: StorageManager;\n new(): StorageManager;\n};\n\ninterface StyleMedia {\n readonly type: string;\n matchMedium(mediaquery: string): boolean;\n}\n\ndeclare var StyleMedia: {\n prototype: StyleMedia;\n new(): StyleMedia;\n};\n\ninterface StyleSheet {\n disabled: boolean;\n readonly href: string | null;\n readonly media: MediaList;\n readonly ownerNode: Node;\n readonly parentStyleSheet: StyleSheet | null;\n readonly title: string | null;\n readonly type: string;\n}\n\ndeclare var StyleSheet: {\n prototype: StyleSheet;\n new(): StyleSheet;\n};\n\ninterface StyleSheetList {\n readonly length: number;\n item(index: number): StyleSheet | null;\n [index: number]: StyleSheet;\n}\n\ndeclare var StyleSheetList: {\n prototype: StyleSheetList;\n new(): StyleSheetList;\n};\n\ninterface SubtleCrypto {\n decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike;\n deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n exportKey(format: \"jwk\", key: CryptoKey): PromiseLike;\n exportKey(format: \"raw\" | \"pkcs8\" | \"spki\", key: CryptoKey): PromiseLike;\n exportKey(format: string, key: CryptoKey): PromiseLike;\n generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"jwk\", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"raw\" | \"pkcs8\" | \"spki\", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike;\n}\n\ndeclare var SubtleCrypto: {\n prototype: SubtleCrypto;\n new(): SubtleCrypto;\n};\n\ninterface SyncManager {\n getTags(): Promise;\n register(tag: string): Promise;\n}\n\ndeclare var SyncManager: {\n prototype: SyncManager;\n new(): SyncManager;\n};\n\ninterface Text extends CharacterData {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly wholeText: string;\n splitText(offset: number): Text;\n}\n\ndeclare var Text: {\n prototype: Text;\n new(data?: string): Text;\n};\n\ninterface TextDecoder {\n /**\n * Returns encoding's name, lowercased.\n */\n readonly encoding: string;\n /**\n * Returns true if error mode is \"fatal\", and false\n * otherwise.\n */\n readonly fatal: boolean;\n /**\n * Returns true if ignore BOM flag is set, and false otherwise.\n */\n readonly ignoreBOM: boolean;\n /**\n * Returns the result of running encoding's decoder. The\n * method can be invoked zero or more times with options's stream set to\n * true, and then once without options's stream (or set to false), to process\n * a fragmented stream. If the invocation without options's stream (or set to\n * false) has no input, it's clearest to omit both arguments.\n * var string = \"\", decoder = new TextDecoder(encoding), buffer;\n * while(buffer = next_chunk()) {\n * string += decoder.decode(buffer, {stream:true});\n * }\n * string += decoder.decode(); // end-of-stream\n * If the error mode is \"fatal\" and encoding's decoder returns error, throws a TypeError.\n */\n decode(input?: BufferSource, options?: TextDecodeOptions): string;\n}\n\ndeclare var TextDecoder: {\n prototype: TextDecoder;\n new(label?: string, options?: TextDecoderOptions): TextDecoder;\n};\n\ninterface TextEncoder {\n /**\n * Returns \"utf-8\".\n */\n readonly encoding: string;\n /**\n * Returns the result of running UTF-8's encoder.\n */\n encode(input?: string): Uint8Array;\n}\n\ndeclare var TextEncoder: {\n prototype: TextEncoder;\n new(): TextEncoder;\n};\n\ninterface TextEvent extends UIEvent {\n readonly data: string;\n initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n}\n\ndeclare var TextEvent: {\n prototype: TextEvent;\n new(): TextEvent;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n};\n\ninterface TextMetrics {\n readonly width: number;\n}\n\ndeclare var TextMetrics: {\n prototype: TextMetrics;\n new(): TextMetrics;\n};\n\ninterface TextTrackEventMap {\n \"cuechange\": Event;\n \"error\": Event;\n \"load\": Event;\n}\n\ninterface TextTrack extends EventTarget {\n readonly activeCues: TextTrackCueList;\n readonly cues: TextTrackCueList;\n readonly inBandMetadataTrackDispatchType: string;\n readonly kind: string;\n readonly label: string;\n readonly language: string;\n mode: TextTrackMode | number;\n oncuechange: ((this: TextTrack, ev: Event) => any) | null;\n onerror: ((this: TextTrack, ev: Event) => any) | null;\n onload: ((this: TextTrack, ev: Event) => any) | null;\n readonly readyState: number;\n addCue(cue: TextTrackCue): void;\n removeCue(cue: TextTrackCue): void;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrack: {\n prototype: TextTrack;\n new(): TextTrack;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n};\n\ninterface TextTrackCueEventMap {\n \"enter\": Event;\n \"exit\": Event;\n}\n\ninterface TextTrackCue extends EventTarget {\n endTime: number;\n id: string;\n onenter: ((this: TextTrackCue, ev: Event) => any) | null;\n onexit: ((this: TextTrackCue, ev: Event) => any) | null;\n pauseOnExit: boolean;\n startTime: number;\n text: string;\n readonly track: TextTrack;\n getCueAsHTML(): DocumentFragment;\n addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrackCue: {\n prototype: TextTrackCue;\n new(startTime: number, endTime: number, text: string): TextTrackCue;\n};\n\ninterface TextTrackCueList {\n readonly length: number;\n getCueById(id: string): TextTrackCue;\n item(index: number): TextTrackCue;\n [index: number]: TextTrackCue;\n}\n\ndeclare var TextTrackCueList: {\n prototype: TextTrackCueList;\n new(): TextTrackCueList;\n};\n\ninterface TextTrackListEventMap {\n \"addtrack\": TrackEvent;\n}\n\ninterface TextTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null;\n item(index: number): TextTrack;\n addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: TextTrack;\n}\n\ndeclare var TextTrackList: {\n prototype: TextTrackList;\n new(): TextTrackList;\n};\n\ninterface TimeRanges {\n readonly length: number;\n end(index: number): number;\n start(index: number): number;\n}\n\ndeclare var TimeRanges: {\n prototype: TimeRanges;\n new(): TimeRanges;\n};\n\ninterface Touch {\n readonly altitudeAngle: number;\n readonly azimuthAngle: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly force: number;\n readonly identifier: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly radiusX: number;\n readonly radiusY: number;\n readonly rotationAngle: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly target: EventTarget;\n readonly touchType: TouchType;\n}\n\ndeclare var Touch: {\n prototype: Touch;\n new(touchInitDict: TouchInit): Touch;\n};\n\ninterface TouchEvent extends UIEvent {\n readonly altKey: boolean;\n readonly changedTouches: TouchList;\n readonly ctrlKey: boolean;\n readonly metaKey: boolean;\n readonly shiftKey: boolean;\n readonly targetTouches: TouchList;\n readonly touches: TouchList;\n}\n\ndeclare var TouchEvent: {\n prototype: TouchEvent;\n new(type: string, eventInitDict?: TouchEventInit): TouchEvent;\n};\n\ninterface TouchList {\n readonly length: number;\n item(index: number): Touch | null;\n [index: number]: Touch;\n}\n\ndeclare var TouchList: {\n prototype: TouchList;\n new(): TouchList;\n};\n\ninterface TrackEvent extends Event {\n readonly track: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ndeclare var TrackEvent: {\n prototype: TrackEvent;\n new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent;\n};\n\ninterface TransitionEvent extends Event {\n readonly elapsedTime: number;\n readonly propertyName: string;\n readonly pseudoElement: string;\n}\n\ndeclare var TransitionEvent: {\n prototype: TransitionEvent;\n new(type: string, transitionEventInitDict?: TransitionEventInit): TransitionEvent;\n};\n\ninterface TreeWalker {\n currentNode: Node;\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n firstChild(): Node | null;\n lastChild(): Node | null;\n nextNode(): Node | null;\n nextSibling(): Node | null;\n parentNode(): Node | null;\n previousNode(): Node | null;\n previousSibling(): Node | null;\n}\n\ndeclare var TreeWalker: {\n prototype: TreeWalker;\n new(): TreeWalker;\n};\n\ninterface UIEvent extends Event {\n readonly detail: number;\n readonly view: Window;\n initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void;\n}\n\ndeclare var UIEvent: {\n prototype: UIEvent;\n new(typeArg: string, eventInitDict?: UIEventInit): UIEvent;\n};\n\ninterface URL {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n readonly searchParams: URLSearchParams;\n username: string;\n toJSON(): string;\n}\n\ndeclare var URL: {\n prototype: URL;\n new(url: string, base?: string | URL): URL;\n createObjectURL(object: any): string;\n revokeObjectURL(url: string): void;\n};\n\ntype webkitURL = URL;\ndeclare var webkitURL: typeof URL;\n\ninterface URLSearchParams {\n /**\n * Appends a specified key/value pair as a new search parameter.\n */\n append(name: string, value: string): void;\n /**\n * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n */\n delete(name: string): void;\n /**\n * Returns the first value associated to the given search parameter.\n */\n get(name: string): string | null;\n /**\n * Returns all the values association with a given search parameter.\n */\n getAll(name: string): string[];\n /**\n * Returns a Boolean indicating if such a search parameter exists.\n */\n has(name: string): boolean;\n /**\n * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n */\n set(name: string, value: string): void;\n sort(): void;\n forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void;\n}\n\ndeclare var URLSearchParams: {\n prototype: URLSearchParams;\n new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams;\n};\n\ninterface VRDisplay extends EventTarget {\n readonly capabilities: VRDisplayCapabilities;\n depthFar: number;\n depthNear: number;\n readonly displayId: number;\n readonly displayName: string;\n readonly isConnected: boolean;\n readonly isPresenting: boolean;\n readonly stageParameters: VRStageParameters | null;\n cancelAnimationFrame(handle: number): void;\n exitPresent(): Promise;\n getEyeParameters(whichEye: string): VREyeParameters;\n getFrameData(frameData: VRFrameData): boolean;\n getLayers(): VRLayer[];\n /** @deprecated */\n getPose(): VRPose;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n requestPresent(layers: VRLayer[]): Promise;\n resetPose(): void;\n submitFrame(pose?: VRPose): void;\n}\n\ndeclare var VRDisplay: {\n prototype: VRDisplay;\n new(): VRDisplay;\n};\n\ninterface VRDisplayCapabilities {\n readonly canPresent: boolean;\n readonly hasExternalDisplay: boolean;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly maxLayers: number;\n}\n\ndeclare var VRDisplayCapabilities: {\n prototype: VRDisplayCapabilities;\n new(): VRDisplayCapabilities;\n};\n\ninterface VRDisplayEvent extends Event {\n readonly display: VRDisplay;\n readonly reason: VRDisplayEventReason | null;\n}\n\ndeclare var VRDisplayEvent: {\n prototype: VRDisplayEvent;\n new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent;\n};\n\ninterface VREyeParameters {\n /** @deprecated */\n readonly fieldOfView: VRFieldOfView;\n readonly offset: Float32Array;\n readonly renderHeight: number;\n readonly renderWidth: number;\n}\n\ndeclare var VREyeParameters: {\n prototype: VREyeParameters;\n new(): VREyeParameters;\n};\n\ninterface VRFieldOfView {\n readonly downDegrees: number;\n readonly leftDegrees: number;\n readonly rightDegrees: number;\n readonly upDegrees: number;\n}\n\ndeclare var VRFieldOfView: {\n prototype: VRFieldOfView;\n new(): VRFieldOfView;\n};\n\ninterface VRFrameData {\n readonly leftProjectionMatrix: Float32Array;\n readonly leftViewMatrix: Float32Array;\n readonly pose: VRPose;\n readonly rightProjectionMatrix: Float32Array;\n readonly rightViewMatrix: Float32Array;\n readonly timestamp: number;\n}\n\ndeclare var VRFrameData: {\n prototype: VRFrameData;\n new(): VRFrameData;\n};\n\ninterface VRPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n readonly timestamp: number;\n}\n\ndeclare var VRPose: {\n prototype: VRPose;\n new(): VRPose;\n};\n\ninterface ValidityState {\n readonly badInput: boolean;\n readonly customError: boolean;\n readonly patternMismatch: boolean;\n readonly rangeOverflow: boolean;\n readonly rangeUnderflow: boolean;\n readonly stepMismatch: boolean;\n readonly tooLong: boolean;\n readonly tooShort: boolean;\n readonly typeMismatch: boolean;\n readonly valid: boolean;\n readonly valueMissing: boolean;\n}\n\ndeclare var ValidityState: {\n prototype: ValidityState;\n new(): ValidityState;\n};\n\ninterface VideoPlaybackQuality {\n readonly corruptedVideoFrames: number;\n readonly creationTime: number;\n readonly droppedVideoFrames: number;\n readonly totalFrameDelay: number;\n readonly totalVideoFrames: number;\n}\n\ndeclare var VideoPlaybackQuality: {\n prototype: VideoPlaybackQuality;\n new(): VideoPlaybackQuality;\n};\n\ninterface VideoTrack {\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n selected: boolean;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var VideoTrack: {\n prototype: VideoTrack;\n new(): VideoTrack;\n};\n\ninterface VideoTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface VideoTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: VideoTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n readonly selectedIndex: number;\n getTrackById(id: string): VideoTrack | null;\n item(index: number): VideoTrack;\n addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: VideoTrack;\n}\n\ndeclare var VideoTrackList: {\n prototype: VideoTrackList;\n new(): VideoTrackList;\n};\n\ninterface WEBGL_color_buffer_float {\n readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;\n readonly RGB32F_EXT: number;\n readonly RGBA32F_EXT: number;\n readonly UNSIGNED_NORMALIZED_EXT: number;\n}\n\ninterface WEBGL_compressed_texture_astc {\n readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number;\n getSupportedProfiles(): string[];\n}\n\ninterface WEBGL_compressed_texture_s3tc {\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n}\n\ndeclare var WEBGL_compressed_texture_s3tc: {\n prototype: WEBGL_compressed_texture_s3tc;\n new(): WEBGL_compressed_texture_s3tc;\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n};\n\ninterface WEBGL_compressed_texture_s3tc_srgb {\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number;\n}\n\ninterface WEBGL_debug_renderer_info {\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n}\n\ndeclare var WEBGL_debug_renderer_info: {\n prototype: WEBGL_debug_renderer_info;\n new(): WEBGL_debug_renderer_info;\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n};\n\ninterface WEBGL_debug_shaders {\n getTranslatedShaderSource(shader: WebGLShader): string;\n}\n\ninterface WEBGL_depth_texture {\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n}\n\ndeclare var WEBGL_depth_texture: {\n prototype: WEBGL_depth_texture;\n new(): WEBGL_depth_texture;\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n};\n\ninterface WEBGL_draw_buffers {\n readonly COLOR_ATTACHMENT0_WEBGL: number;\n readonly COLOR_ATTACHMENT10_WEBGL: number;\n readonly COLOR_ATTACHMENT11_WEBGL: number;\n readonly COLOR_ATTACHMENT12_WEBGL: number;\n readonly COLOR_ATTACHMENT13_WEBGL: number;\n readonly COLOR_ATTACHMENT14_WEBGL: number;\n readonly COLOR_ATTACHMENT15_WEBGL: number;\n readonly COLOR_ATTACHMENT1_WEBGL: number;\n readonly COLOR_ATTACHMENT2_WEBGL: number;\n readonly COLOR_ATTACHMENT3_WEBGL: number;\n readonly COLOR_ATTACHMENT4_WEBGL: number;\n readonly COLOR_ATTACHMENT5_WEBGL: number;\n readonly COLOR_ATTACHMENT6_WEBGL: number;\n readonly COLOR_ATTACHMENT7_WEBGL: number;\n readonly COLOR_ATTACHMENT8_WEBGL: number;\n readonly COLOR_ATTACHMENT9_WEBGL: number;\n readonly DRAW_BUFFER0_WEBGL: number;\n readonly DRAW_BUFFER10_WEBGL: number;\n readonly DRAW_BUFFER11_WEBGL: number;\n readonly DRAW_BUFFER12_WEBGL: number;\n readonly DRAW_BUFFER13_WEBGL: number;\n readonly DRAW_BUFFER14_WEBGL: number;\n readonly DRAW_BUFFER15_WEBGL: number;\n readonly DRAW_BUFFER1_WEBGL: number;\n readonly DRAW_BUFFER2_WEBGL: number;\n readonly DRAW_BUFFER3_WEBGL: number;\n readonly DRAW_BUFFER4_WEBGL: number;\n readonly DRAW_BUFFER5_WEBGL: number;\n readonly DRAW_BUFFER6_WEBGL: number;\n readonly DRAW_BUFFER7_WEBGL: number;\n readonly DRAW_BUFFER8_WEBGL: number;\n readonly DRAW_BUFFER9_WEBGL: number;\n readonly MAX_COLOR_ATTACHMENTS_WEBGL: number;\n readonly MAX_DRAW_BUFFERS_WEBGL: number;\n drawBuffersWEBGL(buffers: number[]): void;\n}\n\ninterface WEBGL_lose_context {\n loseContext(): void;\n restoreContext(): void;\n}\n\ninterface WaveShaperNode extends AudioNode {\n curve: Float32Array | null;\n oversample: OverSampleType;\n}\n\ndeclare var WaveShaperNode: {\n prototype: WaveShaperNode;\n new(context: BaseAudioContext, options?: WaveShaperOptions): WaveShaperNode;\n};\n\ninterface WebAuthentication {\n getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise;\n makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise;\n}\n\ndeclare var WebAuthentication: {\n prototype: WebAuthentication;\n new(): WebAuthentication;\n};\n\ninterface WebAuthnAssertion {\n readonly authenticatorData: ArrayBuffer;\n readonly clientData: ArrayBuffer;\n readonly credential: ScopedCredential;\n readonly signature: ArrayBuffer;\n}\n\ndeclare var WebAuthnAssertion: {\n prototype: WebAuthnAssertion;\n new(): WebAuthnAssertion;\n};\n\ninterface WebGLActiveInfo {\n readonly name: string;\n readonly size: number;\n readonly type: number;\n}\n\ndeclare var WebGLActiveInfo: {\n prototype: WebGLActiveInfo;\n new(): WebGLActiveInfo;\n};\n\ninterface WebGLBuffer extends WebGLObject {\n}\n\ndeclare var WebGLBuffer: {\n prototype: WebGLBuffer;\n new(): WebGLBuffer;\n};\n\ninterface WebGLContextEvent extends Event {\n readonly statusMessage: string;\n}\n\ndeclare var WebGLContextEvent: {\n prototype: WebGLContextEvent;\n new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent;\n};\n\ninterface WebGLFramebuffer extends WebGLObject {\n}\n\ndeclare var WebGLFramebuffer: {\n prototype: WebGLFramebuffer;\n new(): WebGLFramebuffer;\n};\n\ninterface WebGLObject {\n}\n\ndeclare var WebGLObject: {\n prototype: WebGLObject;\n new(): WebGLObject;\n};\n\ninterface WebGLProgram extends WebGLObject {\n}\n\ndeclare var WebGLProgram: {\n prototype: WebGLProgram;\n new(): WebGLProgram;\n};\n\ninterface WebGLRenderbuffer extends WebGLObject {\n}\n\ndeclare var WebGLRenderbuffer: {\n prototype: WebGLRenderbuffer;\n new(): WebGLRenderbuffer;\n};\n\ninterface WebGLRenderingContext {\n readonly canvas: HTMLCanvasElement;\n readonly drawingBufferHeight: number;\n readonly drawingBufferWidth: number;\n activeTexture(texture: number): void;\n attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void;\n bindBuffer(target: number, buffer: WebGLBuffer | null): void;\n bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void;\n bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void;\n bindTexture(target: number, texture: WebGLTexture | null): void;\n blendColor(red: number, green: number, blue: number, alpha: number): void;\n blendEquation(mode: number): void;\n blendEquationSeparate(modeRGB: number, modeAlpha: number): void;\n blendFunc(sfactor: number, dfactor: number): void;\n blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;\n bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void;\n bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void;\n checkFramebufferStatus(target: number): number;\n clear(mask: number): void;\n clearColor(red: number, green: number, blue: number, alpha: number): void;\n clearDepth(depth: number): void;\n clearStencil(s: number): void;\n colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void;\n compileShader(shader: WebGLShader | null): void;\n compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void;\n copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void;\n createBuffer(): WebGLBuffer | null;\n createFramebuffer(): WebGLFramebuffer | null;\n createProgram(): WebGLProgram | null;\n createRenderbuffer(): WebGLRenderbuffer | null;\n createShader(type: number): WebGLShader | null;\n createTexture(): WebGLTexture | null;\n cullFace(mode: number): void;\n deleteBuffer(buffer: WebGLBuffer | null): void;\n deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void;\n deleteProgram(program: WebGLProgram | null): void;\n deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void;\n deleteShader(shader: WebGLShader | null): void;\n deleteTexture(texture: WebGLTexture | null): void;\n depthFunc(func: number): void;\n depthMask(flag: boolean): void;\n depthRange(zNear: number, zFar: number): void;\n detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n disable(cap: number): void;\n disableVertexAttribArray(index: number): void;\n drawArrays(mode: number, first: number, count: number): void;\n drawElements(mode: number, count: number, type: number, offset: number): void;\n enable(cap: number): void;\n enableVertexAttribArray(index: number): void;\n finish(): void;\n flush(): void;\n framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void;\n framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void;\n frontFace(mode: number): void;\n generateMipmap(target: number): void;\n getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null;\n getAttribLocation(program: WebGLProgram | null, name: string): number;\n getBufferParameter(target: number, pname: number): any;\n getContextAttributes(): WebGLContextAttributes;\n getError(): number;\n getExtension(extensionName: \"EXT_blend_minmax\"): EXT_blend_minmax | null;\n getExtension(extensionName: \"EXT_texture_filter_anisotropic\"): EXT_texture_filter_anisotropic | null;\n getExtension(extensionName: \"EXT_frag_depth\"): EXT_frag_depth | null;\n getExtension(extensionName: \"EXT_shader_texture_lod\"): EXT_shader_texture_lod | null;\n getExtension(extensionName: \"EXT_sRGB\"): EXT_sRGB | null;\n getExtension(extensionName: \"OES_vertex_array_object\"): OES_vertex_array_object | null;\n getExtension(extensionName: \"WEBGL_color_buffer_float\"): WEBGL_color_buffer_float | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_astc\"): WEBGL_compressed_texture_astc | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc_srgb\"): WEBGL_compressed_texture_s3tc_srgb | null;\n getExtension(extensionName: \"WEBGL_debug_shaders\"): WEBGL_debug_shaders | null;\n getExtension(extensionName: \"WEBGL_draw_buffers\"): WEBGL_draw_buffers | null;\n getExtension(extensionName: \"WEBGL_lose_context\"): WEBGL_lose_context | null;\n getExtension(extensionName: \"WEBGL_depth_texture\"): WEBGL_depth_texture | null;\n getExtension(extensionName: \"WEBGL_debug_renderer_info\"): WEBGL_debug_renderer_info | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc\"): WEBGL_compressed_texture_s3tc | null;\n getExtension(extensionName: \"OES_texture_half_float_linear\"): OES_texture_half_float_linear | null;\n getExtension(extensionName: \"OES_texture_half_float\"): OES_texture_half_float | null;\n getExtension(extensionName: \"OES_texture_float_linear\"): OES_texture_float_linear | null;\n getExtension(extensionName: \"OES_texture_float\"): OES_texture_float | null;\n getExtension(extensionName: \"OES_standard_derivatives\"): OES_standard_derivatives | null;\n getExtension(extensionName: \"OES_element_index_uint\"): OES_element_index_uint | null;\n getExtension(extensionName: \"ANGLE_instanced_arrays\"): ANGLE_instanced_arrays | null;\n getExtension(extensionName: string): any;\n getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any;\n getParameter(pname: number): any;\n getProgramInfoLog(program: WebGLProgram | null): string | null;\n getProgramParameter(program: WebGLProgram | null, pname: number): any;\n getRenderbufferParameter(target: number, pname: number): any;\n getShaderInfoLog(shader: WebGLShader | null): string | null;\n getShaderParameter(shader: WebGLShader | null, pname: number): any;\n getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null;\n getShaderSource(shader: WebGLShader | null): string | null;\n getSupportedExtensions(): string[] | null;\n getTexParameter(target: number, pname: number): any;\n getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any;\n getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null;\n getVertexAttrib(index: number, pname: number): any;\n getVertexAttribOffset(index: number, pname: number): number;\n hint(target: number, mode: number): void;\n isBuffer(buffer: WebGLBuffer | null): boolean;\n isContextLost(): boolean;\n isEnabled(cap: number): boolean;\n isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean;\n isProgram(program: WebGLProgram | null): boolean;\n isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean;\n isShader(shader: WebGLShader | null): boolean;\n isTexture(texture: WebGLTexture | null): boolean;\n lineWidth(width: number): void;\n linkProgram(program: WebGLProgram | null): void;\n pixelStorei(pname: number, param: number | boolean): void;\n polygonOffset(factor: number, units: number): void;\n readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n renderbufferStorage(target: number, internalformat: number, width: number, height: number): void;\n sampleCoverage(value: number, invert: boolean): void;\n scissor(x: number, y: number, width: number, height: number): void;\n shaderSource(shader: WebGLShader | null, source: string): void;\n stencilFunc(func: number, ref: number, mask: number): void;\n stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void;\n stencilMask(mask: number): void;\n stencilMaskSeparate(face: number, mask: number): void;\n stencilOp(fail: number, zfail: number, zpass: number): void;\n stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void;\n texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n texParameterf(target: number, pname: number, param: number): void;\n texParameteri(target: number, pname: number, param: number): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n uniform1f(location: WebGLUniformLocation | null, x: number): void;\n uniform1fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform1i(location: WebGLUniformLocation | null, x: number): void;\n uniform1iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n useProgram(program: WebGLProgram | null): void;\n validateProgram(program: WebGLProgram | null): void;\n vertexAttrib1f(indx: number, x: number): void;\n vertexAttrib1fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib2f(indx: number, x: number, y: number): void;\n vertexAttrib2fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib3f(indx: number, x: number, y: number, z: number): void;\n vertexAttrib3fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void;\n vertexAttrib4fv(indx: number, values: Float32Array | number[]): void;\n vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void;\n viewport(x: number, y: number, width: number, height: number): void;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n}\n\ndeclare var WebGLRenderingContext: {\n prototype: WebGLRenderingContext;\n new(): WebGLRenderingContext;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n};\n\ninterface WebGLShader extends WebGLObject {\n}\n\ndeclare var WebGLShader: {\n prototype: WebGLShader;\n new(): WebGLShader;\n};\n\ninterface WebGLShaderPrecisionFormat {\n readonly precision: number;\n readonly rangeMax: number;\n readonly rangeMin: number;\n}\n\ndeclare var WebGLShaderPrecisionFormat: {\n prototype: WebGLShaderPrecisionFormat;\n new(): WebGLShaderPrecisionFormat;\n};\n\ninterface WebGLTexture extends WebGLObject {\n}\n\ndeclare var WebGLTexture: {\n prototype: WebGLTexture;\n new(): WebGLTexture;\n};\n\ninterface WebGLUniformLocation {\n}\n\ndeclare var WebGLUniformLocation: {\n prototype: WebGLUniformLocation;\n new(): WebGLUniformLocation;\n};\n\ninterface WebGLVertexArrayObjectOES {\n}\n\ninterface WebKitPoint {\n x: number;\n y: number;\n}\n\ndeclare var WebKitPoint: {\n prototype: WebKitPoint;\n new(x?: number, y?: number): WebKitPoint;\n};\n\ninterface WebSocketEventMap {\n \"close\": CloseEvent;\n \"error\": Event;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface WebSocket extends EventTarget {\n binaryType: BinaryType;\n readonly bufferedAmount: number;\n readonly extensions: string;\n onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;\n onerror: ((this: WebSocket, ev: Event) => any) | null;\n onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;\n onopen: ((this: WebSocket, ev: Event) => any) | null;\n readonly protocol: string;\n readonly readyState: number;\n readonly url: string;\n close(code?: number, reason?: string): void;\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var WebSocket: {\n prototype: WebSocket;\n new(url: string, protocols?: string | string[]): WebSocket;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n};\n\ninterface WheelEvent extends MouseEvent {\n readonly deltaMode: number;\n readonly deltaX: number;\n readonly deltaY: number;\n readonly deltaZ: number;\n readonly wheelDelta: number;\n readonly wheelDeltaX: number;\n readonly wheelDeltaY: number;\n getCurrentPoint(element: Element): void;\n initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n}\n\ndeclare var WheelEvent: {\n prototype: WheelEvent;\n new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n};\n\ninterface WindowEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"compassneedscalibration\": Event;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"devicelight\": DeviceLightEvent;\n \"devicemotion\": DeviceMotionEvent;\n \"deviceorientation\": DeviceOrientationEvent;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"hashchange\": HashChangeEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"message\": MessageEvent;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"offline\": Event;\n \"online\": Event;\n \"orientationchange\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"popstate\": PopStateEvent;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": ProgressEvent;\n \"reset\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"stalled\": Event;\n \"storage\": StorageEvent;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"unload\": Event;\n \"volumechange\": Event;\n \"vrdisplayactivate\": Event;\n \"vrdisplayblur\": Event;\n \"vrdisplayconnect\": Event;\n \"vrdisplaydeactivate\": Event;\n \"vrdisplaydisconnect\": Event;\n \"vrdisplayfocus\": Event;\n \"vrdisplaypointerrestricted\": Event;\n \"vrdisplaypointerunrestricted\": Event;\n \"vrdisplaypresentchange\": Event;\n \"waiting\": Event;\n}\n\ninterface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {\n Blob: typeof Blob;\n URL: typeof URL;\n URLSearchParams: typeof URLSearchParams;\n readonly applicationCache: ApplicationCache;\n readonly caches: CacheStorage;\n readonly clientInformation: Navigator;\n readonly closed: boolean;\n readonly crypto: Crypto;\n customElements: CustomElementRegistry;\n defaultStatus: string;\n readonly devicePixelRatio: number;\n readonly doNotTrack: string;\n readonly document: Document;\n event: Event | undefined;\n /** @deprecated */\n readonly external: External;\n readonly frameElement: Element;\n readonly frames: Window;\n readonly history: History;\n readonly innerHeight: number;\n readonly innerWidth: number;\n readonly isSecureContext: boolean;\n readonly length: number;\n location: Location;\n readonly locationbar: BarProp;\n readonly menubar: BarProp;\n readonly msContentScript: ExtensionScriptApis;\n readonly msCredentials: MSCredentials;\n name: string;\n readonly navigator: Navigator;\n offscreenBuffering: string | boolean;\n onabort: ((this: Window, ev: UIEvent) => any) | null;\n onafterprint: ((this: Window, ev: Event) => any) | null;\n onbeforeprint: ((this: Window, ev: Event) => any) | null;\n onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\n onblur: ((this: Window, ev: FocusEvent) => any) | null;\n oncanplay: ((this: Window, ev: Event) => any) | null;\n oncanplaythrough: ((this: Window, ev: Event) => any) | null;\n onchange: ((this: Window, ev: Event) => any) | null;\n onclick: ((this: Window, ev: MouseEvent) => any) | null;\n oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\n oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\n ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\n ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\n ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\n ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\n ondrag: ((this: Window, ev: DragEvent) => any) | null;\n ondragend: ((this: Window, ev: DragEvent) => any) | null;\n ondragenter: ((this: Window, ev: DragEvent) => any) | null;\n ondragleave: ((this: Window, ev: DragEvent) => any) | null;\n ondragover: ((this: Window, ev: DragEvent) => any) | null;\n ondragstart: ((this: Window, ev: DragEvent) => any) | null;\n ondrop: ((this: Window, ev: DragEvent) => any) | null;\n ondurationchange: ((this: Window, ev: Event) => any) | null;\n onemptied: ((this: Window, ev: Event) => any) | null;\n onended: ((this: Window, ev: Event) => any) | null;\n onerror: ErrorEventHandler;\n onfocus: ((this: Window, ev: FocusEvent) => any) | null;\n onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\n oninput: ((this: Window, ev: Event) => any) | null;\n oninvalid: ((this: Window, ev: Event) => any) | null;\n onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\n onload: ((this: Window, ev: Event) => any) | null;\n onloadeddata: ((this: Window, ev: Event) => any) | null;\n onloadedmetadata: ((this: Window, ev: Event) => any) | null;\n onloadstart: ((this: Window, ev: Event) => any) | null;\n onmessage: ((this: Window, ev: MessageEvent) => any) | null;\n onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\n onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\n onmsgesturechange: ((this: Window, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\n onmsgestureend: ((this: Window, ev: Event) => any) | null;\n onmsgesturehold: ((this: Window, ev: Event) => any) | null;\n onmsgesturestart: ((this: Window, ev: Event) => any) | null;\n onmsgesturetap: ((this: Window, ev: Event) => any) | null;\n onmsinertiastart: ((this: Window, ev: Event) => any) | null;\n onmspointercancel: ((this: Window, ev: Event) => any) | null;\n onmspointerdown: ((this: Window, ev: Event) => any) | null;\n onmspointerenter: ((this: Window, ev: Event) => any) | null;\n onmspointerleave: ((this: Window, ev: Event) => any) | null;\n onmspointermove: ((this: Window, ev: Event) => any) | null;\n onmspointerout: ((this: Window, ev: Event) => any) | null;\n onmspointerover: ((this: Window, ev: Event) => any) | null;\n onmspointerup: ((this: Window, ev: Event) => any) | null;\n onoffline: ((this: Window, ev: Event) => any) | null;\n ononline: ((this: Window, ev: Event) => any) | null;\n onorientationchange: ((this: Window, ev: Event) => any) | null;\n onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpause: ((this: Window, ev: Event) => any) | null;\n onplay: ((this: Window, ev: Event) => any) | null;\n onplaying: ((this: Window, ev: Event) => any) | null;\n onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\n onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\n onratechange: ((this: Window, ev: Event) => any) | null;\n onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\n onreset: ((this: Window, ev: Event) => any) | null;\n onresize: ((this: Window, ev: UIEvent) => any) | null;\n onscroll: ((this: Window, ev: UIEvent) => any) | null;\n onseeked: ((this: Window, ev: Event) => any) | null;\n onseeking: ((this: Window, ev: Event) => any) | null;\n onselect: ((this: Window, ev: UIEvent) => any) | null;\n onstalled: ((this: Window, ev: Event) => any) | null;\n onstorage: ((this: Window, ev: StorageEvent) => any) | null;\n onsubmit: ((this: Window, ev: Event) => any) | null;\n onsuspend: ((this: Window, ev: Event) => any) | null;\n ontimeupdate: ((this: Window, ev: Event) => any) | null;\n onunload: ((this: Window, ev: Event) => any) | null;\n onvolumechange: ((this: Window, ev: Event) => any) | null;\n onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\n onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\n onwaiting: ((this: Window, ev: Event) => any) | null;\n opener: any;\n readonly orientation: string | number;\n readonly outerHeight: number;\n readonly outerWidth: number;\n readonly pageXOffset: number;\n readonly pageYOffset: number;\n readonly parent: Window;\n readonly performance: Performance;\n readonly personalbar: BarProp;\n readonly screen: Screen;\n readonly screenLeft: number;\n readonly screenTop: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly scrollX: number;\n readonly scrollY: number;\n readonly scrollbars: BarProp;\n readonly self: Window;\n readonly speechSynthesis: SpeechSynthesis;\n status: string;\n readonly statusbar: BarProp;\n readonly styleMedia: StyleMedia;\n readonly toolbar: BarProp;\n readonly top: Window;\n readonly window: Window;\n alert(message?: any): void;\n blur(): void;\n cancelAnimationFrame(handle: number): void;\n /** @deprecated */\n captureEvents(): void;\n close(): void;\n confirm(message?: string): boolean;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\n departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\n focus(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\n getSelection(): Selection;\n matchMedia(mediaQuery: string): MediaQueryList;\n moveBy(x?: number, y?: number): void;\n moveTo(x?: number, y?: number): void;\n msWriteProfilerMark(profilerMarkName: string): void;\n open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\n postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\n print(): void;\n prompt(message?: string, _default?: string): string | null;\n /** @deprecated */\n releaseEvents(): void;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n resizeBy(x?: number, y?: number): void;\n resizeTo(x?: number, y?: number): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x?: number, y?: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x?: number, y?: number): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x?: number, y?: number): void;\n stop(): void;\n webkitCancelAnimationFrame(handle: number): void;\n webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\n addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Window: {\n prototype: Window;\n new(): Window;\n};\n\ninterface WindowBase64 {\n atob(encodedString: string): string;\n btoa(rawString: string): string;\n}\n\ninterface WindowConsole {\n readonly console: Console;\n}\n\ninterface WindowEventHandlersEventMap {\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"hashchange\": HashChangeEvent;\n \"message\": MessageEvent;\n \"offline\": Event;\n \"online\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"popstate\": PopStateEvent;\n \"storage\": StorageEvent;\n \"unload\": Event;\n}\n\ninterface WindowEventHandlers {\n onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null;\n onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null;\n onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null;\n onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n ononline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null;\n onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null;\n onunload: ((this: WindowEventHandlers, ev: Event) => any) | null;\n addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface WindowLocalStorage {\n readonly localStorage: Storage;\n}\n\ninterface WindowOrWorkerGlobalScope {\n readonly caches: CacheStorage;\n readonly indexedDB: IDBFactory;\n readonly performance: Performance;\n fetch(input: RequestInfo, init?: RequestInit): Promise;\n}\n\ninterface WindowSessionStorage {\n readonly sessionStorage: Storage;\n}\n\ninterface WindowTimers extends WindowTimersExtension {\n clearInterval(handle?: number): void;\n clearTimeout(handle?: number): void;\n setInterval(handler: (...args: any[]) => void, timeout: number): number;\n setInterval(handler: any, timeout?: any, ...args: any[]): number;\n setTimeout(handler: (...args: any[]) => void, timeout: number): number;\n setTimeout(handler: any, timeout?: any, ...args: any[]): number;\n}\n\ninterface WindowTimersExtension {\n clearImmediate(handle: number): void;\n setImmediate(handler: (...args: any[]) => void): number;\n setImmediate(handler: any, ...args: any[]): number;\n}\n\ninterface WorkerEventMap extends AbstractWorkerEventMap {\n \"message\": MessageEvent;\n}\n\ninterface Worker extends EventTarget, AbstractWorker {\n onmessage: ((this: Worker, ev: MessageEvent) => any) | null;\n postMessage(message: any, transfer?: any[]): void;\n terminate(): void;\n addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Worker: {\n prototype: Worker;\n new(stringUrl: string): Worker;\n};\n\ninterface Worklet {\n addModule(moduleURL: string, options?: WorkletOptions): Promise;\n}\n\ndeclare var Worklet: {\n prototype: Worklet;\n new(): Worklet;\n};\n\ninterface WritableStream {\n readonly locked: boolean;\n abort(reason?: any): Promise;\n getWriter(): WritableStreamDefaultWriter;\n}\n\ndeclare var WritableStream: {\n prototype: WritableStream;\n new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream;\n};\n\ninterface WritableStreamDefaultController {\n error(error?: any): void;\n}\n\ndeclare var WritableStreamDefaultController: {\n prototype: WritableStreamDefaultController;\n new(): WritableStreamDefaultController;\n};\n\ninterface WritableStreamDefaultWriter {\n readonly closed: Promise;\n readonly desiredSize: number;\n readonly ready: Promise;\n abort(reason?: any): Promise;\n close(): Promise;\n releaseLock(): void;\n write(chunk?: any): Promise;\n}\n\ndeclare var WritableStreamDefaultWriter: {\n prototype: WritableStreamDefaultWriter;\n new(): WritableStreamDefaultWriter;\n};\n\ninterface XMLDocument extends Document {\n addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLDocument: {\n prototype: XMLDocument;\n new(): XMLDocument;\n};\n\ninterface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {\n \"readystatechange\": Event;\n}\n\ninterface XMLHttpRequest extends XMLHttpRequestEventTarget {\n onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;\n /**\n * Returns client's state.\n */\n readonly readyState: number;\n /**\n * Returns the response's body.\n */\n readonly response: any;\n /**\n * Returns the text response.\n * Throws an \"InvalidStateError\" DOMException if responseType is not the empty string or \"text\".\n */\n readonly responseText: string;\n /**\n * Returns the response type.\n * Can be set to change the response type. Values are:\n * the empty string (default),\n * \"arraybuffer\",\n * \"blob\",\n * \"document\",\n * \"json\", and\n * \"text\".\n * When set: setting to \"document\" is ignored if current global object is not a Window object.\n * When set: throws an \"InvalidStateError\" DOMException if state is loading or done.\n * When set: throws an \"InvalidAccessError\" DOMException if the synchronous flag is set and current global object is a Window object.\n */\n responseType: XMLHttpRequestResponseType;\n readonly responseURL: string;\n /**\n * Returns the document response.\n * Throws an \"InvalidStateError\" DOMException if responseType is not the empty string or \"document\".\n */\n readonly responseXML: Document | null;\n readonly status: number;\n readonly statusText: string;\n /**\n * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the\n * request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a\n * \"TimeoutError\" DOMException will be thrown otherwise (for the send() method).\n * When set: throws an \"InvalidAccessError\" DOMException if the synchronous flag is set and current global object is a Window object.\n */\n timeout: number;\n /**\n * Returns the associated XMLHttpRequestUpload object. It can be used to gather transmission information when data is\n * transferred to a server.\n */\n readonly upload: XMLHttpRequestUpload;\n /**\n * True when credentials are to be included in a cross-origin request. False when they are\n * to be excluded in a cross-origin request and when cookies are to be ignored in its response.\n * Initially false.\n * When set: throws an \"InvalidStateError\" DOMException if state is not unsent or opened, or if the send() flag is set.\n */\n withCredentials: boolean;\n /**\n * Cancels any network activity.\n */\n abort(): void;\n getAllResponseHeaders(): string;\n getResponseHeader(name: string): string | null;\n /**\n * Sets the request method, request URL, and synchronous flag.\n * Throws a \"SyntaxError\" DOMException if either method is not a\n * valid HTTP method or url cannot be parsed.\n * Throws a \"SecurityError\" DOMException if method is a\n * case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`.\n * Throws an \"InvalidAccessError\" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string.\n */\n open(method: string, url: string): void;\n open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void;\n /**\n * Acts as if the `Content-Type` header value for response is mime.\n * (It does not actually change the header though.)\n * Throws an \"InvalidStateError\" DOMException if state is loading or done.\n */\n overrideMimeType(mime: string): void;\n /**\n * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.\n * Throws an \"InvalidStateError\" DOMException if either state is not opened or the send() flag is set.\n */\n send(body?: Document | BodyInit): void;\n /**\n * Combines a header in author request headers.\n * Throws an \"InvalidStateError\" DOMException if either state is not opened or the send() flag is set.\n * Throws a \"SyntaxError\" DOMException if name is not a header name\n * or if value is not a header value.\n */\n setRequestHeader(name: string, value: string): void;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequest: {\n prototype: XMLHttpRequest;\n new(): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\n\ninterface XMLHttpRequestEventTargetEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n \"timeout\": ProgressEvent;\n}\n\ninterface XMLHttpRequestEventTarget extends EventTarget {\n onabort: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onerror: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onload: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestEventTarget: {\n prototype: XMLHttpRequestEventTarget;\n new(): XMLHttpRequestEventTarget;\n};\n\ninterface XMLHttpRequestUpload extends XMLHttpRequestEventTarget {\n addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestUpload: {\n prototype: XMLHttpRequestUpload;\n new(): XMLHttpRequestUpload;\n};\n\ninterface XMLSerializer {\n serializeToString(target: Node): string;\n}\n\ndeclare var XMLSerializer: {\n prototype: XMLSerializer;\n new(): XMLSerializer;\n};\n\ninterface XPathEvaluator {\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver?: Node): XPathNSResolver;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathEvaluator: {\n prototype: XPathEvaluator;\n new(): XPathEvaluator;\n};\n\ninterface XPathExpression {\n evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathExpression: {\n prototype: XPathExpression;\n new(): XPathExpression;\n};\n\ninterface XPathNSResolver {\n lookupNamespaceURI(prefix: string): string;\n}\n\ndeclare var XPathNSResolver: {\n prototype: XPathNSResolver;\n new(): XPathNSResolver;\n};\n\ninterface XPathResult {\n readonly booleanValue: boolean;\n readonly invalidIteratorState: boolean;\n readonly numberValue: number;\n readonly resultType: number;\n readonly singleNodeValue: Node;\n readonly snapshotLength: number;\n readonly stringValue: string;\n iterateNext(): Node;\n snapshotItem(index: number): Node;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n}\n\ndeclare var XPathResult: {\n prototype: XPathResult;\n new(): XPathResult;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n};\n\ninterface XSLTProcessor {\n clearParameters(): void;\n getParameter(namespaceURI: string, localName: string): any;\n importStylesheet(style: Node): void;\n removeParameter(namespaceURI: string, localName: string): void;\n reset(): void;\n setParameter(namespaceURI: string, localName: string, value: any): void;\n transformToDocument(source: Node): Document;\n transformToFragment(source: Node, document: Document): DocumentFragment;\n}\n\ndeclare var XSLTProcessor: {\n prototype: XSLTProcessor;\n new(): XSLTProcessor;\n};\n\ninterface webkitRTCPeerConnection extends RTCPeerConnection {\n addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var webkitRTCPeerConnection: {\n prototype: webkitRTCPeerConnection;\n new(configuration: RTCConfiguration): webkitRTCPeerConnection;\n};\n\ndeclare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;\n\ninterface DecodeErrorCallback {\n (error: DOMException): void;\n}\n\ninterface DecodeSuccessCallback {\n (decodedData: AudioBuffer): void;\n}\n\ninterface ErrorEventHandler {\n (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void;\n}\n\ninterface EventHandlerNonNull {\n (event: Event): any;\n}\n\ninterface ForEachCallback {\n (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void;\n}\n\ninterface FrameRequestCallback {\n (time: number): void;\n}\n\ninterface FunctionStringCallback {\n (data: string): void;\n}\n\ninterface GenerateAssertionCallback {\n (contents: string, origin: string, options: RTCIdentityProviderOptions): Promise;\n}\n\ninterface IntersectionObserverCallback {\n (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;\n}\n\ninterface MSLaunchUriCallback {\n (): void;\n}\n\ninterface MediaQueryListListener {\n (mql: MediaQueryList): void;\n}\n\ninterface MutationCallback {\n (mutations: MutationRecord[], observer: MutationObserver): void;\n}\n\ninterface NavigatorUserMediaErrorCallback {\n (error: MediaStreamError): void;\n}\n\ninterface NavigatorUserMediaSuccessCallback {\n (stream: MediaStream): void;\n}\n\ninterface NotificationPermissionCallback {\n (permission: NotificationPermission): void;\n}\n\ninterface PerformanceObserverCallback {\n (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void;\n}\n\ninterface PositionCallback {\n (position: Position): void;\n}\n\ninterface PositionErrorCallback {\n (positionError: PositionError): void;\n}\n\ninterface RTCPeerConnectionErrorCallback {\n (error: DOMException): void;\n}\n\ninterface RTCSessionDescriptionCallback {\n (description: RTCSessionDescriptionInit): void;\n}\n\ninterface RTCStatsCallback {\n (report: RTCStatsReport): void;\n}\n\ninterface ValidateAssertionCallback {\n (assertion: string, origin: string): Promise;\n}\n\ninterface VoidFunction {\n (): void;\n}\n\ninterface WritableStreamChunkCallback {\n (chunk: any, controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamDefaultControllerCallback {\n (controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamErrorCallback {\n (reason: string): void;\n}\n\ninterface HTMLElementTagNameMap {\n \"a\": HTMLAnchorElement;\n \"abbr\": HTMLElement;\n \"acronym\": HTMLElement;\n \"address\": HTMLElement;\n \"applet\": HTMLAppletElement;\n \"area\": HTMLAreaElement;\n \"article\": HTMLElement;\n \"aside\": HTMLElement;\n \"audio\": HTMLAudioElement;\n \"b\": HTMLElement;\n \"base\": HTMLBaseElement;\n \"basefont\": HTMLBaseFontElement;\n \"bdo\": HTMLElement;\n \"big\": HTMLElement;\n \"blockquote\": HTMLQuoteElement;\n \"body\": HTMLBodyElement;\n \"br\": HTMLBRElement;\n \"button\": HTMLButtonElement;\n \"canvas\": HTMLCanvasElement;\n \"caption\": HTMLTableCaptionElement;\n \"center\": HTMLElement;\n \"cite\": HTMLElement;\n \"code\": HTMLElement;\n \"col\": HTMLTableColElement;\n \"colgroup\": HTMLTableColElement;\n \"data\": HTMLDataElement;\n \"datalist\": HTMLDataListElement;\n \"dd\": HTMLElement;\n \"del\": HTMLModElement;\n \"dfn\": HTMLElement;\n \"dir\": HTMLDirectoryElement;\n \"div\": HTMLDivElement;\n \"dl\": HTMLDListElement;\n \"dt\": HTMLElement;\n \"em\": HTMLElement;\n \"embed\": HTMLEmbedElement;\n \"fieldset\": HTMLFieldSetElement;\n \"figcaption\": HTMLElement;\n \"figure\": HTMLElement;\n \"font\": HTMLFontElement;\n \"footer\": HTMLElement;\n \"form\": HTMLFormElement;\n \"frame\": HTMLFrameElement;\n \"frameset\": HTMLFrameSetElement;\n \"h1\": HTMLHeadingElement;\n \"h2\": HTMLHeadingElement;\n \"h3\": HTMLHeadingElement;\n \"h4\": HTMLHeadingElement;\n \"h5\": HTMLHeadingElement;\n \"h6\": HTMLHeadingElement;\n \"head\": HTMLHeadElement;\n \"header\": HTMLElement;\n \"hgroup\": HTMLElement;\n \"hr\": HTMLHRElement;\n \"html\": HTMLHtmlElement;\n \"i\": HTMLElement;\n \"iframe\": HTMLIFrameElement;\n \"img\": HTMLImageElement;\n \"input\": HTMLInputElement;\n \"ins\": HTMLModElement;\n \"isindex\": HTMLUnknownElement;\n \"kbd\": HTMLElement;\n \"keygen\": HTMLElement;\n \"label\": HTMLLabelElement;\n \"legend\": HTMLLegendElement;\n \"li\": HTMLLIElement;\n \"link\": HTMLLinkElement;\n \"listing\": HTMLPreElement;\n \"map\": HTMLMapElement;\n \"mark\": HTMLElement;\n \"marquee\": HTMLMarqueeElement;\n \"menu\": HTMLMenuElement;\n \"meta\": HTMLMetaElement;\n \"meter\": HTMLMeterElement;\n \"nav\": HTMLElement;\n \"nextid\": HTMLUnknownElement;\n \"nobr\": HTMLElement;\n \"noframes\": HTMLElement;\n \"noscript\": HTMLElement;\n \"object\": HTMLObjectElement;\n \"ol\": HTMLOListElement;\n \"optgroup\": HTMLOptGroupElement;\n \"option\": HTMLOptionElement;\n \"output\": HTMLOutputElement;\n \"p\": HTMLParagraphElement;\n \"param\": HTMLParamElement;\n \"picture\": HTMLPictureElement;\n \"plaintext\": HTMLElement;\n \"pre\": HTMLPreElement;\n \"progress\": HTMLProgressElement;\n \"q\": HTMLQuoteElement;\n \"rt\": HTMLElement;\n \"ruby\": HTMLElement;\n \"s\": HTMLElement;\n \"samp\": HTMLElement;\n \"script\": HTMLScriptElement;\n \"section\": HTMLElement;\n \"select\": HTMLSelectElement;\n \"slot\": HTMLSlotElement;\n \"small\": HTMLElement;\n \"source\": HTMLSourceElement;\n \"span\": HTMLSpanElement;\n \"strike\": HTMLElement;\n \"strong\": HTMLElement;\n \"style\": HTMLStyleElement;\n \"sub\": HTMLElement;\n \"sup\": HTMLElement;\n \"table\": HTMLTableElement;\n \"tbody\": HTMLTableSectionElement;\n \"td\": HTMLTableDataCellElement;\n \"template\": HTMLTemplateElement;\n \"textarea\": HTMLTextAreaElement;\n \"tfoot\": HTMLTableSectionElement;\n \"th\": HTMLTableHeaderCellElement;\n \"thead\": HTMLTableSectionElement;\n \"time\": HTMLTimeElement;\n \"title\": HTMLTitleElement;\n \"tr\": HTMLTableRowElement;\n \"track\": HTMLTrackElement;\n \"tt\": HTMLElement;\n \"u\": HTMLElement;\n \"ul\": HTMLUListElement;\n \"var\": HTMLElement;\n \"video\": HTMLVideoElement;\n \"wbr\": HTMLElement;\n \"xmp\": HTMLPreElement;\n}\n\ninterface SVGElementTagNameMap {\n \"circle\": SVGCircleElement;\n \"clipPath\": SVGClipPathElement;\n \"defs\": SVGDefsElement;\n \"desc\": SVGDescElement;\n \"ellipse\": SVGEllipseElement;\n \"feBlend\": SVGFEBlendElement;\n \"feColorMatrix\": SVGFEColorMatrixElement;\n \"feComponentTransfer\": SVGFEComponentTransferElement;\n \"feComposite\": SVGFECompositeElement;\n \"feConvolveMatrix\": SVGFEConvolveMatrixElement;\n \"feDiffuseLighting\": SVGFEDiffuseLightingElement;\n \"feDisplacementMap\": SVGFEDisplacementMapElement;\n \"feDistantLight\": SVGFEDistantLightElement;\n \"feFlood\": SVGFEFloodElement;\n \"feFuncA\": SVGFEFuncAElement;\n \"feFuncB\": SVGFEFuncBElement;\n \"feFuncG\": SVGFEFuncGElement;\n \"feFuncR\": SVGFEFuncRElement;\n \"feGaussianBlur\": SVGFEGaussianBlurElement;\n \"feImage\": SVGFEImageElement;\n \"feMerge\": SVGFEMergeElement;\n \"feMergeNode\": SVGFEMergeNodeElement;\n \"feMorphology\": SVGFEMorphologyElement;\n \"feOffset\": SVGFEOffsetElement;\n \"fePointLight\": SVGFEPointLightElement;\n \"feSpecularLighting\": SVGFESpecularLightingElement;\n \"feSpotLight\": SVGFESpotLightElement;\n \"feTile\": SVGFETileElement;\n \"feTurbulence\": SVGFETurbulenceElement;\n \"filter\": SVGFilterElement;\n \"foreignObject\": SVGForeignObjectElement;\n \"g\": SVGGElement;\n \"image\": SVGImageElement;\n \"line\": SVGLineElement;\n \"linearGradient\": SVGLinearGradientElement;\n \"marker\": SVGMarkerElement;\n \"mask\": SVGMaskElement;\n \"metadata\": SVGMetadataElement;\n \"path\": SVGPathElement;\n \"pattern\": SVGPatternElement;\n \"polygon\": SVGPolygonElement;\n \"polyline\": SVGPolylineElement;\n \"radialGradient\": SVGRadialGradientElement;\n \"rect\": SVGRectElement;\n \"stop\": SVGStopElement;\n \"svg\": SVGSVGElement;\n \"switch\": SVGSwitchElement;\n \"symbol\": SVGSymbolElement;\n \"text\": SVGTextElement;\n \"textPath\": SVGTextPathElement;\n \"tspan\": SVGTSpanElement;\n \"use\": SVGUseElement;\n \"view\": SVGViewElement;\n}\n\n/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */\ninterface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { }\n\ndeclare var Audio: {\n new(src?: string): HTMLAudioElement;\n};\ndeclare var Image: {\n new(width?: number, height?: number): HTMLImageElement;\n};\ndeclare var Option: {\n new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement;\n};\ndeclare var Blob: typeof Blob;\ndeclare var URL: typeof URL;\ndeclare var URLSearchParams: typeof URLSearchParams;\ndeclare var applicationCache: ApplicationCache;\ndeclare var caches: CacheStorage;\ndeclare var clientInformation: Navigator;\ndeclare var closed: boolean;\ndeclare var crypto: Crypto;\ndeclare var customElements: CustomElementRegistry;\ndeclare var defaultStatus: string;\ndeclare var devicePixelRatio: number;\ndeclare var doNotTrack: string;\ndeclare var document: Document;\ndeclare var event: Event | undefined;\n/** @deprecated */\ndeclare var external: External;\ndeclare var frameElement: Element;\ndeclare var frames: Window;\ndeclare var history: History;\ndeclare var innerHeight: number;\ndeclare var innerWidth: number;\ndeclare var isSecureContext: boolean;\ndeclare var length: number;\ndeclare var location: Location;\ndeclare var locationbar: BarProp;\ndeclare var menubar: BarProp;\ndeclare var msContentScript: ExtensionScriptApis;\ndeclare var msCredentials: MSCredentials;\ndeclare const name: never;\ndeclare var navigator: Navigator;\ndeclare var offscreenBuffering: string | boolean;\ndeclare var onabort: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onafterprint: ((this: Window, ev: Event) => any) | null;\ndeclare var onbeforeprint: ((this: Window, ev: Event) => any) | null;\ndeclare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\ndeclare var onblur: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var oncanplay: ((this: Window, ev: Event) => any) | null;\ndeclare var oncanplaythrough: ((this: Window, ev: Event) => any) | null;\ndeclare var onchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\ndeclare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\ndeclare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\ndeclare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\ndeclare var ondrag: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragend: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragenter: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragleave: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragover: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragstart: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondrop: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondurationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onemptied: ((this: Window, ev: Event) => any) | null;\ndeclare var onended: ((this: Window, ev: Event) => any) | null;\ndeclare var onerror: ErrorEventHandler;\ndeclare var onfocus: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\ndeclare var oninput: ((this: Window, ev: Event) => any) | null;\ndeclare var oninvalid: ((this: Window, ev: Event) => any) | null;\ndeclare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onload: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadeddata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadedmetadata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadstart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;\ndeclare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var onmsgesturechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgestureend: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturehold: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturestart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturetap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsinertiastart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointercancel: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerdown: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerenter: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerleave: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointermove: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerout: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerover: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerup: ((this: Window, ev: Event) => any) | null;\ndeclare var onoffline: ((this: Window, ev: Event) => any) | null;\ndeclare var ononline: ((this: Window, ev: Event) => any) | null;\ndeclare var onorientationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpause: ((this: Window, ev: Event) => any) | null;\ndeclare var onplay: ((this: Window, ev: Event) => any) | null;\ndeclare var onplaying: ((this: Window, ev: Event) => any) | null;\ndeclare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\ndeclare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onratechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onreset: ((this: Window, ev: Event) => any) | null;\ndeclare var onresize: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onscroll: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onseeked: ((this: Window, ev: Event) => any) | null;\ndeclare var onseeking: ((this: Window, ev: Event) => any) | null;\ndeclare var onselect: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onstalled: ((this: Window, ev: Event) => any) | null;\ndeclare var onstorage: ((this: Window, ev: StorageEvent) => any) | null;\ndeclare var onsubmit: ((this: Window, ev: Event) => any) | null;\ndeclare var onsuspend: ((this: Window, ev: Event) => any) | null;\ndeclare var ontimeupdate: ((this: Window, ev: Event) => any) | null;\ndeclare var onunload: ((this: Window, ev: Event) => any) | null;\ndeclare var onvolumechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onwaiting: ((this: Window, ev: Event) => any) | null;\ndeclare var opener: any;\ndeclare var orientation: string | number;\ndeclare var outerHeight: number;\ndeclare var outerWidth: number;\ndeclare var pageXOffset: number;\ndeclare var pageYOffset: number;\ndeclare var parent: Window;\ndeclare var performance: Performance;\ndeclare var personalbar: BarProp;\ndeclare var screen: Screen;\ndeclare var screenLeft: number;\ndeclare var screenTop: number;\ndeclare var screenX: number;\ndeclare var screenY: number;\ndeclare var scrollX: number;\ndeclare var scrollY: number;\ndeclare var scrollbars: BarProp;\ndeclare var self: Window;\ndeclare var speechSynthesis: SpeechSynthesis;\ndeclare var status: string;\ndeclare var statusbar: BarProp;\ndeclare var styleMedia: StyleMedia;\ndeclare var toolbar: BarProp;\ndeclare var top: Window;\ndeclare var window: Window;\ndeclare function alert(message?: any): void;\ndeclare function blur(): void;\ndeclare function cancelAnimationFrame(handle: number): void;\n/** @deprecated */\ndeclare function captureEvents(): void;\ndeclare function close(): void;\ndeclare function confirm(message?: string): boolean;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\ndeclare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\ndeclare function focus(): void;\ndeclare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\ndeclare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\ndeclare function getSelection(): Selection;\ndeclare function matchMedia(mediaQuery: string): MediaQueryList;\ndeclare function moveBy(x?: number, y?: number): void;\ndeclare function moveTo(x?: number, y?: number): void;\ndeclare function msWriteProfilerMark(profilerMarkName: string): void;\ndeclare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\ndeclare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\ndeclare function print(): void;\ndeclare function prompt(message?: string, _default?: string): string | null;\n/** @deprecated */\ndeclare function releaseEvents(): void;\ndeclare function requestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function resizeBy(x?: number, y?: number): void;\ndeclare function resizeTo(x?: number, y?: number): void;\ndeclare function scroll(options?: ScrollToOptions): void;\ndeclare function scroll(x?: number, y?: number): void;\ndeclare function scrollBy(options?: ScrollToOptions): void;\ndeclare function scrollBy(x?: number, y?: number): void;\ndeclare function scrollTo(options?: ScrollToOptions): void;\ndeclare function scrollTo(x?: number, y?: number): void;\ndeclare function stop(): void;\ndeclare function webkitCancelAnimationFrame(handle: number): void;\ndeclare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function toString(): string;\ndeclare function dispatchEvent(evt: Event): boolean;\ndeclare function clearInterval(handle?: number): void;\ndeclare function clearTimeout(handle?: number): void;\ndeclare function setInterval(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setInterval(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function clearImmediate(handle: number): void;\ndeclare function setImmediate(handler: (...args: any[]) => void): number;\ndeclare function setImmediate(handler: any, ...args: any[]): number;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare var console: Console;\ndeclare var onanimationcancel: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationend: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationiteration: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationstart: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var ongotpointercapture: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onlostpointercapture: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ontouchcancel: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchend: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchmove: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchstart: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontransitioncancel: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionend: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionrun: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionstart: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var onwheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var indexedDB: IDBFactory;\ndeclare function atob(encodedString: string): string;\ndeclare function btoa(rawString: string): string;\ndeclare function fetch(input?: Request | string, init?: RequestInit): Promise;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\ndeclare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\ndeclare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\ndeclare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\ntype BlobPart = BufferSource | Blob | string;\ntype HeadersInit = Headers | string[][] | Record;\ntype BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string;\ntype RequestInfo = Request | string;\ntype DOMHighResTimeStamp = number;\ntype PerformanceEntryList = PerformanceEntry[];\ntype PushMessageDataInit = BufferSource | string;\ntype VibratePattern = number | number[];\ntype BufferSource = ArrayBufferView | ArrayBuffer;\ntype DOMTimeStamp = number;\ntype FormDataEntryValue = File | string;\ntype ScrollBehavior = \"auto\" | \"instant\" | \"smooth\";\ntype ScrollLogicalPosition = \"start\" | \"center\" | \"end\" | \"nearest\";\ntype MouseWheelEvent = WheelEvent;\ntype ScrollRestoration = \"auto\" | \"manual\";\ntype InsertPosition = \"beforebegin\" | \"afterbegin\" | \"beforeend\" | \"afterend\";\ntype OrientationLockType = \"any\" | \"natural\" | \"portrait\" | \"landscape\" | \"portrait-primary\" | \"portrait-secondary\" | \"landscape-primary\"| \"landscape-secondary\";\ntype IDBValidKey = number | string | Date | BufferSource | IDBArrayKey;\ntype AlgorithmIdentifier = string | Algorithm;\ntype MutationRecordType = \"attributes\" | \"characterData\" | \"childList\";\ntype AAGUID = string;\ntype ByteString = string;\ntype ConstrainBoolean = boolean | ConstrainBooleanParameters;\ntype ConstrainDOMString = string | string[] | ConstrainDOMStringParameters;\ntype ConstrainDouble = number | ConstrainDoubleRange;\ntype ConstrainLong = number | ConstrainLongRange;\ntype CryptoOperationData = ArrayBufferView;\ntype GLbitfield = number;\ntype GLboolean = boolean;\ntype GLbyte = number;\ntype GLclampf = number;\ntype GLenum = number;\ntype GLfloat = number;\ntype GLint = number;\ntype GLintptr = number;\ntype GLshort = number;\ntype GLsizei = number;\ntype GLsizeiptr = number;\ntype GLubyte = number;\ntype GLuint = number;\ntype GLushort = number;\ntype IDBKeyPath = string;\ntype MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload;\ntype MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent;\ntype MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload;\ntype RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete;\ntype RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport;\ntype USVString = string;\ntype payloadtype = number;\ntype MessageEventSource = Window | MessagePort | ServiceWorker;\ntype AnimationPlayState = \"idle\" | \"running\" | \"paused\" | \"finished\";\ntype AppendMode = \"segments\" | \"sequence\";\ntype AudioContextLatencyCategory = \"balanced\" | \"interactive\" | \"playback\";\ntype AudioContextState = \"suspended\" | \"running\" | \"closed\";\ntype AutomationRate = \"a-rate\" | \"k-rate\";\ntype BinaryType = \"blob\" | \"arraybuffer\";\ntype BiquadFilterType = \"lowpass\" | \"highpass\" | \"bandpass\" | \"lowshelf\" | \"highshelf\" | \"peaking\" | \"notch\" | \"allpass\";\ntype CanPlayTypeResult = \"\" | \"maybe\" | \"probably\";\ntype CanvasFillRule = \"nonzero\" | \"evenodd\";\ntype ChannelCountMode = \"max\" | \"clamped-max\" | \"explicit\";\ntype ChannelInterpretation = \"speakers\" | \"discrete\";\ntype ClientTypes = \"window\" | \"worker\" | \"sharedworker\" | \"all\";\ntype CompositeOperation = \"replace\" | \"add\" | \"accumulate\";\ntype DisplayCaptureSurfaceType = \"monitor\" | \"window\" | \"application\" | \"browser\";\ntype DistanceModelType = \"linear\" | \"inverse\" | \"exponential\";\ntype DocumentReadyState = \"loading\" | \"interactive\" | \"complete\";\ntype EndOfStreamError = \"network\" | \"decode\";\ntype ExpandGranularity = \"character\" | \"word\" | \"sentence\" | \"textedit\";\ntype FillMode = \"none\" | \"forwards\" | \"backwards\" | \"both\" | \"auto\";\ntype GamepadHand = \"\" | \"left\" | \"right\";\ntype GamepadHapticActuatorType = \"vibration\";\ntype GamepadInputEmulationType = \"mouse\" | \"keyboard\" | \"gamepad\";\ntype GamepadMappingType = \"\" | \"standard\";\ntype IDBCursorDirection = \"next\" | \"nextunique\" | \"prev\" | \"prevunique\";\ntype IDBRequestReadyState = \"pending\" | \"done\";\ntype IDBTransactionMode = \"readonly\" | \"readwrite\" | \"versionchange\";\ntype IterationCompositeOperation = \"replace\" | \"accumulate\";\ntype KeyFormat = \"raw\" | \"spki\" | \"pkcs8\" | \"jwk\";\ntype KeyType = \"public\" | \"private\" | \"secret\";\ntype KeyUsage = \"encrypt\" | \"decrypt\" | \"sign\" | \"verify\" | \"deriveKey\" | \"deriveBits\" | \"wrapKey\" | \"unwrapKey\";\ntype ListeningState = \"inactive\" | \"active\" | \"disambiguation\";\ntype MSCredentialType = \"FIDO_2_0\";\ntype MSIceAddrType = \"os\" | \"stun\" | \"turn\" | \"peer-derived\";\ntype MSIceType = \"failed\" | \"direct\" | \"relay\";\ntype MSStatsType = \"description\" | \"localclientevent\" | \"inbound-network\" | \"outbound-network\" | \"inbound-payload\" | \"outbound-payload\" | \"transportdiagnostics\";\ntype MSTransportType = \"Embedded\" | \"USB\" | \"NFC\" | \"BT\";\ntype MSWebViewPermissionState = \"unknown\" | \"defer\" | \"allow\" | \"deny\";\ntype MSWebViewPermissionType = \"geolocation\" | \"unlimitedIndexedDBQuota\" | \"media\" | \"pointerlock\" | \"webnotifications\";\ntype MediaDeviceKind = \"audioinput\" | \"audiooutput\" | \"videoinput\";\ntype MediaKeyMessageType = \"license-request\" | \"license-renewal\" | \"license-release\" | \"individualization-request\";\ntype MediaKeySessionType = \"temporary\" | \"persistent-license\" | \"persistent-release-message\";\ntype MediaKeyStatus = \"usable\" | \"expired\" | \"output-downscaled\" | \"output-not-allowed\" | \"status-pending\" | \"internal-error\";\ntype MediaKeysRequirement = \"required\" | \"optional\" | \"not-allowed\";\ntype MediaStreamTrackState = \"live\" | \"ended\";\ntype NavigationReason = \"up\" | \"down\" | \"left\" | \"right\";\ntype NavigationType = \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\";\ntype NotificationDirection = \"auto\" | \"ltr\" | \"rtl\";\ntype NotificationPermission = \"default\" | \"denied\" | \"granted\";\ntype OscillatorType = \"sine\" | \"square\" | \"sawtooth\" | \"triangle\" | \"custom\";\ntype OverSampleType = \"none\" | \"2x\" | \"4x\";\ntype PanningModelType = \"equalpower\" | \"HRTF\";\ntype PaymentComplete = \"success\" | \"fail\" | \"unknown\";\ntype PaymentShippingType = \"shipping\" | \"delivery\" | \"pickup\";\ntype PlaybackDirection = \"normal\" | \"reverse\" | \"alternate\" | \"alternate-reverse\";\ntype PushEncryptionKeyName = \"p256dh\" | \"auth\";\ntype PushPermissionState = \"denied\" | \"granted\" | \"prompt\";\ntype RTCBundlePolicy = \"balanced\" | \"max-compat\" | \"max-bundle\";\ntype RTCDataChannelState = \"connecting\" | \"open\" | \"closing\" | \"closed\";\ntype RTCDegradationPreference = \"maintain-framerate\" | \"maintain-resolution\" | \"balanced\";\ntype RTCDtlsRole = \"auto\" | \"client\" | \"server\";\ntype RTCDtlsTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\" | \"failed\";\ntype RTCDtxStatus = \"disabled\" | \"enabled\";\ntype RTCErrorDetailType = \"data-channel-failure\" | \"dtls-failure\" | \"fingerprint-failure\" | \"idp-bad-script-failure\" | \"idp-execution-failure\" | \"idp-load-failure\" | \"idp-need-login\" | \"idp-timeout\" | \"idp-tls-failure\" | \"idp-token-expired\" | \"idp-token-invalid\" | \"sctp-failure\" | \"sdp-syntax-error\" | \"hardware-encoder-not-available\" | \"hardware-encoder-error\";\ntype RTCIceCandidateType = \"host\" | \"srflx\" | \"prflx\" | \"relay\";\ntype RTCIceComponent = \"rtp\" | \"rtcp\";\ntype RTCIceConnectionState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCIceCredentialType = \"password\" | \"oauth\";\ntype RTCIceGatherPolicy = \"all\" | \"nohost\" | \"relay\";\ntype RTCIceGathererState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceGatheringState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceProtocol = \"udp\" | \"tcp\";\ntype RTCIceRole = \"controlling\" | \"controlled\";\ntype RTCIceTcpCandidateType = \"active\" | \"passive\" | \"so\";\ntype RTCIceTransportPolicy = \"relay\" | \"all\";\ntype RTCIceTransportState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCPeerConnectionState = \"new\" | \"connecting\" | \"connected\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCPriorityType = \"very-low\" | \"low\" | \"medium\" | \"high\";\ntype RTCRtcpMuxPolicy = \"negotiate\" | \"require\";\ntype RTCRtpTransceiverDirection = \"sendrecv\" | \"sendonly\" | \"recvonly\" | \"inactive\";\ntype RTCSctpTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\";\ntype RTCSdpType = \"offer\" | \"pranswer\" | \"answer\" | \"rollback\";\ntype RTCSignalingState = \"stable\" | \"have-local-offer\" | \"have-remote-offer\" | \"have-local-pranswer\" | \"have-remote-pranswer\" | \"closed\";\ntype RTCStatsIceCandidatePairState = \"frozen\" | \"waiting\" | \"inprogress\" | \"failed\" | \"succeeded\" | \"cancelled\";\ntype RTCStatsIceCandidateType = \"host\" | \"serverreflexive\" | \"peerreflexive\" | \"relayed\";\ntype RTCStatsType = \"inboundrtp\" | \"outboundrtp\" | \"session\" | \"datachannel\" | \"track\" | \"transport\" | \"candidatepair\" | \"localcandidate\" | \"remotecandidate\";\ntype ReadyState = \"closed\" | \"open\" | \"ended\";\ntype ReferrerPolicy = \"\" | \"no-referrer\" | \"no-referrer-when-downgrade\" | \"origin-only\" | \"origin-when-cross-origin\" | \"unsafe-url\";\ntype RequestCache = \"default\" | \"no-store\" | \"reload\" | \"no-cache\" | \"force-cache\" | \"only-if-cached\";\ntype RequestCredentials = \"omit\" | \"same-origin\" | \"include\";\ntype RequestDestination = \"\" | \"audio\" | \"audioworklet\" | \"document\" | \"embed\" | \"font\" | \"image\" | \"manifest\" | \"object\" | \"paintworklet\" | \"report\" | \"script\" | \"sharedworker\" | \"style\" | \"track\" | \"video\" | \"worker\" | \"xslt\";\ntype RequestMode = \"navigate\" | \"same-origin\" | \"no-cors\" | \"cors\";\ntype RequestRedirect = \"follow\" | \"error\" | \"manual\";\ntype ResponseType = \"basic\" | \"cors\" | \"default\" | \"error\" | \"opaque\" | \"opaqueredirect\";\ntype ScopedCredentialType = \"ScopedCred\";\ntype SelectionMode = \"select\" | \"start\" | \"end\" | \"preserve\";\ntype ServiceWorkerState = \"installing\" | \"installed\" | \"activating\" | \"activated\" | \"redundant\";\ntype ServiceWorkerUpdateViaCache = \"imports\" | \"all\" | \"none\";\ntype TextTrackKind = \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\ntype TextTrackMode = \"disabled\" | \"hidden\" | \"showing\";\ntype TouchType = \"direct\" | \"stylus\";\ntype Transport = \"usb\" | \"nfc\" | \"ble\";\ntype VRDisplayEventReason = \"mounted\" | \"navigation\" | \"requested\" | \"unmounted\";\ntype VREye = \"left\" | \"right\";\ntype VideoFacingModeEnum = \"user\" | \"environment\" | \"left\" | \"right\";\ntype VisibilityState = \"hidden\" | \"visible\" | \"prerender\" | \"unloaded\";\ntype WorkerType = \"classic\" | \"module\";\ntype XMLHttpRequestResponseType = \"\" | \"arraybuffer\" | \"blob\" | \"document\" | \"json\" | \"text\";\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// DOM Iterable APIs\n/////////////////////////////\n\ninterface AudioParamMap extends ReadonlyMap {\n}\n\ninterface AudioTrackList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface CSSRuleList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface CSSStyleDeclaration {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface ClientRectList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface DOMRectList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface DOMStringList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface DOMTokenList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface DataTransferItemList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface FileList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface FormData {\n [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;\n /**\n * Returns an array of key, value pairs for every entry in the list.\n */\n entries(): IterableIterator<[string, FormDataEntryValue]>;\n /**\n * Returns a list of keys in the list.\n */\n keys(): IterableIterator;\n /**\n * Returns a list of values in the list.\n */\n values(): IterableIterator;\n}\n\ninterface HTMLAllCollection {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface HTMLCollectionBase {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface HTMLCollectionOf {\n [Symbol.iterator](): IterableIterator;\n entries(): IterableIterator<[number, T]>;\n keys(): IterableIterator;\n values(): IterableIterator;\n}\n\ninterface HTMLSelectElement {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface Headers {\n [Symbol.iterator](): IterableIterator<[string, string]>;\n /**\n * Returns an iterator allowing to go through all key/value pairs contained in this object.\n */\n entries(): IterableIterator<[string, string]>;\n /**\n * Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.\n */\n keys(): IterableIterator;\n /**\n * Returns an iterator allowing to go through all values of the key/value pairs contained in this object.\n */\n values(): IterableIterator;\n}\n\ninterface MediaList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface MimeTypeArray {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface NamedNodeMap {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface NodeList {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the list.\n */\n entries(): IterableIterator<[number, Node]>;\n /**\n * Returns an list of keys in the list.\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the list.\n */\n values(): IterableIterator;\n}\n\ninterface NodeListOf {\n [Symbol.iterator](): IterableIterator;\n /**\n * Returns an array of key, value pairs for every entry in the list.\n */\n entries(): IterableIterator<[number, TNode]>;\n /**\n * Returns an list of keys in the list.\n */\n keys(): IterableIterator;\n /**\n * Returns an list of values in the list.\n */\n values(): IterableIterator;\n}\n\ninterface Plugin {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface PluginArray {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface RTCStatsReport extends ReadonlyMap {\n}\n\ninterface SourceBufferList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface StyleSheetList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface TextTrackCueList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface TextTrackList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface TouchList {\n [Symbol.iterator](): IterableIterator;\n}\n\ninterface URLSearchParams {\n [Symbol.iterator](): IterableIterator<[string, string]>;\n /**\n * Returns an array of key, value pairs for every entry in the search params.\n */\n entries(): IterableIterator<[string, string]>;\n /**\n * Returns a list of keys in the search params.\n */\n keys(): IterableIterator;\n /**\n * Returns a list of values in the search params.\n */\n values(): IterableIterator;\n}\n\ninterface VideoTrackList {\n [Symbol.iterator](): IterableIterator;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/////////////////////////////\n/// WorkerGlobalScope APIs\n/////////////////////////////\n// These are only available in a Web Worker\ndeclare function importScripts(...urls: string[]): void;\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n\n/////////////////////////////\n/// Windows Script Host APIS\n/////////////////////////////\n\n\ninterface ActiveXObject {\n new (s: string): any;\n}\ndeclare var ActiveXObject: ActiveXObject;\n\ninterface ITextWriter {\n Write(s: string): void;\n WriteLine(s: string): void;\n Close(): void;\n}\n\ninterface TextStreamBase {\n /**\n * The column number of the current character position in an input stream.\n */\n Column: number;\n\n /**\n * The current line number in an input stream.\n */\n Line: number;\n\n /**\n * Closes a text stream.\n * It is not necessary to close standard streams; they close automatically when the process ends. If\n * you close a standard stream, be aware that any other pointers to that standard stream become invalid.\n */\n Close(): void;\n}\n\ninterface TextStreamWriter extends TextStreamBase {\n /**\n * Sends a string to an output stream.\n */\n Write(s: string): void;\n\n /**\n * Sends a specified number of blank lines (newline characters) to an output stream.\n */\n WriteBlankLines(intLines: number): void;\n\n /**\n * Sends a string followed by a newline character to an output stream.\n */\n WriteLine(s: string): void;\n}\n\ninterface TextStreamReader extends TextStreamBase {\n /**\n * Returns a specified number of characters from an input stream, starting at the current pointer position.\n * Does not return until the ENTER key is pressed.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n Read(characters: number): string;\n\n /**\n * Returns all characters from an input stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadAll(): string;\n\n /**\n * Returns an entire line from an input stream.\n * Although this method extracts the newline character, it does not add it to the returned string.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadLine(): string;\n\n /**\n * Skips a specified number of characters when reading from an input text stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)\n */\n Skip(characters: number): void;\n\n /**\n * Skips the next line when reading from an input text stream.\n * Can only be used on a stream in reading mode, not writing or appending mode.\n */\n SkipLine(): void;\n\n /**\n * Indicates whether the stream pointer position is at the end of a line.\n */\n AtEndOfLine: boolean;\n\n /**\n * Indicates whether the stream pointer position is at the end of a stream.\n */\n AtEndOfStream: boolean;\n}\n\ndeclare var WScript: {\n /**\n * Outputs text to either a message box (under WScript.exe) or the command console window followed by\n * a newline (under CScript.exe).\n */\n Echo(s: any): void;\n\n /**\n * Exposes the write-only error output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdErr: TextStreamWriter;\n\n /**\n * Exposes the write-only output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdOut: TextStreamWriter;\n Arguments: { length: number; Item(n: number): string; };\n\n /**\n * The full path of the currently running script.\n */\n ScriptFullName: string;\n\n /**\n * Forces the script to stop immediately, with an optional exit code.\n */\n Quit(exitCode?: number): number;\n\n /**\n * The Windows Script Host build version number.\n */\n BuildVersion: number;\n\n /**\n * Fully qualified path of the host executable.\n */\n FullName: string;\n\n /**\n * Gets/sets the script mode - interactive(true) or batch(false).\n */\n Interactive: boolean;\n\n /**\n * The name of the host executable (WScript.exe or CScript.exe).\n */\n Name: string;\n\n /**\n * Path of the directory containing the host executable.\n */\n Path: string;\n\n /**\n * The filename of the currently running script.\n */\n ScriptName: string;\n\n /**\n * Exposes the read-only input stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdIn: TextStreamReader;\n\n /**\n * Windows Script Host version\n */\n Version: string;\n\n /**\n * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.\n */\n ConnectObject(objEventSource: any, strPrefix: string): void;\n\n /**\n * Creates a COM object.\n * @param strProgiID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n CreateObject(strProgID: string, strPrefix?: string): any;\n\n /**\n * Disconnects a COM object from its event sources.\n */\n DisconnectObject(obj: any): void;\n\n /**\n * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.\n * @param strPathname Fully qualified path to the file containing the object persisted to disk.\n * For objects in memory, pass a zero-length string.\n * @param strProgID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;\n\n /**\n * Suspends script execution for a specified length of time, then continues execution.\n * @param intTime Interval (in milliseconds) to suspend script execution.\n */\n Sleep(intTime: number): void;\n};\n\n/**\n * WSH is an alias for WScript under Windows Script Host\n */\ndeclare var WSH: typeof WScript;\n\n/**\n * Represents an Automation SAFEARRAY\n */\ndeclare class SafeArray {\n private constructor();\n private SafeArray_typekey: SafeArray;\n}\n\n/**\n * Allows enumerating over a COM collection, which may not have indexed item access.\n */\ninterface Enumerator {\n /**\n * Returns true if the current item is the last one in the collection, or the collection is empty,\n * or the current item is undefined.\n */\n atEnd(): boolean;\n\n /**\n * Returns the current item in the collection\n */\n item(): T;\n\n /**\n * Resets the current item in the collection to the first item. If there are no items in the collection,\n * the current item is set to undefined.\n */\n moveFirst(): void;\n\n /**\n * Moves the current item to the next item in the collection. If the enumerator is at the end of\n * the collection or the collection is empty, the current item is set to undefined.\n */\n moveNext(): void;\n}\n\ninterface EnumeratorConstructor {\n new (safearray: SafeArray): Enumerator;\n new (collection: { Item(index: any): T }): Enumerator;\n new (collection: any): Enumerator;\n}\n\ndeclare var Enumerator: EnumeratorConstructor;\n\n/**\n * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.\n */\ninterface VBArray {\n /**\n * Returns the number of dimensions (1-based).\n */\n dimensions(): number;\n\n /**\n * Takes an index for each dimension in the array, and returns the item at the corresponding location.\n */\n getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;\n\n /**\n * Returns the smallest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n lbound(dimension?: number): number;\n\n /**\n * Returns the largest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n ubound(dimension?: number): number;\n\n /**\n * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,\n * each successive dimension is appended to the end of the array.\n * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]\n */\n toArray(): T[];\n}\n\ninterface VBArrayConstructor {\n new (safeArray: SafeArray): VBArray;\n}\n\ndeclare var VBArray: VBArrayConstructor;\n\n/**\n * Automation date (VT_DATE)\n */\ndeclare class VarDate {\n private constructor();\n private VarDate_typekey: VarDate;\n}\n\ninterface DateConstructor {\n new (vd: VarDate): Date;\n}\n\ninterface Date {\n getVarDate: () => VarDate;\n}\n\n\n"; diff --git a/src/lib/lib-ts.ts b/src/lib/lib-ts.ts index 44505104..8d9399e4 100644 --- a/src/lib/lib-ts.ts +++ b/src/lib/lib-ts.ts @@ -3,4 +3,4 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -export const contents = "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// ECMAScript APIs\n/////////////////////////////\n\ndeclare const NaN: number;\ndeclare const Infinity: number;\n\n/**\n * Evaluates JavaScript code and executes it.\n * @param x A String value that contains valid JavaScript code.\n */\ndeclare function eval(x: string): any;\n\n/**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\ndeclare function parseInt(s: string, radix?: number): number;\n\n/**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\ndeclare function parseFloat(string: string): number;\n\n/**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\n * @param number A numeric value.\n */\ndeclare function isNaN(number: number): boolean;\n\n/**\n * Determines whether a supplied number is finite.\n * @param number Any numeric value.\n */\ndeclare function isFinite(number: number): boolean;\n\n/**\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\n * @param encodedURI A value representing an encoded URI.\n */\ndeclare function decodeURI(encodedURI: string): string;\n\n/**\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\n * @param encodedURIComponent A value representing an encoded URI component.\n */\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\n\n/**\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\n * @param uri A value representing an encoded URI.\n */\ndeclare function encodeURI(uri: string): string;\n\n/**\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\n * @param uriComponent A value representing an encoded URI component.\n */\ndeclare function encodeURIComponent(uriComponent: string): string;\n\n/**\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\n * @param string A string value\n */\ndeclare function escape(string: string): string;\n\n/**\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\n * @param string A string value\n */\ndeclare function unescape(string: string): string;\n\ninterface PropertyDescriptor {\n configurable?: boolean;\n enumerable?: boolean;\n value?: any;\n writable?: boolean;\n get?(): any;\n set?(v: any): void;\n}\n\ninterface PropertyDescriptorMap {\n [s: string]: PropertyDescriptor;\n}\n\ninterface Object {\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\n constructor: Function;\n\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns a date converted to a string using the current locale. */\n toLocaleString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): Object;\n\n /**\n * Determines whether an object has a property with the specified name.\n * @param v A property name.\n */\n hasOwnProperty(v: string): boolean;\n\n /**\n * Determines whether an object exists in another object's prototype chain.\n * @param v Another object whose prototype chain is to be checked.\n */\n isPrototypeOf(v: Object): boolean;\n\n /**\n * Determines whether a specified property is enumerable.\n * @param v A property name.\n */\n propertyIsEnumerable(v: string): boolean;\n}\n\ninterface ObjectConstructor {\n new(value?: any): Object;\n (): any;\n (value: any): any;\n\n /** A reference to the prototype for a class of objects. */\n readonly prototype: Object;\n\n /**\n * Returns the prototype of an object.\n * @param o The object that references the prototype.\n */\n getPrototypeOf(o: any): any;\n\n /**\n * Gets the own property descriptor of the specified object.\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\n * @param o Object that contains the property.\n * @param p Name of the property.\n */\n getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined;\n\n /**\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\n * @param o Object that contains the own properties.\n */\n getOwnPropertyNames(o: any): string[];\n\n /**\n * Creates an object that has the specified prototype or that has null prototype.\n * @param o Object to use as a prototype. May be null.\n */\n create(o: object | null): any;\n\n /**\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\n * @param o Object to use as a prototype. May be null\n * @param properties JavaScript object that contains one or more property descriptors.\n */\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Adds a property to an object, or modifies attributes of an existing property.\n * @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.\n * @param p The property name.\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\n */\n defineProperty(o: any, p: string, attributes: PropertyDescriptor & ThisType): any;\n\n /**\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\n */\n defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n seal(o: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(a: T[]): ReadonlyArray;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(f: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(o: T): Readonly;\n\n /**\n * Prevents the addition of new properties to an object.\n * @param o Object to make non-extensible.\n */\n preventExtensions(o: T): T;\n\n /**\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isSealed(o: any): boolean;\n\n /**\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isFrozen(o: any): boolean;\n\n /**\n * Returns a value that indicates whether new properties can be added to an object.\n * @param o Object to test.\n */\n isExtensible(o: any): boolean;\n\n /**\n * Returns the names of the enumerable properties and methods of an object.\n * @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.\n */\n keys(o: {}): string[];\n}\n\n/**\n * Provides functionality common to all JavaScript objects.\n */\ndeclare const Object: ObjectConstructor;\n\n/**\n * Creates a new function.\n */\ninterface Function {\n /**\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\n * @param thisArg The object to be used as the this object.\n * @param argArray A set of arguments to be passed to the function.\n */\n apply(this: Function, thisArg: any, argArray?: any): any;\n\n /**\n * Calls a method of an object, substituting another object for the current object.\n * @param thisArg The object to be used as the current object.\n * @param argArray A list of arguments to be passed to the method.\n */\n call(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /**\n * For a given function, creates a bound function that has the same body as the original function.\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\n * @param thisArg An object to which the this keyword can refer inside the new function.\n * @param argArray A list of arguments to be passed to the new function.\n */\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /** Returns a string representation of a function. */\n toString(): string;\n\n prototype: any;\n readonly length: number;\n\n // Non-standard extensions\n arguments: any;\n caller: Function;\n}\n\ninterface FunctionConstructor {\n /**\n * Creates a new function.\n * @param args A list of arguments the function accepts.\n */\n new(...args: string[]): Function;\n (...args: string[]): Function;\n readonly prototype: Function;\n}\n\ndeclare const Function: FunctionConstructor;\n\ninterface IArguments {\n [index: number]: any;\n length: number;\n callee: Function;\n}\n\ninterface String {\n /** Returns a string representation of a string. */\n toString(): string;\n\n /**\n * Returns the character at the specified index.\n * @param pos The zero-based index of the desired character.\n */\n charAt(pos: number): string;\n\n /**\n * Returns the Unicode value of the character at the specified location.\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\n */\n charCodeAt(index: number): number;\n\n /**\n * Returns a string that contains the concatenation of two or more strings.\n * @param strings The strings to append to the end of the string.\n */\n concat(...strings: string[]): string;\n\n /**\n * Returns the position of the first occurrence of a substring.\n * @param searchString The substring to search for in the string\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\n */\n indexOf(searchString: string, position?: number): number;\n\n /**\n * Returns the last occurrence of a substring in the string.\n * @param searchString The substring to search for.\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\n */\n lastIndexOf(searchString: string, position?: number): number;\n\n /**\n * Determines whether two strings are equivalent in the current locale.\n * @param that String to compare to target string\n */\n localeCompare(that: string): number;\n\n /**\n * Matches a string with a regular expression, and returns an array containing the results of that search.\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\n */\n match(regexp: string | RegExp): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: string | RegExp, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param regexp The regular expression pattern and applicable flags.\n */\n search(regexp: string | RegExp): number;\n\n /**\n * Returns a section of a string.\n * @param start The index to the beginning of the specified portion of stringObj.\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\n * If this value is not specified, the substring continues to the end of stringObj.\n */\n slice(start?: number, end?: number): string;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(separator: string | RegExp, limit?: number): string[];\n\n /**\n * Returns the substring at the specified location within a String object.\n * @param start The zero-based index number indicating the beginning of the substring.\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\n * If end is omitted, the characters from start through the end of the original string are returned.\n */\n substring(start: number, end?: number): string;\n\n /** Converts all the alphabetic characters in a string to lowercase. */\n toLowerCase(): string;\n\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\n toLocaleLowerCase(): string;\n\n /** Converts all the alphabetic characters in a string to uppercase. */\n toUpperCase(): string;\n\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\n toLocaleUpperCase(): string;\n\n /** Removes the leading and trailing white space and line terminator characters from a string. */\n trim(): string;\n\n /** Returns the length of a String object. */\n readonly length: number;\n\n // IE extensions\n /**\n * Gets a substring beginning at the specified location and having the specified length.\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\n * @param length The number of characters to include in the returned substring.\n */\n substr(from: number, length?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): string;\n\n readonly [index: number]: string;\n}\n\ninterface StringConstructor {\n new(value?: any): String;\n (value?: any): string;\n readonly prototype: String;\n fromCharCode(...codes: number[]): string;\n}\n\n/**\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\n */\ndeclare const String: StringConstructor;\n\ninterface Boolean {\n /** Returns the primitive value of the specified object. */\n valueOf(): boolean;\n}\n\ninterface BooleanConstructor {\n new(value?: any): Boolean;\n (value?: any): boolean;\n readonly prototype: Boolean;\n}\n\ndeclare const Boolean: BooleanConstructor;\n\ninterface Number {\n /**\n * Returns a string representation of an object.\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\n */\n toString(radix?: number): string;\n\n /**\n * Returns a string representing a number in fixed-point notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toFixed(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented in exponential notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toExponential(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\n */\n toPrecision(precision?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): number;\n}\n\ninterface NumberConstructor {\n new(value?: any): Number;\n (value?: any): number;\n readonly prototype: Number;\n\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\n readonly MAX_VALUE: number;\n\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\n readonly MIN_VALUE: number;\n\n /**\n * A value that is not a number.\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\n */\n readonly NaN: number;\n\n /**\n * A value that is less than the largest negative number that can be represented in JavaScript.\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\n */\n readonly NEGATIVE_INFINITY: number;\n\n /**\n * A value greater than the largest number that can be represented in JavaScript.\n * JavaScript displays POSITIVE_INFINITY values as infinity.\n */\n readonly POSITIVE_INFINITY: number;\n}\n\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\ndeclare const Number: NumberConstructor;\n\ninterface TemplateStringsArray extends ReadonlyArray {\n readonly raw: ReadonlyArray;\n}\n\ninterface Math {\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\n readonly E: number;\n /** The natural logarithm of 10. */\n readonly LN10: number;\n /** The natural logarithm of 2. */\n readonly LN2: number;\n /** The base-2 logarithm of e. */\n readonly LOG2E: number;\n /** The base-10 logarithm of e. */\n readonly LOG10E: number;\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\n readonly PI: number;\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\n readonly SQRT1_2: number;\n /** The square root of 2. */\n readonly SQRT2: number;\n /**\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\n * For example, the absolute value of -5 is the same as the absolute value of 5.\n * @param x A numeric expression for which the absolute value is needed.\n */\n abs(x: number): number;\n /**\n * Returns the arc cosine (or inverse cosine) of a number.\n * @param x A numeric expression.\n */\n acos(x: number): number;\n /**\n * Returns the arcsine of a number.\n * @param x A numeric expression.\n */\n asin(x: number): number;\n /**\n * Returns the arctangent of a number.\n * @param x A numeric expression for which the arctangent is needed.\n */\n atan(x: number): number;\n /**\n * Returns the angle (in radians) from the X axis to a point.\n * @param y A numeric expression representing the cartesian y-coordinate.\n * @param x A numeric expression representing the cartesian x-coordinate.\n */\n atan2(y: number, x: number): number;\n /**\n * Returns the smallest integer greater than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n ceil(x: number): number;\n /**\n * Returns the cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cos(x: number): number;\n /**\n * Returns e (the base of natural logarithms) raised to a power.\n * @param x A numeric expression representing the power of e.\n */\n exp(x: number): number;\n /**\n * Returns the greatest integer less than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n floor(x: number): number;\n /**\n * Returns the natural logarithm (base e) of a number.\n * @param x A numeric expression.\n */\n log(x: number): number;\n /**\n * Returns the larger of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n max(...values: number[]): number;\n /**\n * Returns the smaller of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n min(...values: number[]): number;\n /**\n * Returns the value of a base expression taken to a specified power.\n * @param x The base value of the expression.\n * @param y The exponent value of the expression.\n */\n pow(x: number, y: number): number;\n /** Returns a pseudorandom number between 0 and 1. */\n random(): number;\n /**\n * Returns a supplied numeric expression rounded to the nearest number.\n * @param x The value to be rounded to the nearest number.\n */\n round(x: number): number;\n /**\n * Returns the sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sin(x: number): number;\n /**\n * Returns the square root of a number.\n * @param x A numeric expression.\n */\n sqrt(x: number): number;\n /**\n * Returns the tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tan(x: number): number;\n}\n/** An intrinsic object that provides basic mathematics functionality and constants. */\ndeclare const Math: Math;\n\n/** Enables basic storage and retrieval of dates and times. */\ninterface Date {\n /** Returns a string representation of a date. The format of the string depends on the locale. */\n toString(): string;\n /** Returns a date as a string value. */\n toDateString(): string;\n /** Returns a time as a string value. */\n toTimeString(): string;\n /** Returns a value as a string value appropriate to the host environment's current locale. */\n toLocaleString(): string;\n /** Returns a date as a string value appropriate to the host environment's current locale. */\n toLocaleDateString(): string;\n /** Returns a time as a string value appropriate to the host environment's current locale. */\n toLocaleTimeString(): string;\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\n valueOf(): number;\n /** Gets the time value in milliseconds. */\n getTime(): number;\n /** Gets the year, using local time. */\n getFullYear(): number;\n /** Gets the year using Universal Coordinated Time (UTC). */\n getUTCFullYear(): number;\n /** Gets the month, using local time. */\n getMonth(): number;\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\n getUTCMonth(): number;\n /** Gets the day-of-the-month, using local time. */\n getDate(): number;\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\n getUTCDate(): number;\n /** Gets the day of the week, using local time. */\n getDay(): number;\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\n getUTCDay(): number;\n /** Gets the hours in a date, using local time. */\n getHours(): number;\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\n getUTCHours(): number;\n /** Gets the minutes of a Date object, using local time. */\n getMinutes(): number;\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\n getUTCMinutes(): number;\n /** Gets the seconds of a Date object, using local time. */\n getSeconds(): number;\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCSeconds(): number;\n /** Gets the milliseconds of a Date, using local time. */\n getMilliseconds(): number;\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCMilliseconds(): number;\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\n getTimezoneOffset(): number;\n /**\n * Sets the date and time value in the Date object.\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\n */\n setTime(time: number): number;\n /**\n * Sets the milliseconds value in the Date object using local time.\n * @param ms A numeric value equal to the millisecond value.\n */\n setMilliseconds(ms: number): number;\n /**\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\n * @param ms A numeric value equal to the millisecond value.\n */\n setUTCMilliseconds(ms: number): number;\n\n /**\n * Sets the seconds value in the Date object using local time.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setSeconds(sec: number, ms?: number): number;\n /**\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCSeconds(sec: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using local time.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the hour value in the Date object using local time.\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the numeric day-of-the-month value of the Date object using local time.\n * @param date A numeric value equal to the day of the month.\n */\n setDate(date: number): number;\n /**\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\n * @param date A numeric value equal to the day of the month.\n */\n setUTCDate(date: number): number;\n /**\n * Sets the month value in the Date object using local time.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\n */\n setMonth(month: number, date?: number): number;\n /**\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\n */\n setUTCMonth(month: number, date?: number): number;\n /**\n * Sets the year of the Date object using local time.\n * @param year A numeric value for the year.\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\n * @param date A numeric value equal for the day of the month.\n */\n setFullYear(year: number, month?: number, date?: number): number;\n /**\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\n * @param year A numeric value equal to the year.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\n * @param date A numeric value equal to the day of the month.\n */\n setUTCFullYear(year: number, month?: number, date?: number): number;\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\n toUTCString(): string;\n /** Returns a date as a string value in ISO format. */\n toISOString(): string;\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\n toJSON(key?: any): string;\n}\n\ninterface DateConstructor {\n new(): Date;\n new(value: number): Date;\n new(value: string): Date;\n new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;\n (): string;\n readonly prototype: Date;\n /**\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\n * @param s A date string\n */\n parse(s: string): number;\n /**\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\n * @param month The month as an number between 0 and 11 (January to December).\n * @param date The date as an number between 1 and 31.\n * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.\n * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.\n * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.\n * @param ms An number from 0 to 999 that specifies the milliseconds.\n */\n UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;\n now(): number;\n}\n\ndeclare const Date: DateConstructor;\n\ninterface RegExpMatchArray extends Array {\n index?: number;\n input?: string;\n}\n\ninterface RegExpExecArray extends Array {\n index: number;\n input: string;\n}\n\ninterface RegExp {\n /**\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\n * @param string The String object or string literal on which to perform the search.\n */\n exec(string: string): RegExpExecArray | null;\n\n /**\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\n * @param string String on which to perform the search.\n */\n test(string: string): boolean;\n\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\n readonly source: string;\n\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\n readonly global: boolean;\n\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\n readonly ignoreCase: boolean;\n\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\n readonly multiline: boolean;\n\n lastIndex: number;\n\n // Non-standard extensions\n compile(): this;\n}\n\ninterface RegExpConstructor {\n new(pattern: RegExp | string): RegExp;\n new(pattern: string, flags?: string): RegExp;\n (pattern: RegExp | string): RegExp;\n (pattern: string, flags?: string): RegExp;\n readonly prototype: RegExp;\n\n // Non-standard extensions\n $1: string;\n $2: string;\n $3: string;\n $4: string;\n $5: string;\n $6: string;\n $7: string;\n $8: string;\n $9: string;\n lastMatch: string;\n}\n\ndeclare const RegExp: RegExpConstructor;\n\ninterface Error {\n name: string;\n message: string;\n stack?: string;\n}\n\ninterface ErrorConstructor {\n new(message?: string): Error;\n (message?: string): Error;\n readonly prototype: Error;\n}\n\ndeclare const Error: ErrorConstructor;\n\ninterface EvalError extends Error {\n}\n\ninterface EvalErrorConstructor {\n new(message?: string): EvalError;\n (message?: string): EvalError;\n readonly prototype: EvalError;\n}\n\ndeclare const EvalError: EvalErrorConstructor;\n\ninterface RangeError extends Error {\n}\n\ninterface RangeErrorConstructor {\n new(message?: string): RangeError;\n (message?: string): RangeError;\n readonly prototype: RangeError;\n}\n\ndeclare const RangeError: RangeErrorConstructor;\n\ninterface ReferenceError extends Error {\n}\n\ninterface ReferenceErrorConstructor {\n new(message?: string): ReferenceError;\n (message?: string): ReferenceError;\n readonly prototype: ReferenceError;\n}\n\ndeclare const ReferenceError: ReferenceErrorConstructor;\n\ninterface SyntaxError extends Error {\n}\n\ninterface SyntaxErrorConstructor {\n new(message?: string): SyntaxError;\n (message?: string): SyntaxError;\n readonly prototype: SyntaxError;\n}\n\ndeclare const SyntaxError: SyntaxErrorConstructor;\n\ninterface TypeError extends Error {\n}\n\ninterface TypeErrorConstructor {\n new(message?: string): TypeError;\n (message?: string): TypeError;\n readonly prototype: TypeError;\n}\n\ndeclare const TypeError: TypeErrorConstructor;\n\ninterface URIError extends Error {\n}\n\ninterface URIErrorConstructor {\n new(message?: string): URIError;\n (message?: string): URIError;\n readonly prototype: URIError;\n}\n\ndeclare const URIError: URIErrorConstructor;\n\ninterface JSON {\n /**\n * Converts a JavaScript Object Notation (JSON) string into an object.\n * @param text A valid JSON string.\n * @param reviver A function that transforms the results. This function is called for each member of the object.\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\n */\n parse(text: string, reviver?: (key: any, value: any) => any): any;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer A function that transforms the results.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\n}\n\n/**\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\n */\ndeclare const JSON: JSON;\n\n\n/////////////////////////////\n/// ECMAScript Array API (specially handled by compiler)\n/////////////////////////////\n\ninterface ReadonlyArray {\n /**\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n readonly length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n\n readonly [n: number]: T;\n}\n\ninterface ConcatArray {\n readonly length: number;\n readonly [n: number]: T;\n join(separator?: string): string;\n slice(start?: number, end?: number): T[];\n}\n\ninterface Array {\n /**\n * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Appends new elements to an array, and returns the new length of the array.\n * @param items New elements of the Array.\n */\n push(...items: T[]): number;\n /**\n * Removes the last element from an array and returns it.\n */\n pop(): T | undefined;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Reverses the elements in an Array.\n */\n reverse(): T[];\n /**\n * Removes the first element from an array and returns it.\n */\n shift(): T | undefined;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: T, b: T) => number): this;\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n */\n splice(start: number, deleteCount?: number): T[];\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the array in place of the deleted elements.\n */\n splice(start: number, deleteCount: number, ...items: T[]): T[];\n /**\n * Inserts new elements at the start of an array.\n * @param items Elements to insert at the start of the Array.\n */\n unshift(...items: T[]): number;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n\n [n: number]: T;\n}\n\ninterface ArrayConstructor {\n new(arrayLength?: number): any[];\n new (arrayLength: number): T[];\n new (...items: T[]): T[];\n (arrayLength?: number): any[];\n (arrayLength: number): T[];\n (...items: T[]): T[];\n isArray(arg: any): arg is Array;\n readonly prototype: Array;\n}\n\ndeclare const Array: ArrayConstructor;\n\ninterface TypedPropertyDescriptor {\n enumerable?: boolean;\n configurable?: boolean;\n writable?: boolean;\n value?: T;\n get?: () => T;\n set?: (value: T) => void;\n}\n\ndeclare type ClassDecorator = (target: TFunction) => TFunction | void;\ndeclare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;\ndeclare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;\ndeclare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;\n\ndeclare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike;\n\ninterface PromiseLike {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike;\n}\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface Promise {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise;\n\n /**\n * Attaches a callback for only the rejection of the Promise.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of the callback.\n */\n catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise;\n}\n\ninterface ArrayLike {\n readonly length: number;\n readonly [n: number]: T;\n}\n\n/**\n * Make all properties in T optional\n */\ntype Partial = {\n [P in keyof T]?: T[P];\n};\n\n/**\n * Make all properties in T required\n */\ntype Required = {\n [P in keyof T]-?: T[P];\n};\n\n/**\n * Make all properties in T readonly\n */\ntype Readonly = {\n readonly [P in keyof T]: T[P];\n};\n\n/**\n * From T pick a set of properties K\n */\ntype Pick = {\n [P in K]: T[P];\n};\n\n/**\n * Construct a type with a set of properties K of type T\n */\ntype Record = {\n [P in K]: T;\n};\n\n/**\n * Exclude from T those types that are assignable to U\n */\ntype Exclude = T extends U ? never : T;\n\n/**\n * Extract from T those types that are assignable to U\n */\ntype Extract = T extends U ? T : never;\n\n/**\n * Exclude null and undefined from T\n */\ntype NonNullable = T extends null | undefined ? never : T;\n\n/**\n * Obtain the return type of a function type\n */\ntype ReturnType any> = T extends (...args: any[]) => infer R ? R : any;\n\n/**\n * Obtain the return type of a constructor function type\n */\ntype InstanceType any> = T extends new (...args: any[]) => infer R ? R : any;\n\n/**\n * Marker for contextual 'this' type\n */\ninterface ThisType { }\n\n/**\n * Represents a raw buffer of binary data, which is used to store data for the\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\n * but can be passed to a typed array or DataView Object to interpret the raw\n * buffer as needed.\n */\ninterface ArrayBuffer {\n /**\n * Read-only. The length of the ArrayBuffer (in bytes).\n */\n readonly byteLength: number;\n\n /**\n * Returns a section of an ArrayBuffer.\n */\n slice(begin: number, end?: number): ArrayBuffer;\n}\n\n/**\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\n */\ninterface ArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\n\ninterface ArrayBufferConstructor {\n readonly prototype: ArrayBuffer;\n new(byteLength: number): ArrayBuffer;\n isView(arg: any): arg is ArrayBufferView;\n}\ndeclare const ArrayBuffer: ArrayBufferConstructor;\n\ninterface ArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\ninterface DataView {\n readonly buffer: ArrayBuffer;\n readonly byteLength: number;\n readonly byteOffset: number;\n /**\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt8(byteOffset: number): number;\n\n /**\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt16(byteOffset: number, littleEndian?: boolean): number;\n /**\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint8(byteOffset: number): number;\n\n /**\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint16(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Stores an Float32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Float64 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setInt8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Int16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setUint8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Uint16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\n}\n\ninterface DataViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;\n}\ndeclare const DataView: DataViewConstructor;\n\n/**\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Int8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\ninterface Int8ArrayConstructor {\n readonly prototype: Int8Array;\n new(length: number): Int8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n\n\n}\ndeclare const Int8Array: Int8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ArrayConstructor {\n readonly prototype: Uint8Array;\n new(length: number): Uint8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n\n}\ndeclare const Uint8Array: Uint8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\n * If the requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8ClampedArray {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8ClampedArray;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8ClampedArray;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8ClampedArray;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ClampedArrayConstructor {\n readonly prototype: Uint8ClampedArray;\n new(length: number): Uint8ClampedArray;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8ClampedArray;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\ndeclare const Uint8ClampedArray: Uint8ClampedArrayConstructor;\n\n/**\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int16ArrayConstructor {\n readonly prototype: Int16Array;\n new(length: number): Int16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n\n\n}\ndeclare const Int16Array: Int16ArrayConstructor;\n\n/**\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint16ArrayConstructor {\n readonly prototype: Uint16Array;\n new(length: number): Uint16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n\n\n}\ndeclare const Uint16Array: Uint16ArrayConstructor;\n/**\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int32ArrayConstructor {\n readonly prototype: Int32Array;\n new(length: number): Int32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n\n}\ndeclare const Int32Array: Int32ArrayConstructor;\n\n/**\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint32ArrayConstructor {\n readonly prototype: Uint32Array;\n new(length: number): Uint32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n\n}\ndeclare const Uint32Array: Uint32ArrayConstructor;\n\n/**\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\n * of bytes could not be allocated an exception is raised.\n */\ninterface Float32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float32ArrayConstructor {\n readonly prototype: Float32Array;\n new(length: number): Float32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n\n\n}\ndeclare const Float32Array: Float32ArrayConstructor;\n\n/**\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Float64Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float64Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float64Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float64Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float64ArrayConstructor {\n readonly prototype: Float64Array;\n new(length: number): Float64Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n\n}\ndeclare const Float64Array: Float64ArrayConstructor;\n\n/////////////////////////////\n/// ECMAScript Internationalization API\n/////////////////////////////\n\ndeclare namespace Intl {\n interface CollatorOptions {\n usage?: string;\n localeMatcher?: string;\n numeric?: boolean;\n caseFirst?: string;\n sensitivity?: string;\n ignorePunctuation?: boolean;\n }\n\n interface ResolvedCollatorOptions {\n locale: string;\n usage: string;\n sensitivity: string;\n ignorePunctuation: boolean;\n collation: string;\n caseFirst: string;\n numeric: boolean;\n }\n\n interface Collator {\n compare(x: string, y: string): number;\n resolvedOptions(): ResolvedCollatorOptions;\n }\n var Collator: {\n new(locales?: string | string[], options?: CollatorOptions): Collator;\n (locales?: string | string[], options?: CollatorOptions): Collator;\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\n };\n\n interface NumberFormatOptions {\n localeMatcher?: string;\n style?: string;\n currency?: string;\n currencyDisplay?: string;\n useGrouping?: boolean;\n minimumIntegerDigits?: number;\n minimumFractionDigits?: number;\n maximumFractionDigits?: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n }\n\n interface ResolvedNumberFormatOptions {\n locale: string;\n numberingSystem: string;\n style: string;\n currency?: string;\n currencyDisplay?: string;\n minimumIntegerDigits: number;\n minimumFractionDigits: number;\n maximumFractionDigits: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n useGrouping: boolean;\n }\n\n interface NumberFormat {\n format(value: number): string;\n resolvedOptions(): ResolvedNumberFormatOptions;\n }\n var NumberFormat: {\n new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\n };\n\n interface DateTimeFormatOptions {\n localeMatcher?: string;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n formatMatcher?: string;\n hour12?: boolean;\n timeZone?: string;\n }\n\n interface ResolvedDateTimeFormatOptions {\n locale: string;\n calendar: string;\n numberingSystem: string;\n timeZone: string;\n hour12?: boolean;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n }\n\n interface DateTimeFormat {\n format(date?: Date | number): string;\n resolvedOptions(): ResolvedDateTimeFormatOptions;\n }\n var DateTimeFormat: {\n new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\n };\n}\n\ninterface String {\n /**\n * Determines whether two strings are equivalent in the current or specified locale.\n * @param that String to compare to target string\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\n */\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\n}\n\ninterface Number {\n /**\n * Converts a number to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\n}\n\ninterface Date {\n /**\n * Converts a date and time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n /**\n * Converts a date to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n\n /**\n * Converts a time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n}\n\n\n/////////////////////////////\n/// DOM APIs\n/////////////////////////////\n\ninterface Account {\n displayName: string;\n id: string;\n imageURL?: string;\n name?: string;\n rpDisplayName: string;\n}\n\ninterface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\ninterface AesCbcParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface AesCtrParams extends Algorithm {\n counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n length: number;\n}\n\ninterface AesDerivedKeyParams extends Algorithm {\n length: number;\n}\n\ninterface AesGcmParams extends Algorithm {\n additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n tagLength?: number;\n}\n\ninterface AesKeyAlgorithm extends KeyAlgorithm {\n length: number;\n}\n\ninterface AesKeyGenParams extends Algorithm {\n length: number;\n}\n\ninterface Algorithm {\n name: string;\n}\n\ninterface AnalyserOptions extends AudioNodeOptions {\n fftSize?: number;\n maxDecibels?: number;\n minDecibels?: number;\n smoothingTimeConstant?: number;\n}\n\ninterface AnimationEventInit extends EventInit {\n animationName?: string;\n elapsedTime?: number;\n}\n\ninterface AssertionOptions {\n allowList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface AudioBufferOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface AudioBufferSourceOptions {\n buffer?: AudioBuffer | null;\n detune?: number;\n loop?: boolean;\n loopEnd?: number;\n loopStart?: number;\n playbackRate?: number;\n}\n\ninterface AudioContextInfo {\n currentTime?: number;\n sampleRate?: number;\n}\n\ninterface AudioContextOptions {\n latencyHint?: AudioContextLatencyCategory | number;\n sampleRate?: number;\n}\n\ninterface AudioNodeOptions {\n channelCount?: number;\n channelCountMode?: ChannelCountMode;\n channelInterpretation?: ChannelInterpretation;\n}\n\ninterface AudioParamDescriptor {\n defaultValue?: number;\n maxValue?: number;\n minValue?: number;\n name?: string;\n}\n\ninterface AudioProcessingEventInit extends EventInit {\n inputBuffer: AudioBuffer;\n outputBuffer: AudioBuffer;\n playbackTime: number;\n}\n\ninterface AudioTimestamp {\n contextTime?: number;\n performanceTime?: number;\n}\n\ninterface BiquadFilterOptions extends AudioNodeOptions {\n Q?: number;\n detune?: number;\n frequency?: number;\n gain?: number;\n type?: BiquadFilterType;\n}\n\ninterface ByteLengthChunk {\n byteLength?: number;\n}\n\ninterface CacheQueryOptions {\n cacheName?: string;\n ignoreMethod?: boolean;\n ignoreSearch?: boolean;\n ignoreVary?: boolean;\n}\n\ninterface ChannelMergerOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n}\n\ninterface ChannelSplitterOptions extends AudioNodeOptions {\n numberOfOutputs?: number;\n}\n\ninterface ClientData {\n challenge: string;\n extensions?: WebAuthnExtensions;\n hashAlg: string | Algorithm;\n origin: string;\n rpId: string;\n tokenBinding?: string;\n}\n\ninterface ClientQueryOptions {\n includeReserved?: boolean;\n includeUncontrolled?: boolean;\n type?: ClientTypes;\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number;\n reason?: string;\n wasClean?: boolean;\n}\n\ninterface CompositionEventInit extends UIEventInit {\n data?: string;\n}\n\ninterface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface ConstantSourceOptions {\n offset?: number;\n}\n\ninterface ConstrainBooleanParameters {\n exact?: boolean;\n ideal?: boolean;\n}\n\ninterface ConstrainDOMStringParameters {\n exact?: string | string[];\n ideal?: string | string[];\n}\n\ninterface ConstrainDoubleRange extends DoubleRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainLongRange extends LongRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainVideoFacingModeParameters {\n exact?: VideoFacingModeEnum | VideoFacingModeEnum[];\n ideal?: VideoFacingModeEnum | VideoFacingModeEnum[];\n}\n\ninterface ConvolverOptions extends AudioNodeOptions {\n buffer?: AudioBuffer | null;\n disableNormalization?: boolean;\n}\n\ninterface CustomEventInit extends EventInit {\n detail?: T;\n}\n\ninterface DOMRectInit {\n height?: number;\n width?: number;\n x?: number;\n y?: number;\n}\n\ninterface DelayOptions extends AudioNodeOptions {\n delayTime?: number;\n maxDelayTime?: number;\n}\n\ninterface DeviceAccelerationDict {\n x?: number | null;\n y?: number | null;\n z?: number | null;\n}\n\ninterface DeviceLightEventInit extends EventInit {\n value?: number;\n}\n\ninterface DeviceMotionEventInit extends EventInit {\n acceleration?: DeviceAccelerationDict | null;\n accelerationIncludingGravity?: DeviceAccelerationDict | null;\n interval?: number | null;\n rotationRate?: DeviceRotationRateDict | null;\n}\n\ninterface DeviceOrientationEventInit extends EventInit {\n absolute?: boolean;\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DeviceRotationRateDict {\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DoubleRange {\n max?: number;\n min?: number;\n}\n\ninterface DynamicsCompressorOptions extends AudioNodeOptions {\n attack?: number;\n knee?: number;\n ratio?: number;\n release?: number;\n threshold?: number;\n}\n\ninterface EcKeyAlgorithm extends KeyAlgorithm {\n namedCurve: string;\n}\n\ninterface EcKeyGenParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcKeyImportParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcdhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface EcdsaParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface ErrorEventInit extends EventInit {\n colno?: number;\n error?: any;\n filename?: string;\n lineno?: number;\n message?: string;\n}\n\ninterface EventInit {\n bubbles?: boolean;\n cancelable?: boolean;\n scoped?: boolean;\n}\n\ninterface EventListenerOptions {\n capture?: boolean;\n}\n\ninterface EventModifierInit extends UIEventInit {\n altKey?: boolean;\n ctrlKey?: boolean;\n metaKey?: boolean;\n modifierAltGraph?: boolean;\n modifierCapsLock?: boolean;\n modifierFn?: boolean;\n modifierFnLock?: boolean;\n modifierHyper?: boolean;\n modifierNumLock?: boolean;\n modifierOS?: boolean;\n modifierScrollLock?: boolean;\n modifierSuper?: boolean;\n modifierSymbol?: boolean;\n modifierSymbolLock?: boolean;\n shiftKey?: boolean;\n}\n\ninterface ExceptionInformation {\n domain?: string | null;\n}\n\ninterface ExtendableEventInit extends EventInit {\n}\n\ninterface ExtendableMessageEventInit extends ExtendableEventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: object | ServiceWorker | MessagePort | null;\n}\n\ninterface FetchEventInit extends ExtendableEventInit {\n clientId?: string;\n request: Request;\n reservedClientId?: string;\n targetClientId?: string;\n}\n\ninterface FocusEventInit extends UIEventInit {\n relatedTarget?: EventTarget | null;\n}\n\ninterface FocusNavigationEventInit extends EventInit {\n navigationReason?: string | null;\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface FocusNavigationOrigin {\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface GainOptions extends AudioNodeOptions {\n gain?: number;\n}\n\ninterface GamepadEventInit extends EventInit {\n gamepad?: Gamepad;\n}\n\ninterface GetNotificationOptions {\n tag?: string;\n}\n\ninterface HashChangeEventInit extends EventInit {\n newURL?: string;\n oldURL?: string;\n}\n\ninterface HkdfParams extends Algorithm {\n hash: string | Algorithm;\n info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface HmacImportParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface HmacKeyAlgorithm extends KeyAlgorithm {\n hash: KeyAlgorithm;\n length: number;\n}\n\ninterface HmacKeyGenParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface IDBIndexParameters {\n multiEntry?: boolean;\n unique?: boolean;\n}\n\ninterface IDBObjectStoreParameters {\n autoIncrement?: boolean;\n keyPath?: string | string[];\n}\n\ninterface IIRFilterOptions extends AudioNodeOptions {\n feedback: number[];\n feedforward: number[];\n}\n\ninterface IntersectionObserverEntryInit {\n boundingClientRect: DOMRectInit;\n intersectionRect: DOMRectInit;\n isIntersecting: boolean;\n rootBounds: DOMRectInit;\n target: Element;\n time: number;\n}\n\ninterface IntersectionObserverInit {\n root?: Element | null;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\ninterface JsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\ninterface KeyAlgorithm {\n name: string;\n}\n\ninterface KeyboardEventInit extends EventModifierInit {\n code?: string;\n key?: string;\n location?: number;\n repeat?: boolean;\n}\n\ninterface LongRange {\n max?: number;\n min?: number;\n}\n\ninterface MSAccountInfo {\n accountImageUri?: string;\n accountName?: string;\n rpDisplayName: string;\n userDisplayName: string;\n userId?: string;\n}\n\ninterface MSAudioLocalClientEvent extends MSLocalClientEventBase {\n cpuInsufficientEventRatio?: number;\n deviceCaptureNotFunctioningEventRatio?: number;\n deviceClippingEventRatio?: number;\n deviceEchoEventRatio?: number;\n deviceGlitchesEventRatio?: number;\n deviceHalfDuplexAECEventRatio?: number;\n deviceHowlingEventCount?: number;\n deviceLowSNREventRatio?: number;\n deviceLowSpeechLevelEventRatio?: number;\n deviceMultipleEndpointsEventCount?: number;\n deviceNearEndToEchoRatioEventRatio?: number;\n deviceRenderMuteEventRatio?: number;\n deviceRenderNotFunctioningEventRatio?: number;\n deviceRenderZeroVolumeEventRatio?: number;\n networkDelayEventRatio?: number;\n networkSendQualityEventRatio?: number;\n}\n\ninterface MSAudioRecvPayload extends MSPayloadBase {\n burstLossLength1?: number;\n burstLossLength2?: number;\n burstLossLength3?: number;\n burstLossLength4?: number;\n burstLossLength5?: number;\n burstLossLength6?: number;\n burstLossLength7?: number;\n burstLossLength8OrHigher?: number;\n fecRecvDistance1?: number;\n fecRecvDistance2?: number;\n fecRecvDistance3?: number;\n packetReorderDepthAvg?: number;\n packetReorderDepthMax?: number;\n packetReorderRatio?: number;\n ratioCompressedSamplesAvg?: number;\n ratioConcealedSamplesAvg?: number;\n ratioStretchedSamplesAvg?: number;\n samplingRate?: number;\n signal?: MSAudioRecvSignal;\n}\n\ninterface MSAudioRecvSignal {\n initialSignalLevelRMS?: number;\n recvNoiseLevelCh1?: number;\n recvSignalLevelCh1?: number;\n renderLoopbackSignalLevel?: number;\n renderNoiseLevel?: number;\n renderSignalLevel?: number;\n}\n\ninterface MSAudioSendPayload extends MSPayloadBase {\n audioFECUsed?: boolean;\n samplingRate?: number;\n sendMutePercent?: number;\n signal?: MSAudioSendSignal;\n}\n\ninterface MSAudioSendSignal {\n noiseLevel?: number;\n sendNoiseLevelCh1?: number;\n sendSignalLevelCh1?: number;\n}\n\ninterface MSConnectivity {\n iceType?: MSIceType;\n iceWarningFlags?: MSIceWarningFlags;\n relayAddress?: MSRelayAddress;\n}\n\ninterface MSCredentialFilter {\n accept?: MSCredentialSpec[];\n}\n\ninterface MSCredentialParameters {\n type?: MSCredentialType;\n}\n\ninterface MSCredentialSpec {\n id?: string;\n type: MSCredentialType;\n}\n\ninterface MSDCCEventInit extends EventInit {\n maxFr?: number;\n maxFs?: number;\n}\n\ninterface MSDSHEventInit extends EventInit {\n sources?: number[];\n timestamp?: number;\n}\n\ninterface MSDelay {\n roundTrip?: number;\n roundTripMax?: number;\n}\n\ninterface MSDescription extends RTCStats {\n connectivity?: MSConnectivity;\n deviceDevName?: string;\n localAddr?: MSIPAddressInfo;\n networkconnectivity?: MSNetworkConnectivityInfo;\n reflexiveLocalIPAddr?: MSIPAddressInfo;\n remoteAddr?: MSIPAddressInfo;\n transport?: RTCIceProtocol;\n}\n\ninterface MSFIDOCredentialParameters extends MSCredentialParameters {\n algorithm?: string | Algorithm;\n authenticators?: string[];\n}\n\ninterface MSIPAddressInfo {\n ipAddr?: string;\n manufacturerMacAddrMask?: string;\n port?: number;\n}\n\ninterface MSIceWarningFlags {\n allocationMessageIntegrityFailed?: boolean;\n alternateServerReceived?: boolean;\n connCheckMessageIntegrityFailed?: boolean;\n connCheckOtherError?: boolean;\n fipsAllocationFailure?: boolean;\n multipleRelayServersAttempted?: boolean;\n noRelayServersConfigured?: boolean;\n portRangeExhausted?: boolean;\n pseudoTLSFailure?: boolean;\n tcpNatConnectivityFailed?: boolean;\n tcpRelayConnectivityFailed?: boolean;\n turnAuthUnknownUsernameError?: boolean;\n turnTcpAllocateFailed?: boolean;\n turnTcpSendFailed?: boolean;\n turnTcpTimedOut?: boolean;\n turnTurnTcpConnectivityFailed?: boolean;\n turnUdpAllocateFailed?: boolean;\n turnUdpSendFailed?: boolean;\n udpLocalConnectivityFailed?: boolean;\n udpNatConnectivityFailed?: boolean;\n udpRelayConnectivityFailed?: boolean;\n useCandidateChecksFailed?: boolean;\n}\n\ninterface MSJitter {\n interArrival?: number;\n interArrivalMax?: number;\n interArrivalSD?: number;\n}\n\ninterface MSLocalClientEventBase extends RTCStats {\n networkBandwidthLowEventRatio?: number;\n networkReceiveQualityEventRatio?: number;\n}\n\ninterface MSNetwork extends RTCStats {\n delay?: MSDelay;\n jitter?: MSJitter;\n packetLoss?: MSPacketLoss;\n utilization?: MSUtilization;\n}\n\ninterface MSNetworkConnectivityInfo {\n linkspeed?: number;\n networkConnectionDetails?: string;\n vpn?: boolean;\n}\n\ninterface MSNetworkInterfaceType {\n interfaceTypeEthernet?: boolean;\n interfaceTypePPP?: boolean;\n interfaceTypeTunnel?: boolean;\n interfaceTypeWWAN?: boolean;\n interfaceTypeWireless?: boolean;\n}\n\ninterface MSOutboundNetwork extends MSNetwork {\n appliedBandwidthLimit?: number;\n}\n\ninterface MSPacketLoss {\n lossRate?: number;\n lossRateMax?: number;\n}\n\ninterface MSPayloadBase extends RTCStats {\n payloadDescription?: string;\n}\n\ninterface MSPortRange {\n max?: number;\n min?: number;\n}\n\ninterface MSRelayAddress {\n port?: number;\n relayAddress?: string;\n}\n\ninterface MSSignatureParameters {\n userPrompt?: string;\n}\n\ninterface MSTransportDiagnosticsStats extends RTCStats {\n allocationTimeInMs?: number;\n baseAddress?: string;\n baseInterface?: MSNetworkInterfaceType;\n iceRole?: RTCIceRole;\n iceWarningFlags?: MSIceWarningFlags;\n interfaces?: MSNetworkInterfaceType;\n localAddrType?: MSIceAddrType;\n localAddress?: string;\n localInterface?: MSNetworkInterfaceType;\n localMR?: string;\n localMRTCPPort?: number;\n localSite?: string;\n msRtcEngineVersion?: string;\n networkName?: string;\n numConsentReqReceived?: number;\n numConsentReqSent?: number;\n numConsentRespReceived?: number;\n numConsentRespSent?: number;\n portRangeMax?: number;\n portRangeMin?: number;\n protocol?: RTCIceProtocol;\n remoteAddrType?: MSIceAddrType;\n remoteAddress?: string;\n remoteMR?: string;\n remoteMRTCPPort?: number;\n remoteSite?: string;\n rtpRtcpMux?: boolean;\n stunVer?: number;\n}\n\ninterface MSUtilization {\n bandwidthEstimation?: number;\n bandwidthEstimationAvg?: number;\n bandwidthEstimationMax?: number;\n bandwidthEstimationMin?: number;\n bandwidthEstimationStdDev?: number;\n packets?: number;\n}\n\ninterface MSVideoPayload extends MSPayloadBase {\n durationSeconds?: number;\n resolution?: string;\n videoBitRateAvg?: number;\n videoBitRateMax?: number;\n videoFrameRateAvg?: number;\n videoPacketLossRate?: number;\n}\n\ninterface MSVideoRecvPayload extends MSVideoPayload {\n lowBitRateCallPercent?: number;\n lowFrameRateCallPercent?: number;\n recvBitRateAverage?: number;\n recvBitRateMaximum?: number;\n recvCodecType?: string;\n recvFpsHarmonicAverage?: number;\n recvFrameRateAverage?: number;\n recvNumResSwitches?: number;\n recvReorderBufferMaxSuccessfullyOrderedExtent?: number;\n recvReorderBufferMaxSuccessfullyOrderedLateTime?: number;\n recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number;\n recvReorderBufferPacketsDroppedDueToTimeout?: number;\n recvReorderBufferReorderedPackets?: number;\n recvResolutionHeight?: number;\n recvResolutionWidth?: number;\n recvVideoStreamsMax?: number;\n recvVideoStreamsMin?: number;\n recvVideoStreamsMode?: number;\n reorderBufferTotalPackets?: number;\n videoFrameLossRate?: number;\n videoPostFECPLR?: number;\n videoResolutions?: MSVideoResolutionDistribution;\n}\n\ninterface MSVideoResolutionDistribution {\n cifQuality?: number;\n h1080Quality?: number;\n h1440Quality?: number;\n h2160Quality?: number;\n h720Quality?: number;\n vgaQuality?: number;\n}\n\ninterface MSVideoSendPayload extends MSVideoPayload {\n sendBitRateAverage?: number;\n sendBitRateMaximum?: number;\n sendFrameRateAverage?: number;\n sendResolutionHeight?: number;\n sendResolutionWidth?: number;\n sendVideoStreamsMax?: number;\n}\n\ninterface MediaElementAudioSourceOptions {\n mediaElement: HTMLMediaElement;\n}\n\ninterface MediaEncryptedEventInit extends EventInit {\n initData?: ArrayBuffer | null;\n initDataType?: string;\n}\n\ninterface MediaKeyMessageEventInit extends EventInit {\n message?: ArrayBuffer | null;\n messageType?: MediaKeyMessageType;\n}\n\ninterface MediaKeySystemConfiguration {\n audioCapabilities?: MediaKeySystemMediaCapability[];\n distinctiveIdentifier?: MediaKeysRequirement;\n initDataTypes?: string[];\n persistentState?: MediaKeysRequirement;\n videoCapabilities?: MediaKeySystemMediaCapability[];\n}\n\ninterface MediaKeySystemMediaCapability {\n contentType?: string;\n robustness?: string;\n}\n\ninterface MediaStreamConstraints {\n audio?: boolean | MediaTrackConstraints;\n video?: boolean | MediaTrackConstraints;\n}\n\ninterface MediaStreamErrorEventInit extends EventInit {\n error?: MediaStreamError | null;\n}\n\ninterface MediaStreamEventInit extends EventInit {\n stream?: MediaStream;\n}\n\ninterface MediaStreamTrackEventInit extends EventInit {\n track?: MediaStreamTrack | null;\n}\n\ninterface MediaTrackCapabilities {\n aspectRatio?: number | DoubleRange;\n deviceId?: string;\n echoCancellation?: boolean[];\n facingMode?: string;\n frameRate?: number | DoubleRange;\n groupId?: string;\n height?: number | LongRange;\n sampleRate?: number | LongRange;\n sampleSize?: number | LongRange;\n volume?: number | DoubleRange;\n width?: number | LongRange;\n}\n\ninterface MediaTrackConstraintSet {\n aspectRatio?: number | ConstrainDoubleRange;\n channelCount?: number | ConstrainLongRange;\n deviceId?: string | string[] | ConstrainDOMStringParameters;\n displaySurface?: string | string[] | ConstrainDOMStringParameters;\n echoCancellation?: boolean | ConstrainBooleanParameters;\n facingMode?: string | string[] | ConstrainDOMStringParameters;\n frameRate?: number | ConstrainDoubleRange;\n groupId?: string | string[] | ConstrainDOMStringParameters;\n height?: number | ConstrainLongRange;\n latency?: number | ConstrainDoubleRange;\n logicalSurface?: boolean | ConstrainBooleanParameters;\n sampleRate?: number | ConstrainLongRange;\n sampleSize?: number | ConstrainLongRange;\n volume?: number | ConstrainDoubleRange;\n width?: number | ConstrainLongRange;\n}\n\ninterface MediaTrackConstraints extends MediaTrackConstraintSet {\n advanced?: MediaTrackConstraintSet[];\n}\n\ninterface MediaTrackSettings {\n aspectRatio?: number;\n deviceId?: string;\n echoCancellation?: boolean;\n facingMode?: string;\n frameRate?: number;\n groupId?: string;\n height?: number;\n sampleRate?: number;\n sampleSize?: number;\n volume?: number;\n width?: number;\n}\n\ninterface MediaTrackSupportedConstraints {\n aspectRatio?: boolean;\n deviceId?: boolean;\n echoCancellation?: boolean;\n facingMode?: boolean;\n frameRate?: boolean;\n groupId?: boolean;\n height?: boolean;\n sampleRate?: boolean;\n sampleSize?: boolean;\n volume?: boolean;\n width?: boolean;\n}\n\ninterface MessageEventInit extends EventInit {\n channel?: string;\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: Window | null;\n}\n\ninterface MouseEventInit extends EventModifierInit {\n button?: number;\n buttons?: number;\n clientX?: number;\n clientY?: number;\n relatedTarget?: EventTarget | null;\n screenX?: number;\n screenY?: number;\n}\n\ninterface MsZoomToOptions {\n animate?: string;\n contentX?: number;\n contentY?: number;\n scaleFactor?: number;\n viewportX?: string | null;\n viewportY?: string | null;\n}\n\ninterface MutationObserverInit {\n attributeFilter?: string[];\n attributeOldValue?: boolean;\n attributes?: boolean;\n characterData?: boolean;\n characterDataOldValue?: boolean;\n childList?: boolean;\n subtree?: boolean;\n}\n\ninterface NotificationEventInit extends ExtendableEventInit {\n action?: string;\n notification: Notification;\n}\n\ninterface NotificationOptions {\n body?: string;\n data?: any;\n dir?: NotificationDirection;\n icon?: string;\n lang?: string;\n tag?: string;\n}\n\ninterface ObjectURLOptions {\n oneTimeOnly?: boolean;\n}\n\ninterface OfflineAudioCompletionEventInit extends EventInit {\n renderedBuffer: AudioBuffer;\n}\n\ninterface OscillatorOptions extends AudioNodeOptions {\n detune?: number;\n frequency?: number;\n periodicWave?: PeriodicWave;\n type?: OscillatorType;\n}\n\ninterface PannerOptions extends AudioNodeOptions {\n coneInnerAngle?: number;\n coneOuterAngle?: number;\n coneOuterGain?: number;\n distanceModel?: DistanceModelType;\n maxDistance?: number;\n orientationX?: number;\n orientationY?: number;\n orientationZ?: number;\n panningModel?: PanningModelType;\n positionX?: number;\n positionY?: number;\n positionZ?: number;\n refDistance?: number;\n rolloffFactor?: number;\n}\n\ninterface PaymentCurrencyAmount {\n currency: string;\n currencySystem?: string;\n value: string;\n}\n\ninterface PaymentDetailsBase {\n displayItems?: PaymentItem[];\n modifiers?: PaymentDetailsModifier[];\n shippingOptions?: PaymentShippingOption[];\n}\n\ninterface PaymentDetailsInit extends PaymentDetailsBase {\n id?: string;\n total: PaymentItem;\n}\n\ninterface PaymentDetailsModifier {\n additionalDisplayItems?: PaymentItem[];\n data?: any;\n supportedMethods: string | string[];\n total?: PaymentItem;\n}\n\ninterface PaymentDetailsUpdate extends PaymentDetailsBase {\n error?: string;\n total?: PaymentItem;\n}\n\ninterface PaymentItem {\n amount: PaymentCurrencyAmount;\n label: string;\n pending?: boolean;\n}\n\ninterface PaymentMethodData {\n data?: any;\n supportedMethods: string | string[];\n}\n\ninterface PaymentOptions {\n requestPayerEmail?: boolean;\n requestPayerName?: boolean;\n requestPayerPhone?: boolean;\n requestShipping?: boolean;\n shippingType?: string;\n}\n\ninterface PaymentRequestUpdateEventInit extends EventInit {\n}\n\ninterface PaymentShippingOption {\n amount: PaymentCurrencyAmount;\n id: string;\n label: string;\n selected?: boolean;\n}\n\ninterface Pbkdf2Params extends Algorithm {\n hash: string | Algorithm;\n iterations: number;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface PeriodicWaveConstraints {\n disableNormalization?: boolean;\n}\n\ninterface PeriodicWaveOptions extends PeriodicWaveConstraints {\n imag?: number[];\n real?: number[];\n}\n\ninterface PointerEventInit extends MouseEventInit {\n height?: number;\n isPrimary?: boolean;\n pointerId?: number;\n pointerType?: string;\n pressure?: number;\n tiltX?: number;\n tiltY?: number;\n width?: number;\n}\n\ninterface PopStateEventInit extends EventInit {\n state?: any;\n}\n\ninterface PositionOptions {\n enableHighAccuracy?: boolean;\n maximumAge?: number;\n timeout?: number;\n}\n\ninterface ProgressEventInit extends EventInit {\n lengthComputable?: boolean;\n loaded?: number;\n total?: number;\n}\n\ninterface PushEventInit extends ExtendableEventInit {\n data?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null;\n}\n\ninterface PushSubscriptionChangeInit extends ExtendableEventInit {\n newSubscription?: PushSubscription;\n oldSubscription?: PushSubscription;\n}\n\ninterface PushSubscriptionOptionsInit {\n applicationServerKey?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | string | null;\n userVisibleOnly?: boolean;\n}\n\ninterface QueuingStrategy {\n highWaterMark?: number;\n size?: WritableStreamChunkCallback;\n}\n\ninterface RTCConfiguration {\n bundlePolicy?: RTCBundlePolicy;\n iceServers?: RTCIceServer[];\n iceTransportPolicy?: RTCIceTransportPolicy;\n peerIdentity?: string;\n}\n\ninterface RTCDTMFToneChangeEventInit extends EventInit {\n tone?: string;\n}\n\ninterface RTCDtlsFingerprint {\n algorithm?: string;\n value?: string;\n}\n\ninterface RTCDtlsParameters {\n fingerprints?: RTCDtlsFingerprint[];\n role?: RTCDtlsRole;\n}\n\ninterface RTCIceCandidateAttributes extends RTCStats {\n addressSourceUrl?: string;\n candidateType?: RTCStatsIceCandidateType;\n ipAddress?: string;\n portNumber?: number;\n priority?: number;\n transport?: string;\n}\n\ninterface RTCIceCandidateComplete {\n}\n\ninterface RTCIceCandidateDictionary {\n foundation?: string;\n ip?: string;\n msMTurnSessionId?: string;\n port?: number;\n priority?: number;\n protocol?: RTCIceProtocol;\n relatedAddress?: string;\n relatedPort?: number;\n tcpType?: RTCIceTcpCandidateType;\n type?: RTCIceCandidateType;\n}\n\ninterface RTCIceCandidateInit {\n candidate?: string;\n sdpMLineIndex?: number;\n sdpMid?: string;\n}\n\ninterface RTCIceCandidatePair {\n local?: RTCIceCandidateDictionary;\n remote?: RTCIceCandidateDictionary;\n}\n\ninterface RTCIceCandidatePairStats extends RTCStats {\n availableIncomingBitrate?: number;\n availableOutgoingBitrate?: number;\n bytesReceived?: number;\n bytesSent?: number;\n localCandidateId?: string;\n nominated?: boolean;\n priority?: number;\n readable?: boolean;\n remoteCandidateId?: string;\n roundTripTime?: number;\n state?: RTCStatsIceCandidatePairState;\n transportId?: string;\n writable?: boolean;\n}\n\ninterface RTCIceGatherOptions {\n gatherPolicy?: RTCIceGatherPolicy;\n iceservers?: RTCIceServer[];\n portRange?: MSPortRange;\n}\n\ninterface RTCIceParameters {\n iceLite?: boolean | null;\n password?: string;\n usernameFragment?: string;\n}\n\ninterface RTCIceServer {\n credential?: string | null;\n urls?: any;\n username?: string | null;\n}\n\ninterface RTCInboundRTPStreamStats extends RTCRTPStreamStats {\n bytesReceived?: number;\n fractionLost?: number;\n jitter?: number;\n packetsLost?: number;\n packetsReceived?: number;\n}\n\ninterface RTCMediaStreamTrackStats extends RTCStats {\n audioLevel?: number;\n echoReturnLoss?: number;\n echoReturnLossEnhancement?: number;\n frameHeight?: number;\n frameWidth?: number;\n framesCorrupted?: number;\n framesDecoded?: number;\n framesDropped?: number;\n framesPerSecond?: number;\n framesReceived?: number;\n framesSent?: number;\n remoteSource?: boolean;\n ssrcIds?: string[];\n trackIdentifier?: string;\n}\n\ninterface RTCOfferOptions {\n iceRestart?: boolean;\n offerToReceiveAudio?: number;\n offerToReceiveVideo?: number;\n voiceActivityDetection?: boolean;\n}\n\ninterface RTCOutboundRTPStreamStats extends RTCRTPStreamStats {\n bytesSent?: number;\n packetsSent?: number;\n roundTripTime?: number;\n targetBitrate?: number;\n}\n\ninterface RTCPeerConnectionIceEventInit extends EventInit {\n candidate?: RTCIceCandidate;\n}\n\ninterface RTCRTPStreamStats extends RTCStats {\n associateStatsId?: string;\n codecId?: string;\n firCount?: number;\n isRemote?: boolean;\n mediaTrackId?: string;\n mediaType?: string;\n nackCount?: number;\n pliCount?: number;\n sliCount?: number;\n ssrc?: string;\n transportId?: string;\n}\n\ninterface RTCRtcpFeedback {\n parameter?: string;\n type?: string;\n}\n\ninterface RTCRtcpParameters {\n cname?: string;\n mux?: boolean;\n reducedSize?: boolean;\n ssrc?: number;\n}\n\ninterface RTCRtpCapabilities {\n codecs?: RTCRtpCodecCapability[];\n fecMechanisms?: string[];\n headerExtensions?: RTCRtpHeaderExtension[];\n}\n\ninterface RTCRtpCodecCapability {\n clockRate?: number;\n kind?: string;\n maxSpatialLayers?: number;\n maxTemporalLayers?: number;\n maxptime?: number;\n name?: string;\n numChannels?: number;\n options?: any;\n parameters?: any;\n preferredPayloadType?: number;\n ptime?: number;\n rtcpFeedback?: RTCRtcpFeedback[];\n svcMultiStreamSupport?: boolean;\n}\n\ninterface RTCRtpCodecParameters {\n clockRate?: number;\n maxptime?: number;\n name?: string;\n numChannels?: number;\n parameters?: any;\n payloadType?: number;\n ptime?: number;\n rtcpFeedback?: RTCRtcpFeedback[];\n}\n\ninterface RTCRtpContributingSource {\n audioLevel?: number;\n csrc?: number;\n timestamp?: number;\n}\n\ninterface RTCRtpEncodingParameters {\n active?: boolean;\n codecPayloadType?: number;\n dependencyEncodingIds?: string[];\n encodingId?: string;\n fec?: RTCRtpFecParameters;\n framerateScale?: number;\n maxBitrate?: number;\n maxFramerate?: number;\n minQuality?: number;\n priority?: number;\n resolutionScale?: number;\n rtx?: RTCRtpRtxParameters;\n ssrc?: number;\n ssrcRange?: RTCSsrcRange;\n}\n\ninterface RTCRtpFecParameters {\n mechanism?: string;\n ssrc?: number;\n}\n\ninterface RTCRtpHeaderExtension {\n kind?: string;\n preferredEncrypt?: boolean;\n preferredId?: number;\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionParameters {\n encrypt?: boolean;\n id?: number;\n uri?: string;\n}\n\ninterface RTCRtpParameters {\n codecs?: RTCRtpCodecParameters[];\n degradationPreference?: RTCDegradationPreference;\n encodings?: RTCRtpEncodingParameters[];\n headerExtensions?: RTCRtpHeaderExtensionParameters[];\n muxId?: string;\n rtcp?: RTCRtcpParameters;\n}\n\ninterface RTCRtpRtxParameters {\n ssrc?: number;\n}\n\ninterface RTCRtpUnhandled {\n muxId?: string;\n payloadType?: number;\n ssrc?: number;\n}\n\ninterface RTCSessionDescriptionInit {\n sdp?: string;\n type?: RTCSdpType;\n}\n\ninterface RTCSrtpKeyParam {\n keyMethod?: string;\n keySalt?: string;\n lifetime?: string;\n mkiLength?: number;\n mkiValue?: number;\n}\n\ninterface RTCSrtpSdesParameters {\n cryptoSuite?: string;\n keyParams?: RTCSrtpKeyParam[];\n sessionParams?: string[];\n tag?: number;\n}\n\ninterface RTCSsrcRange {\n max?: number;\n min?: number;\n}\n\ninterface RTCStats {\n id?: string;\n msType?: MSStatsType;\n timestamp?: number;\n type?: RTCStatsType;\n}\n\ninterface RTCStatsReport {\n}\n\ninterface RTCTransportStats extends RTCStats {\n activeConnection?: boolean;\n bytesReceived?: number;\n bytesSent?: number;\n localCertificateId?: string;\n remoteCertificateId?: string;\n rtcpTransportStatsId?: string;\n selectedCandidatePairId?: string;\n}\n\ninterface RegistrationOptions {\n scope?: string;\n}\n\ninterface RequestInit {\n body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null;\n cache?: RequestCache;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n integrity?: string;\n keepalive?: boolean;\n method?: string;\n mode?: RequestMode;\n redirect?: RequestRedirect;\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n signal?: AbortSignal;\n window?: any;\n}\n\ninterface ResponseInit {\n headers?: HeadersInit;\n status?: number;\n statusText?: string;\n}\n\ninterface RsaHashedImportParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {\n hash: KeyAlgorithm;\n}\n\ninterface RsaHashedKeyGenParams extends RsaKeyGenParams {\n hash: string | Algorithm;\n}\n\ninterface RsaKeyAlgorithm extends KeyAlgorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaKeyGenParams extends Algorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaOaepParams extends Algorithm {\n label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n}\n\ninterface RsaOtherPrimesInfo {\n d?: string;\n r?: string;\n t?: string;\n}\n\ninterface RsaPssParams extends Algorithm {\n saltLength: number;\n}\n\ninterface ScopedCredentialDescriptor {\n id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n transports?: Transport[];\n type: ScopedCredentialType;\n}\n\ninterface ScopedCredentialOptions {\n excludeList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface ScopedCredentialParameters {\n algorithm: string | Algorithm;\n type: ScopedCredentialType;\n}\n\ninterface SecurityPolicyViolationEventInit extends EventInit {\n blockedURI?: string;\n columnNumber?: number;\n documentURI?: string;\n effectiveDirective?: string;\n lineNumber?: number;\n originalPolicy?: string;\n referrer?: string;\n sourceFile?: string;\n statusCode?: number;\n violatedDirective?: string;\n}\n\ninterface ServiceWorkerMessageEventInit extends EventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: ServiceWorker | MessagePort | null;\n}\n\ninterface SpeechSynthesisEventInit extends EventInit {\n charIndex?: number;\n charLength?: number;\n elapsedTime?: number;\n name?: string;\n utterance?: SpeechSynthesisUtterance | null;\n}\n\ninterface StereoPannerOptions extends AudioNodeOptions {\n pan?: number;\n}\n\ninterface StoreExceptionsInformation extends ExceptionInformation {\n detailURI?: string | null;\n explanationString?: string | null;\n siteName?: string | null;\n}\n\ninterface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface SyncEventInit extends ExtendableEventInit {\n lastChance?: boolean;\n tag: string;\n}\n\ninterface TextDecodeOptions {\n stream?: boolean;\n}\n\ninterface TextDecoderOptions {\n fatal?: boolean;\n ignoreBOM?: boolean;\n}\n\ninterface TrackEventInit extends EventInit {\n track?: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ninterface TransitionEventInit extends EventInit {\n elapsedTime?: number;\n propertyName?: string;\n}\n\ninterface UIEventInit extends EventInit {\n detail?: number;\n view?: Window | null;\n}\n\ninterface UnderlyingSink {\n abort?: WritableStreamErrorCallback;\n close?: WritableStreamDefaultControllerCallback;\n start: WritableStreamDefaultControllerCallback;\n write?: WritableStreamChunkCallback;\n}\n\ninterface VRDisplayEventInit extends EventInit {\n display: VRDisplay;\n reason?: VRDisplayEventReason;\n}\n\ninterface VRLayer {\n leftBounds?: number[] | null;\n rightBounds?: number[] | null;\n source?: HTMLCanvasElement | null;\n}\n\ninterface VRStageParameters {\n sittingToStandingTransform?: Float32Array;\n sizeX?: number;\n sizeY?: number;\n}\n\ninterface WaveShaperOptions extends AudioNodeOptions {\n curve?: number[];\n oversample?: OverSampleType;\n}\n\ninterface WebAuthnExtensions {\n}\n\ninterface WebGLContextAttributes {\n alpha?: boolean;\n antialias?: boolean;\n depth?: boolean;\n failIfMajorPerformanceCaveat?: boolean;\n premultipliedAlpha?: boolean;\n preserveDrawingBuffer?: boolean;\n stencil?: boolean;\n}\n\ninterface WebGLContextEventInit extends EventInit {\n statusMessage?: string;\n}\n\ninterface WheelEventInit extends MouseEventInit {\n deltaMode?: number;\n deltaX?: number;\n deltaY?: number;\n deltaZ?: number;\n}\n\ninterface EventListener {\n (evt: Event): void;\n}\n\ntype WebKitEntriesCallback = ((entries: WebKitEntry[]) => void) | { handleEvent(entries: WebKitEntry[]): void; };\n\ntype WebKitErrorCallback = ((err: DOMError) => void) | { handleEvent(err: DOMError): void; };\n\ntype WebKitFileCallback = ((file: File) => void) | { handleEvent(file: File): void; };\n\ninterface ANGLE_instanced_arrays {\n drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void;\n drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void;\n vertexAttribDivisorANGLE(index: number, divisor: number): void;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n}\n\ndeclare var ANGLE_instanced_arrays: {\n prototype: ANGLE_instanced_arrays;\n new(): ANGLE_instanced_arrays;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n};\n\ninterface AbortController {\n readonly signal: AbortSignal;\n abort(): void;\n}\n\ndeclare var AbortController: {\n prototype: AbortController;\n new(): AbortController;\n};\n\ninterface AbortSignalEventMap {\n \"abort\": ProgressEvent;\n}\n\ninterface AbortSignal extends EventTarget {\n readonly aborted: boolean;\n onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AbortSignal: {\n prototype: AbortSignal;\n new(): AbortSignal;\n};\n\ninterface AbstractWorkerEventMap {\n \"error\": ErrorEvent;\n}\n\ninterface AbstractWorker {\n onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AesCfbParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCmacParams extends Algorithm {\n length: number;\n}\n\ninterface AnalyserNode extends AudioNode {\n fftSize: number;\n readonly frequencyBinCount: number;\n maxDecibels: number;\n minDecibels: number;\n smoothingTimeConstant: number;\n getByteFrequencyData(array: Uint8Array): void;\n getByteTimeDomainData(array: Uint8Array): void;\n getFloatFrequencyData(array: Float32Array): void;\n getFloatTimeDomainData(array: Float32Array): void;\n}\n\ndeclare var AnalyserNode: {\n prototype: AnalyserNode;\n new(): AnalyserNode;\n};\n\ninterface Animation {\n currentTime: number | null;\n effect: AnimationEffectReadOnly;\n readonly finished: Promise;\n id: string;\n readonly pending: boolean;\n readonly playState: \"idle\" | \"running\" | \"paused\" | \"finished\";\n playbackRate: number;\n readonly ready: Promise;\n startTime: number;\n timeline: AnimationTimeline;\n cancel(): void;\n finish(): void;\n oncancel: (this: Animation, ev: AnimationPlaybackEvent) => any;\n onfinish: (this: Animation, ev: AnimationPlaybackEvent) => any;\n pause(): void;\n play(): void;\n reverse(): void;\n}\n\ndeclare var Animation: {\n prototype: Animation;\n new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation;\n};\n\ninterface AnimationEffectReadOnly {\n readonly timing: number;\n getComputedTiming(): ComputedTimingProperties;\n}\n\ninterface AnimationEvent extends Event {\n readonly animationName: string;\n readonly elapsedTime: number;\n}\n\ndeclare var AnimationEvent: {\n prototype: AnimationEvent;\n new(typeArg: string, eventInitDict?: AnimationEventInit): AnimationEvent;\n};\n\ninterface AnimationKeyFrame {\n easing?: string | string[];\n offset?: number | null | (number | null)[];\n [index: string]: string | number | number[] | string[] | null | (number | null)[] | undefined;\n}\n\ninterface AnimationOptions {\n delay?: number;\n direction?: \"normal\" | \"reverse\" | \"alternate\" | \"alternate-reverse\";\n duration?: number;\n easing?: string;\n endDelay?: number;\n fill?: \"none\" | \"forwards\" | \"backwards\" | \"both\"| \"auto\";\n id?: string;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface AnimationPlaybackEvent extends Event {\n readonly currentTime: number | null;\n readonly timelineTime: number | null;\n}\n\ndeclare var AnimationPlaybackEvent: {\n prototype: AnimationPlaybackEvent;\n new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent;\n};\n\ninterface AnimationPlaybackEventInit extends EventInit {\n currentTime?: number | null;\n timelineTime?: number | null;\n}\n\ninterface AnimationTimeline {\n readonly currentTime: number | null;\n}\n\ninterface ApplicationCacheEventMap {\n \"cached\": Event;\n \"checking\": Event;\n \"downloading\": Event;\n \"error\": Event;\n \"noupdate\": Event;\n \"obsolete\": Event;\n \"progress\": ProgressEvent;\n \"updateready\": Event;\n}\n\ninterface ApplicationCache extends EventTarget {\n oncached: ((this: ApplicationCache, ev: Event) => any) | null;\n onchecking: ((this: ApplicationCache, ev: Event) => any) | null;\n ondownloading: ((this: ApplicationCache, ev: Event) => any) | null;\n onerror: ((this: ApplicationCache, ev: Event) => any) | null;\n onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null;\n onobsolete: ((this: ApplicationCache, ev: Event) => any) | null;\n onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null;\n onupdateready: ((this: ApplicationCache, ev: Event) => any) | null;\n readonly status: number;\n abort(): void;\n swapCache(): void;\n update(): void;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ApplicationCache: {\n prototype: ApplicationCache;\n new(): ApplicationCache;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n};\n\ninterface AssignedNodesOptions {\n flatten?: boolean;\n}\n\ninterface Attr extends Node {\n readonly name: string;\n readonly ownerElement: Element | null;\n readonly prefix: string | null;\n readonly specified: boolean;\n value: string;\n}\n\ndeclare var Attr: {\n prototype: Attr;\n new(): Attr;\n};\n\ninterface AudioBuffer {\n readonly duration: number;\n readonly length: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n getChannelData(channel: number): Float32Array;\n}\n\ndeclare var AudioBuffer: {\n prototype: AudioBuffer;\n new(): AudioBuffer;\n};\n\ninterface AudioBufferSourceNodeEventMap {\n \"ended\": Event;\n}\n\ninterface AudioBufferSourceNode extends AudioNode {\n buffer: AudioBuffer | null;\n readonly detune: AudioParam;\n loop: boolean;\n loopEnd: number;\n loopStart: number;\n onended: ((this: AudioBufferSourceNode, ev: Event) => any) | null;\n readonly playbackRate: AudioParam;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioBufferSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioBufferSourceNode: {\n prototype: AudioBufferSourceNode;\n new(): AudioBufferSourceNode;\n};\n\ninterface AudioContextEventMap {\n \"statechange\": Event;\n}\n\ninterface AudioContextBase extends EventTarget {\n readonly currentTime: number;\n readonly destination: AudioDestinationNode;\n readonly listener: AudioListener;\n onstatechange: ((this: AudioContext, ev: Event) => any) | null;\n readonly sampleRate: number;\n readonly state: AudioContextState;\n close(): Promise;\n createAnalyser(): AnalyserNode;\n createBiquadFilter(): BiquadFilterNode;\n createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;\n createBufferSource(): AudioBufferSourceNode;\n createChannelMerger(numberOfInputs?: number): ChannelMergerNode;\n createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode;\n createConvolver(): ConvolverNode;\n createDelay(maxDelayTime?: number): DelayNode;\n createDynamicsCompressor(): DynamicsCompressorNode;\n createGain(): GainNode;\n createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode;\n createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;\n createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode;\n createOscillator(): OscillatorNode;\n createPanner(): PannerNode;\n createPeriodicWave(real: Float32Array, imag: Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave;\n createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;\n createStereoPanner(): StereoPannerNode;\n createWaveShaper(): WaveShaperNode;\n decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise;\n resume(): Promise;\n addEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioContext, ev: AudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AudioContext extends AudioContextBase {\n suspend(): Promise;\n}\n\ndeclare var AudioContext: {\n prototype: AudioContext;\n new(): AudioContext;\n};\n\ninterface AudioDestinationNode extends AudioNode {\n readonly maxChannelCount: number;\n}\n\ndeclare var AudioDestinationNode: {\n prototype: AudioDestinationNode;\n new(): AudioDestinationNode;\n};\n\ninterface AudioListener {\n /** @deprecated */\n dopplerFactor: number;\n /** @deprecated */\n speedOfSound: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n /** @deprecated */\n setVelocity(x: number, y: number, z: number): void;\n}\n\ndeclare var AudioListener: {\n prototype: AudioListener;\n new(): AudioListener;\n};\n\ninterface AudioNode extends EventTarget {\n channelCount: number;\n channelCountMode: ChannelCountMode;\n channelInterpretation: ChannelInterpretation;\n readonly context: AudioContext;\n readonly numberOfInputs: number;\n readonly numberOfOutputs: number;\n connect(destination: AudioNode, output?: number, input?: number): AudioNode;\n connect(destination: AudioParam, output?: number): void;\n disconnect(): void;\n disconnect(output: number): void;\n disconnect(destination: AudioNode): void;\n disconnect(destination: AudioNode, output: number): void;\n disconnect(destination: AudioNode, output: number, input: number): void;\n disconnect(destination: AudioParam): void;\n disconnect(destination: AudioParam, output: number): void;\n}\n\ndeclare var AudioNode: {\n prototype: AudioNode;\n new(): AudioNode;\n};\n\ninterface AudioParam {\n readonly defaultValue: number;\n value: number;\n cancelScheduledValues(cancelTime: number): AudioParam;\n exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;\n linearRampToValueAtTime(value: number, endTime: number): AudioParam;\n setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam;\n setValueAtTime(value: number, startTime: number): AudioParam;\n setValueCurveAtTime(values: number[], startTime: number, duration: number): AudioParam;\n}\n\ndeclare var AudioParam: {\n prototype: AudioParam;\n new(): AudioParam;\n};\n\ninterface AudioProcessingEvent extends Event {\n readonly inputBuffer: AudioBuffer;\n readonly outputBuffer: AudioBuffer;\n readonly playbackTime: number;\n}\n\ndeclare var AudioProcessingEvent: {\n prototype: AudioProcessingEvent;\n new(): AudioProcessingEvent;\n};\n\ninterface AudioTrack {\n enabled: boolean;\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var AudioTrack: {\n prototype: AudioTrack;\n new(): AudioTrack;\n};\n\ninterface AudioTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface AudioTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: AudioTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n getTrackById(id: string): AudioTrack | null;\n item(index: number): AudioTrack;\n addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: AudioTrack;\n}\n\ndeclare var AudioTrackList: {\n prototype: AudioTrackList;\n new(): AudioTrackList;\n};\n\ninterface BarProp {\n readonly visible: boolean;\n}\n\ndeclare var BarProp: {\n prototype: BarProp;\n new(): BarProp;\n};\n\ninterface BeforeUnloadEvent extends Event {\n returnValue: any;\n}\n\ndeclare var BeforeUnloadEvent: {\n prototype: BeforeUnloadEvent;\n new(): BeforeUnloadEvent;\n};\n\ninterface BhxBrowser {\n readonly lastError: DOMException;\n checkMatchesGlobExpression(pattern: string, value: string): boolean;\n checkMatchesUriExpression(pattern: string, value: string): boolean;\n clearLastError(): void;\n currentWindowId(): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n getExtensionId(): string;\n getThisAddress(): any;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericListenerHandler(eventHandler: Function): void;\n setLastError(parameters: string): void;\n webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void;\n}\n\ndeclare var BhxBrowser: {\n prototype: BhxBrowser;\n new(): BhxBrowser;\n};\n\ninterface BiquadFilterNode extends AudioNode {\n readonly Q: AudioParam;\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n readonly gain: AudioParam;\n type: BiquadFilterType;\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var BiquadFilterNode: {\n prototype: BiquadFilterNode;\n new(): BiquadFilterNode;\n};\n\ninterface Blob {\n readonly size: number;\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n slice(start?: number, end?: number, contentType?: string): Blob;\n}\n\ndeclare var Blob: {\n prototype: Blob;\n new (blobParts?: any[], options?: BlobPropertyBag): Blob;\n};\n\ninterface BlobPropertyBag {\n endings?: string;\n type?: string;\n}\n\ninterface Body {\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise;\n blob(): Promise;\n formData(): Promise;\n json(): Promise;\n text(): Promise;\n}\n\ninterface BroadcastChannel extends EventTarget {\n readonly name: string;\n onmessage: (ev: MessageEvent) => any;\n onmessageerror: (ev: MessageEvent) => any;\n addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n close(): void;\n postMessage(message: any): void;\n removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BroadcastChannel: {\n prototype: BroadcastChannel;\n new(name: string): BroadcastChannel;\n};\n\ninterface BroadcastChannelEventMap {\n message: MessageEvent;\n messageerror: MessageEvent;\n}\n\ninterface ByteLengthQueuingStrategy {\n highWaterMark: number;\n size(chunk?: any): number;\n}\n\ndeclare var ByteLengthQueuingStrategy: {\n prototype: ByteLengthQueuingStrategy;\n new(strategy: QueuingStrategy): ByteLengthQueuingStrategy;\n};\n\ninterface CDATASection extends Text {\n}\n\ndeclare var CDATASection: {\n prototype: CDATASection;\n new(): CDATASection;\n};\n\ninterface CSS {\n escape(value: string): string;\n supports(property: string, value?: string): boolean;\n}\ndeclare var CSS: CSS;\n\ninterface CSSConditionRule extends CSSGroupingRule {\n conditionText: string;\n}\n\ndeclare var CSSConditionRule: {\n prototype: CSSConditionRule;\n new(): CSSConditionRule;\n};\n\ninterface CSSFontFaceRule extends CSSRule {\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSFontFaceRule: {\n prototype: CSSFontFaceRule;\n new(): CSSFontFaceRule;\n};\n\ninterface CSSGroupingRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n deleteRule(index: number): void;\n insertRule(rule: string, index: number): number;\n}\n\ndeclare var CSSGroupingRule: {\n prototype: CSSGroupingRule;\n new(): CSSGroupingRule;\n};\n\ninterface CSSImportRule extends CSSRule {\n readonly href: string;\n readonly media: MediaList;\n readonly styleSheet: CSSStyleSheet;\n}\n\ndeclare var CSSImportRule: {\n prototype: CSSImportRule;\n new(): CSSImportRule;\n};\n\ninterface CSSKeyframeRule extends CSSRule {\n keyText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSKeyframeRule: {\n prototype: CSSKeyframeRule;\n new(): CSSKeyframeRule;\n};\n\ninterface CSSKeyframesRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n name: string;\n appendRule(rule: string): void;\n deleteRule(rule: string): void;\n findRule(rule: string): CSSKeyframeRule | null;\n}\n\ndeclare var CSSKeyframesRule: {\n prototype: CSSKeyframesRule;\n new(): CSSKeyframesRule;\n};\n\ninterface CSSMediaRule extends CSSConditionRule {\n readonly media: MediaList;\n}\n\ndeclare var CSSMediaRule: {\n prototype: CSSMediaRule;\n new(): CSSMediaRule;\n};\n\ninterface CSSNamespaceRule extends CSSRule {\n readonly namespaceURI: string;\n readonly prefix: string;\n}\n\ndeclare var CSSNamespaceRule: {\n prototype: CSSNamespaceRule;\n new(): CSSNamespaceRule;\n};\n\ninterface CSSPageRule extends CSSRule {\n readonly pseudoClass: string;\n readonly selector: string;\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSPageRule: {\n prototype: CSSPageRule;\n new(): CSSPageRule;\n};\n\ninterface CSSRule {\n cssText: string;\n readonly parentRule: CSSRule | null;\n readonly parentStyleSheet: CSSStyleSheet | null;\n readonly type: number;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n}\n\ndeclare var CSSRule: {\n prototype: CSSRule;\n new(): CSSRule;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n};\n\ninterface CSSRuleList {\n readonly length: number;\n item(index: number): CSSRule | null;\n [index: number]: CSSRule;\n}\n\ndeclare var CSSRuleList: {\n prototype: CSSRuleList;\n new(): CSSRuleList;\n};\n\ninterface CSSStyleDeclaration {\n alignContent: string | null;\n alignItems: string | null;\n alignSelf: string | null;\n alignmentBaseline: string | null;\n animation: string | null;\n animationDelay: string | null;\n animationDirection: string | null;\n animationDuration: string | null;\n animationFillMode: string | null;\n animationIterationCount: string | null;\n animationName: string | null;\n animationPlayState: string | null;\n animationTimingFunction: string | null;\n backfaceVisibility: string | null;\n background: string | null;\n backgroundAttachment: string | null;\n backgroundClip: string | null;\n backgroundColor: string | null;\n backgroundImage: string | null;\n backgroundOrigin: string | null;\n backgroundPosition: string | null;\n backgroundPositionX: string | null;\n backgroundPositionY: string | null;\n backgroundRepeat: string | null;\n backgroundSize: string | null;\n baselineShift: string | null;\n border: string | null;\n borderBottom: string | null;\n borderBottomColor: string | null;\n borderBottomLeftRadius: string | null;\n borderBottomRightRadius: string | null;\n borderBottomStyle: string | null;\n borderBottomWidth: string | null;\n borderCollapse: string | null;\n borderColor: string | null;\n borderImage: string | null;\n borderImageOutset: string | null;\n borderImageRepeat: string | null;\n borderImageSlice: string | null;\n borderImageSource: string | null;\n borderImageWidth: string | null;\n borderLeft: string | null;\n borderLeftColor: string | null;\n borderLeftStyle: string | null;\n borderLeftWidth: string | null;\n borderRadius: string | null;\n borderRight: string | null;\n borderRightColor: string | null;\n borderRightStyle: string | null;\n borderRightWidth: string | null;\n borderSpacing: string | null;\n borderStyle: string | null;\n borderTop: string | null;\n borderTopColor: string | null;\n borderTopLeftRadius: string | null;\n borderTopRightRadius: string | null;\n borderTopStyle: string | null;\n borderTopWidth: string | null;\n borderWidth: string | null;\n bottom: string | null;\n boxShadow: string | null;\n boxSizing: string | null;\n breakAfter: string | null;\n breakBefore: string | null;\n breakInside: string | null;\n captionSide: string | null;\n clear: string | null;\n clip: string | null;\n clipPath: string | null;\n clipRule: string | null;\n color: string | null;\n colorInterpolationFilters: string | null;\n columnCount: any;\n columnFill: string | null;\n columnGap: any;\n columnRule: string | null;\n columnRuleColor: any;\n columnRuleStyle: string | null;\n columnRuleWidth: any;\n columnSpan: string | null;\n columnWidth: any;\n columns: string | null;\n content: string | null;\n counterIncrement: string | null;\n counterReset: string | null;\n cssFloat: string | null;\n cssText: string;\n cursor: string | null;\n direction: string | null;\n display: string | null;\n dominantBaseline: string | null;\n emptyCells: string | null;\n enableBackground: string | null;\n fill: string | null;\n fillOpacity: string | null;\n fillRule: string | null;\n filter: string | null;\n flex: string | null;\n flexBasis: string | null;\n flexDirection: string | null;\n flexFlow: string | null;\n flexGrow: string | null;\n flexShrink: string | null;\n flexWrap: string | null;\n floodColor: string | null;\n floodOpacity: string | null;\n font: string | null;\n fontFamily: string | null;\n fontFeatureSettings: string | null;\n fontSize: string | null;\n fontSizeAdjust: string | null;\n fontStretch: string | null;\n fontStyle: string | null;\n fontVariant: string | null;\n fontWeight: string | null;\n gap: string | null;\n glyphOrientationHorizontal: string | null;\n glyphOrientationVertical: string | null;\n grid: string | null;\n gridArea: string | null;\n gridAutoColumns: string | null;\n gridAutoFlow: string | null;\n gridAutoRows: string | null;\n gridColumn: string | null;\n gridColumnEnd: string | null;\n gridColumnGap: string | null;\n gridColumnStart: string | null;\n gridGap: string | null;\n gridRow: string | null;\n gridRowEnd: string | null;\n gridRowGap: string | null;\n gridRowStart: string | null;\n gridTemplate: string | null;\n gridTemplateAreas: string | null;\n gridTemplateColumns: string | null;\n gridTemplateRows: string | null;\n height: string | null;\n imeMode: string | null;\n justifyContent: string | null;\n justifyItems: string | null;\n justifySelf: string | null;\n kerning: string | null;\n layoutGrid: string | null;\n layoutGridChar: string | null;\n layoutGridLine: string | null;\n layoutGridMode: string | null;\n layoutGridType: string | null;\n left: string | null;\n readonly length: number;\n letterSpacing: string | null;\n lightingColor: string | null;\n lineBreak: string | null;\n lineHeight: string | null;\n listStyle: string | null;\n listStyleImage: string | null;\n listStylePosition: string | null;\n listStyleType: string | null;\n margin: string | null;\n marginBottom: string | null;\n marginLeft: string | null;\n marginRight: string | null;\n marginTop: string | null;\n marker: string | null;\n markerEnd: string | null;\n markerMid: string | null;\n markerStart: string | null;\n mask: string | null;\n maskImage: string | null;\n maxHeight: string | null;\n maxWidth: string | null;\n minHeight: string | null;\n minWidth: string | null;\n msContentZoomChaining: string | null;\n msContentZoomLimit: string | null;\n msContentZoomLimitMax: any;\n msContentZoomLimitMin: any;\n msContentZoomSnap: string | null;\n msContentZoomSnapPoints: string | null;\n msContentZoomSnapType: string | null;\n msContentZooming: string | null;\n msFlowFrom: string | null;\n msFlowInto: string | null;\n msFontFeatureSettings: string | null;\n msGridColumn: any;\n msGridColumnAlign: string | null;\n msGridColumnSpan: any;\n msGridColumns: string | null;\n msGridRow: any;\n msGridRowAlign: string | null;\n msGridRowSpan: any;\n msGridRows: string | null;\n msHighContrastAdjust: string | null;\n msHyphenateLimitChars: string | null;\n msHyphenateLimitLines: any;\n msHyphenateLimitZone: any;\n msHyphens: string | null;\n msImeAlign: string | null;\n msOverflowStyle: string | null;\n msScrollChaining: string | null;\n msScrollLimit: string | null;\n msScrollLimitXMax: any;\n msScrollLimitXMin: any;\n msScrollLimitYMax: any;\n msScrollLimitYMin: any;\n msScrollRails: string | null;\n msScrollSnapPointsX: string | null;\n msScrollSnapPointsY: string | null;\n msScrollSnapType: string | null;\n msScrollSnapX: string | null;\n msScrollSnapY: string | null;\n msScrollTranslation: string | null;\n msTextCombineHorizontal: string | null;\n msTextSizeAdjust: any;\n msTouchAction: string | null;\n msTouchSelect: string | null;\n msUserSelect: string | null;\n msWrapFlow: string;\n msWrapMargin: any;\n msWrapThrough: string;\n objectFit: string | null;\n objectPosition: string | null;\n opacity: string | null;\n order: string | null;\n orphans: string | null;\n outline: string | null;\n outlineColor: string | null;\n outlineOffset: string | null;\n outlineStyle: string | null;\n outlineWidth: string | null;\n overflow: string | null;\n overflowX: string | null;\n overflowY: string | null;\n padding: string | null;\n paddingBottom: string | null;\n paddingLeft: string | null;\n paddingRight: string | null;\n paddingTop: string | null;\n pageBreakAfter: string | null;\n pageBreakBefore: string | null;\n pageBreakInside: string | null;\n readonly parentRule: CSSRule;\n penAction: string | null;\n perspective: string | null;\n perspectiveOrigin: string | null;\n pointerEvents: string | null;\n position: string | null;\n quotes: string | null;\n resize: string | null;\n right: string | null;\n rotate: string | null;\n rowGap: string | null;\n rubyAlign: string | null;\n rubyOverhang: string | null;\n rubyPosition: string | null;\n scale: string | null;\n stopColor: string | null;\n stopOpacity: string | null;\n stroke: string | null;\n strokeDasharray: string | null;\n strokeDashoffset: string | null;\n strokeLinecap: string | null;\n strokeLinejoin: string | null;\n strokeMiterlimit: string | null;\n strokeOpacity: string | null;\n strokeWidth: string | null;\n tableLayout: string | null;\n textAlign: string | null;\n textAlignLast: string | null;\n textAnchor: string | null;\n textCombineUpright: string | null;\n textDecoration: string | null;\n textIndent: string | null;\n textJustify: string | null;\n textKashida: string | null;\n textKashidaSpace: string | null;\n textOverflow: string | null;\n textShadow: string | null;\n textTransform: string | null;\n textUnderlinePosition: string | null;\n top: string | null;\n touchAction: string | null;\n transform: string | null;\n transformOrigin: string | null;\n transformStyle: string | null;\n transition: string | null;\n transitionDelay: string | null;\n transitionDuration: string | null;\n transitionProperty: string | null;\n transitionTimingFunction: string | null;\n translate: string | null;\n unicodeBidi: string | null;\n userSelect: string | null;\n verticalAlign: string | null;\n visibility: string | null;\n webkitAlignContent: string | null;\n webkitAlignItems: string | null;\n webkitAlignSelf: string | null;\n webkitAnimation: string | null;\n webkitAnimationDelay: string | null;\n webkitAnimationDirection: string | null;\n webkitAnimationDuration: string | null;\n webkitAnimationFillMode: string | null;\n webkitAnimationIterationCount: string | null;\n webkitAnimationName: string | null;\n webkitAnimationPlayState: string | null;\n webkitAnimationTimingFunction: string | null;\n webkitAppearance: string | null;\n webkitBackfaceVisibility: string | null;\n webkitBackgroundClip: string | null;\n webkitBackgroundOrigin: string | null;\n webkitBackgroundSize: string | null;\n webkitBorderBottomLeftRadius: string | null;\n webkitBorderBottomRightRadius: string | null;\n webkitBorderImage: string | null;\n webkitBorderRadius: string | null;\n webkitBorderTopLeftRadius: string | null;\n webkitBorderTopRightRadius: string | null;\n webkitBoxAlign: string | null;\n webkitBoxDirection: string | null;\n webkitBoxFlex: string | null;\n webkitBoxOrdinalGroup: string | null;\n webkitBoxOrient: string | null;\n webkitBoxPack: string | null;\n webkitBoxSizing: string | null;\n webkitColumnBreakAfter: string | null;\n webkitColumnBreakBefore: string | null;\n webkitColumnBreakInside: string | null;\n webkitColumnCount: any;\n webkitColumnGap: any;\n webkitColumnRule: string | null;\n webkitColumnRuleColor: any;\n webkitColumnRuleStyle: string | null;\n webkitColumnRuleWidth: any;\n webkitColumnSpan: string | null;\n webkitColumnWidth: any;\n webkitColumns: string | null;\n webkitFilter: string | null;\n webkitFlex: string | null;\n webkitFlexBasis: string | null;\n webkitFlexDirection: string | null;\n webkitFlexFlow: string | null;\n webkitFlexGrow: string | null;\n webkitFlexShrink: string | null;\n webkitFlexWrap: string | null;\n webkitJustifyContent: string | null;\n webkitOrder: string | null;\n webkitPerspective: string | null;\n webkitPerspectiveOrigin: string | null;\n webkitTapHighlightColor: string | null;\n webkitTextFillColor: string | null;\n webkitTextSizeAdjust: any;\n webkitTextStroke: string | null;\n webkitTextStrokeColor: string | null;\n webkitTextStrokeWidth: string | null;\n webkitTransform: string | null;\n webkitTransformOrigin: string | null;\n webkitTransformStyle: string | null;\n webkitTransition: string | null;\n webkitTransitionDelay: string | null;\n webkitTransitionDuration: string | null;\n webkitTransitionProperty: string | null;\n webkitTransitionTimingFunction: string | null;\n webkitUserModify: string | null;\n webkitUserSelect: string | null;\n webkitWritingMode: string | null;\n whiteSpace: string | null;\n widows: string | null;\n width: string | null;\n wordBreak: string | null;\n wordSpacing: string | null;\n wordWrap: string | null;\n writingMode: string | null;\n zIndex: string | null;\n zoom: string | null;\n getPropertyPriority(propertyName: string): string;\n getPropertyValue(propertyName: string): string;\n item(index: number): string;\n removeProperty(propertyName: string): string;\n setProperty(propertyName: string, value: string | null, priority?: string | null): void;\n [index: number]: string;\n}\n\ndeclare var CSSStyleDeclaration: {\n prototype: CSSStyleDeclaration;\n new(): CSSStyleDeclaration;\n};\n\ninterface CSSStyleRule extends CSSRule {\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSStyleRule: {\n prototype: CSSStyleRule;\n new(): CSSStyleRule;\n};\n\ninterface CSSStyleSheet extends StyleSheet {\n readonly cssRules: CSSRuleList;\n /** @deprecated */\n cssText: string;\n /** @deprecated */\n readonly id: string;\n /** @deprecated */\n readonly imports: StyleSheetList;\n /** @deprecated */\n readonly isAlternate: boolean;\n /** @deprecated */\n readonly isPrefAlternate: boolean;\n readonly ownerRule: CSSRule | null;\n /** @deprecated */\n readonly owningElement: Element;\n /** @deprecated */\n readonly pages: any;\n /** @deprecated */\n readonly readOnly: boolean;\n readonly rules: CSSRuleList;\n /** @deprecated */\n addImport(bstrURL: string, lIndex?: number): number;\n /** @deprecated */\n addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number;\n addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number;\n deleteRule(index?: number): void;\n insertRule(rule: string, index?: number): number;\n /** @deprecated */\n removeImport(lIndex: number): void;\n removeRule(lIndex: number): void;\n}\n\ndeclare var CSSStyleSheet: {\n prototype: CSSStyleSheet;\n new(): CSSStyleSheet;\n};\n\ninterface CSSSupportsRule extends CSSConditionRule {\n}\n\ndeclare var CSSSupportsRule: {\n prototype: CSSSupportsRule;\n new(): CSSSupportsRule;\n};\n\ninterface Cache {\n add(request: Request | string): Promise;\n addAll(requests: (Request | string)[]): Promise;\n delete(request: Request | string, options?: CacheQueryOptions): Promise;\n keys(request?: Request | string, options?: CacheQueryOptions): Promise;\n match(request: Request | string, options?: CacheQueryOptions): Promise;\n matchAll(request?: Request | string, options?: CacheQueryOptions): Promise;\n put(request: Request | string, response: Response): Promise;\n}\n\ndeclare var Cache: {\n prototype: Cache;\n new(): Cache;\n};\n\ninterface CacheStorage {\n delete(cacheName: string): Promise;\n has(cacheName: string): Promise;\n keys(): Promise;\n match(request: Request | string, options?: CacheQueryOptions): Promise;\n open(cacheName: string): Promise;\n}\n\ndeclare var CacheStorage: {\n prototype: CacheStorage;\n new(): CacheStorage;\n};\n\ninterface Canvas2DContextAttributes {\n alpha?: boolean;\n storage?: boolean;\n willReadFrequently?: boolean;\n [attribute: string]: boolean | string | undefined;\n}\n\ninterface CanvasGradient {\n addColorStop(offset: number, color: string): void;\n}\n\ndeclare var CanvasGradient: {\n prototype: CanvasGradient;\n new(): CanvasGradient;\n};\n\ninterface CanvasPathMethods {\n arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;\n bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;\n closePath(): void;\n ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n lineTo(x: number, y: number): void;\n moveTo(x: number, y: number): void;\n quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;\n rect(x: number, y: number, w: number, h: number): void;\n}\n\ninterface CanvasPattern {\n setTransform(matrix: SVGMatrix): void;\n}\n\ndeclare var CanvasPattern: {\n prototype: CanvasPattern;\n new(): CanvasPattern;\n};\n\ninterface CanvasRenderingContext2D extends CanvasPathMethods {\n readonly canvas: HTMLCanvasElement;\n fillStyle: string | CanvasGradient | CanvasPattern;\n font: string;\n globalAlpha: number;\n globalCompositeOperation: string;\n imageSmoothingEnabled: boolean;\n lineCap: string;\n lineDashOffset: number;\n lineJoin: string;\n lineWidth: number;\n miterLimit: number;\n mozImageSmoothingEnabled: boolean;\n msFillRule: CanvasFillRule;\n oImageSmoothingEnabled: boolean;\n shadowBlur: number;\n shadowColor: string;\n shadowOffsetX: number;\n shadowOffsetY: number;\n strokeStyle: string | CanvasGradient | CanvasPattern;\n textAlign: string;\n textBaseline: string;\n webkitImageSmoothingEnabled: boolean;\n beginPath(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n clip(fillRule?: CanvasFillRule): void;\n clip(path: Path2D, fillRule?: CanvasFillRule): void;\n createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;\n createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;\n drawFocusIfNeeded(element: Element): void;\n drawFocusIfNeeded(path: Path2D, element: Element): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void;\n fill(fillRule?: CanvasFillRule): void;\n fill(path: Path2D, fillRule?: CanvasFillRule): void;\n fillRect(x: number, y: number, w: number, h: number): void;\n fillText(text: string, x: number, y: number, maxWidth?: number): void;\n getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;\n getLineDash(): number[];\n isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n measureText(text: string): TextMetrics;\n putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void;\n restore(): void;\n rotate(angle: number): void;\n save(): void;\n scale(x: number, y: number): void;\n setLineDash(segments: number[]): void;\n setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n stroke(path?: Path2D): void;\n strokeRect(x: number, y: number, w: number, h: number): void;\n strokeText(text: string, x: number, y: number, maxWidth?: number): void;\n transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n translate(x: number, y: number): void;\n}\n\ndeclare var CanvasRenderingContext2D: {\n prototype: CanvasRenderingContext2D;\n new(): CanvasRenderingContext2D;\n};\n\ninterface ChannelMergerNode extends AudioNode {\n}\n\ndeclare var ChannelMergerNode: {\n prototype: ChannelMergerNode;\n new(): ChannelMergerNode;\n};\n\ninterface ChannelSplitterNode extends AudioNode {\n}\n\ndeclare var ChannelSplitterNode: {\n prototype: ChannelSplitterNode;\n new(): ChannelSplitterNode;\n};\n\ninterface CharacterData extends Node, ChildNode {\n data: string;\n readonly length: number;\n appendData(arg: string): void;\n deleteData(offset: number, count: number): void;\n insertData(offset: number, arg: string): void;\n replaceData(offset: number, count: number, arg: string): void;\n substringData(offset: number, count: number): string;\n}\n\ndeclare var CharacterData: {\n prototype: CharacterData;\n new(): CharacterData;\n};\n\ninterface ChildNode {\n remove(): void;\n}\n\ninterface ClientRect {\n bottom: number;\n readonly height: number;\n left: number;\n right: number;\n top: number;\n readonly width: number;\n}\n\ndeclare var ClientRect: {\n prototype: ClientRect;\n new(): ClientRect;\n};\n\ninterface ClientRectList {\n readonly length: number;\n item(index: number): ClientRect;\n [index: number]: ClientRect;\n}\n\ndeclare var ClientRectList: {\n prototype: ClientRectList;\n new(): ClientRectList;\n};\n\ninterface ClipboardEvent extends Event {\n readonly clipboardData: DataTransfer;\n}\n\ndeclare var ClipboardEvent: {\n prototype: ClipboardEvent;\n new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;\n};\n\ninterface ClipboardEventInit extends EventInit {\n data?: string;\n dataType?: string;\n}\n\ninterface CloseEvent extends Event {\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n /** @deprecated */\n initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;\n}\n\ndeclare var CloseEvent: {\n prototype: CloseEvent;\n new(type: string, eventInitDict?: CloseEventInit): CloseEvent;\n};\n\ninterface Comment extends CharacterData {\n text: string;\n}\n\ndeclare var Comment: {\n prototype: Comment;\n new(data?: string): Comment;\n};\n\ninterface CompositionEvent extends UIEvent {\n readonly data: string;\n readonly locale: string;\n initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void;\n}\n\ndeclare var CompositionEvent: {\n prototype: CompositionEvent;\n new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent;\n};\n\ninterface ComputedTimingProperties {\n activeDuration: number;\n currentIteration: number | null;\n endTime: number;\n localTime: number | null;\n progress: number | null;\n}\n\ninterface ConcatParams extends Algorithm {\n algorithmId: Uint8Array;\n hash?: string | Algorithm;\n partyUInfo: Uint8Array;\n partyVInfo: Uint8Array;\n privateInfo?: Uint8Array;\n publicInfo?: Uint8Array;\n}\n\ninterface Console {\n memory: any;\n assert(condition?: boolean, message?: string, ...data: any[]): void;\n clear(): void;\n count(label?: string): void;\n debug(message?: any, ...optionalParams: any[]): void;\n dir(value?: any, ...optionalParams: any[]): void;\n dirxml(value: any): void;\n error(message?: any, ...optionalParams: any[]): void;\n exception(message?: string, ...optionalParams: any[]): void;\n group(groupTitle?: string, ...optionalParams: any[]): void;\n groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;\n groupEnd(): void;\n info(message?: any, ...optionalParams: any[]): void;\n log(message?: any, ...optionalParams: any[]): void;\n markTimeline(label?: string): void;\n msIsIndependentlyComposed(element: Element): boolean;\n profile(reportName?: string): void;\n profileEnd(): void;\n select(element: Element): void;\n table(...tabularData: any[]): void;\n time(label?: string): void;\n timeEnd(label?: string): void;\n timeStamp(label?: string): void;\n timeline(label?: string): void;\n timelineEnd(label?: string): void;\n trace(message?: any, ...optionalParams: any[]): void;\n warn(message?: any, ...optionalParams: any[]): void;\n}\n\ndeclare var Console: {\n prototype: Console;\n new(): Console;\n};\n\ninterface ContentScriptGlobalScope extends EventTarget {\n readonly msContentScript: ExtensionScriptApis;\n readonly window: Window;\n}\n\ndeclare var ContentScriptGlobalScope: {\n prototype: ContentScriptGlobalScope;\n new(): ContentScriptGlobalScope;\n};\n\ninterface ConvolverNode extends AudioNode {\n buffer: AudioBuffer | null;\n normalize: boolean;\n}\n\ndeclare var ConvolverNode: {\n prototype: ConvolverNode;\n new(): ConvolverNode;\n};\n\ninterface Coordinates {\n readonly accuracy: number;\n readonly altitude: number | null;\n readonly altitudeAccuracy: number | null;\n readonly heading: number | null;\n readonly latitude: number;\n readonly longitude: number;\n readonly speed: number | null;\n}\n\ndeclare var Coordinates: {\n prototype: Coordinates;\n new(): Coordinates;\n};\n\ninterface CountQueuingStrategy {\n highWaterMark: number;\n size(): number;\n}\n\ndeclare var CountQueuingStrategy: {\n prototype: CountQueuingStrategy;\n new(strategy: QueuingStrategy): CountQueuingStrategy;\n};\n\ninterface Crypto {\n readonly subtle: SubtleCrypto;\n getRandomValues(array: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null;\n}\n\ndeclare var Crypto: {\n prototype: Crypto;\n new(): Crypto;\n};\n\ninterface CryptoKey {\n readonly algorithm: KeyAlgorithm;\n readonly extractable: boolean;\n readonly type: string;\n readonly usages: string[];\n}\n\ndeclare var CryptoKey: {\n prototype: CryptoKey;\n new(): CryptoKey;\n};\n\ninterface CryptoKeyPair {\n privateKey: CryptoKey;\n publicKey: CryptoKey;\n}\n\ndeclare var CryptoKeyPair: {\n prototype: CryptoKeyPair;\n new(): CryptoKeyPair;\n};\n\ninterface CustomElementRegistry {\n define(name: string, constructor: Function, options?: ElementDefinitionOptions): void;\n get(name: string): any;\n whenDefined(name: string): PromiseLike;\n}\n\ninterface CustomEvent extends Event {\n readonly detail: T;\n initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void;\n}\n\ndeclare var CustomEvent: {\n prototype: CustomEvent;\n new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent;\n};\n\ninterface DOMError {\n readonly name: string;\n toString(): string;\n}\n\ndeclare var DOMError: {\n prototype: DOMError;\n new(): DOMError;\n};\n\ninterface DOMException {\n readonly code: number;\n readonly message: string;\n readonly name: string;\n toString(): string;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly PARSE_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SERIALIZE_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n}\n\ndeclare var DOMException: {\n prototype: DOMException;\n new(message?: string, name?: string): DOMException;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly PARSE_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SERIALIZE_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n};\n\ninterface DOMImplementation {\n createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document;\n createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;\n createHTMLDocument(title?: string): Document;\n hasFeature(feature: string | null, version: string | null): boolean;\n}\n\ndeclare var DOMImplementation: {\n prototype: DOMImplementation;\n new(): DOMImplementation;\n};\n\ninterface DOML2DeprecatedColorProperty {\n color: string;\n}\n\ninterface DOML2DeprecatedSizeProperty {\n size: number;\n}\n\ninterface DOMParser {\n parseFromString(source: string, mimeType: string): Document;\n}\n\ndeclare var DOMParser: {\n prototype: DOMParser;\n new(): DOMParser;\n};\n\ninterface DOMRect extends DOMRectReadOnly {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var DOMRect: {\n prototype: DOMRect;\n new (x?: number, y?: number, width?: number, height?: number): DOMRect;\n fromRect(rectangle?: DOMRectInit): DOMRect;\n};\n\ninterface DOMRectList {\n readonly length: number;\n item(index: number): DOMRect | null;\n [index: number]: DOMRect;\n}\n\ninterface DOMRectReadOnly {\n readonly bottom: number;\n readonly height: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n}\n\ndeclare var DOMRectReadOnly: {\n prototype: DOMRectReadOnly;\n new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly;\n fromRect(rectangle?: DOMRectInit): DOMRectReadOnly;\n};\n\ninterface DOMSettableTokenList extends DOMTokenList {\n value: string;\n}\n\ndeclare var DOMSettableTokenList: {\n prototype: DOMSettableTokenList;\n new(): DOMSettableTokenList;\n};\n\ninterface DOMStringList {\n readonly length: number;\n contains(str: string): boolean;\n item(index: number): string | null;\n [index: number]: string;\n}\n\ndeclare var DOMStringList: {\n prototype: DOMStringList;\n new(): DOMStringList;\n};\n\ninterface DOMStringMap {\n [name: string]: string | undefined;\n}\n\ndeclare var DOMStringMap: {\n prototype: DOMStringMap;\n new(): DOMStringMap;\n};\n\ninterface DOMTokenList {\n readonly length: number;\n add(...tokens: string[]): void;\n contains(token: string): boolean;\n item(index: number): string | null;\n remove(...tokens: string[]): void;\n toString(): string;\n toggle(token: string, force?: boolean): boolean;\n [index: number]: string;\n}\n\ndeclare var DOMTokenList: {\n prototype: DOMTokenList;\n new(): DOMTokenList;\n};\n\ninterface DataCue extends TextTrackCue {\n data: ArrayBuffer;\n addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var DataCue: {\n prototype: DataCue;\n new(): DataCue;\n};\n\ninterface DataTransfer {\n dropEffect: string;\n effectAllowed: string;\n readonly files: FileList;\n readonly items: DataTransferItemList;\n readonly types: string[];\n clearData(format?: string): boolean;\n getData(format: string): string;\n setData(format: string, data: string): boolean;\n setDragImage(image: Element, x: number, y: number): void;\n}\n\ndeclare var DataTransfer: {\n prototype: DataTransfer;\n new(): DataTransfer;\n};\n\ninterface DataTransferItem {\n readonly kind: string;\n readonly type: string;\n getAsFile(): File | null;\n getAsString(_callback: FunctionStringCallback | null): void;\n webkitGetAsEntry(): any;\n}\n\ndeclare var DataTransferItem: {\n prototype: DataTransferItem;\n new(): DataTransferItem;\n};\n\ninterface DataTransferItemList {\n readonly length: number;\n add(data: File): DataTransferItem | null;\n add(data: string, type: string): DataTransferItem | null;\n clear(): void;\n item(index: number): DataTransferItem;\n remove(index: number): void;\n [name: number]: DataTransferItem;\n}\n\ndeclare var DataTransferItemList: {\n prototype: DataTransferItemList;\n new(): DataTransferItemList;\n};\n\ninterface DeferredPermissionRequest {\n readonly id: number;\n readonly type: MSWebViewPermissionType;\n readonly uri: string;\n allow(): void;\n deny(): void;\n}\n\ndeclare var DeferredPermissionRequest: {\n prototype: DeferredPermissionRequest;\n new(): DeferredPermissionRequest;\n};\n\ninterface DelayNode extends AudioNode {\n readonly delayTime: AudioParam;\n}\n\ndeclare var DelayNode: {\n prototype: DelayNode;\n new(): DelayNode;\n};\n\ninterface DeviceAcceleration {\n readonly x: number | null;\n readonly y: number | null;\n readonly z: number | null;\n}\n\ndeclare var DeviceAcceleration: {\n prototype: DeviceAcceleration;\n new(): DeviceAcceleration;\n};\n\ninterface DeviceLightEvent extends Event {\n readonly value: number;\n}\n\ndeclare var DeviceLightEvent: {\n prototype: DeviceLightEvent;\n new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;\n};\n\ninterface DeviceMotionEvent extends Event {\n readonly acceleration: DeviceAcceleration | null;\n readonly accelerationIncludingGravity: DeviceAcceleration | null;\n readonly interval: number | null;\n readonly rotationRate: DeviceRotationRate | null;\n initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void;\n}\n\ndeclare var DeviceMotionEvent: {\n prototype: DeviceMotionEvent;\n new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;\n};\n\ninterface DeviceOrientationEvent extends Event {\n readonly absolute: boolean;\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void;\n}\n\ndeclare var DeviceOrientationEvent: {\n prototype: DeviceOrientationEvent;\n new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;\n};\n\ninterface DeviceRotationRate {\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n}\n\ndeclare var DeviceRotationRate: {\n prototype: DeviceRotationRate;\n new(): DeviceRotationRate;\n};\n\ninterface DhImportKeyParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyAlgorithm extends KeyAlgorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface DhKeyGenParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DocumentEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforedeactivate\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"fullscreenchange\": Event;\n \"fullscreenerror\": Event;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSManipulationStateChanged\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"mssitemodejumplistitemremoved\": Event;\n \"msthumbnailclick\": Event;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"pointerlockchange\": Event;\n \"pointerlockerror\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectionchange\": Event;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"stop\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent {\n /**\n * Sets or gets the URL for the current document.\n */\n readonly URL: string;\n /**\n * Gets the URL for the document, stripped of any character encoding.\n */\n readonly URLUnencoded: string;\n /**\n * Gets the object that has the focus when the parent document has focus.\n */\n readonly activeElement: Element;\n /**\n * Sets or gets the color of all active links in the document.\n */\n alinkColor: string;\n /**\n * Returns a reference to the collection of elements contained by the object.\n */\n readonly all: HTMLAllCollection;\n /**\n * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order.\n */\n readonly anchors: HTMLCollectionOf;\n /**\n * Retrieves a collection of all applet objects in the document.\n */\n readonly applets: HTMLCollectionOf;\n /**\n * Deprecated. Sets or retrieves a value that indicates the background color behind the object.\n */\n bgColor: string;\n /**\n * Specifies the beginning and end of the document body.\n */\n body: HTMLElement;\n readonly characterSet: string;\n /**\n * Gets or sets the character set used to encode the object.\n */\n charset: string;\n /**\n * Gets a value that indicates whether standards-compliant mode is switched on for the object.\n */\n readonly compatMode: string;\n cookie: string;\n readonly currentScript: HTMLScriptElement | SVGScriptElement | null;\n readonly defaultView: Window;\n /**\n * Sets or gets a value that indicates whether the document can be edited.\n */\n designMode: string;\n /**\n * Sets or retrieves a value that indicates the reading order of the object.\n */\n dir: string;\n /**\n * Gets an object representing the document type declaration associated with the current document.\n */\n readonly doctype: DocumentType;\n /**\n * Gets a reference to the root node of the document.\n */\n readonly documentElement: HTMLElement;\n /**\n * Sets or gets the security domain of the document.\n */\n domain: string;\n /**\n * Retrieves a collection of all embed objects in the document.\n */\n readonly embeds: HTMLCollectionOf;\n /**\n * Sets or gets the foreground (text) color of the document.\n */\n fgColor: string;\n /**\n * Retrieves a collection, in source order, of all form objects in the document.\n */\n readonly forms: HTMLCollectionOf;\n readonly fullscreenElement: Element | null;\n readonly fullscreenEnabled: boolean;\n readonly head: HTMLHeadElement;\n readonly hidden: boolean;\n /**\n * Retrieves a collection, in source order, of img objects in the document.\n */\n readonly images: HTMLCollectionOf;\n /**\n * Gets the implementation object of the current document.\n */\n readonly implementation: DOMImplementation;\n /**\n * Returns the character encoding used to create the webpage that is loaded into the document object.\n */\n readonly inputEncoding: string | null;\n /**\n * Gets the date that the page was last modified, if the page supplies one.\n */\n readonly lastModified: string;\n /**\n * Sets or gets the color of the document links.\n */\n linkColor: string;\n /**\n * Retrieves a collection of all a objects that specify the href property and all area objects in the document.\n */\n readonly links: HTMLCollectionOf;\n /**\n * Contains information about the current URL.\n */\n location: Location;\n msCSSOMElementFloatMetrics: boolean;\n msCapsLockWarningOff: boolean;\n /**\n * Fires when the user aborts the download.\n * @param ev The event.\n */\n onabort: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the object is set as the active element.\n * @param ev The event.\n */\n onactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the object is set as the active element.\n * @param ev The event.\n */\n onbeforeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the activeElement is changed from the current object to another object in the parent document.\n * @param ev The event.\n */\n onbeforedeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the object loses the input focus.\n * @param ev The focus event.\n */\n onblur: ((this: Document, ev: FocusEvent) => any) | null;\n /**\n * Occurs when playback is possible, but would require further buffering.\n * @param ev The event.\n */\n oncanplay: ((this: Document, ev: Event) => any) | null;\n oncanplaythrough: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the contents of the object or selection have changed.\n * @param ev The event.\n */\n onchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the left mouse button on the object\n * @param ev The mouse event.\n */\n onclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user clicks the right mouse button in the client area, opening the context menu.\n * @param ev The mouse event.\n */\n oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null;\n /**\n * Fires when the user double-clicks the object.\n * @param ev The mouse event.\n */\n ondblclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the activeElement is changed from the current object to another object in the parent document.\n * @param ev The UI Event\n */\n ondeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires on the source object continuously during a drag operation.\n * @param ev The event.\n */\n ondrag: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user releases the mouse at the close of a drag operation.\n * @param ev The event.\n */\n ondragend: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element when the user drags the object to a valid drop target.\n * @param ev The drag event.\n */\n ondragenter: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.\n * @param ev The drag event.\n */\n ondragleave: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element continuously while the user drags the object over a valid drop target.\n * @param ev The event.\n */\n ondragover: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user starts to drag a text selection or selected object.\n * @param ev The event.\n */\n ondragstart: ((this: Document, ev: DragEvent) => any) | null;\n ondrop: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Occurs when the duration attribute is updated.\n * @param ev The event.\n */\n ondurationchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the media element is reset to its initial state.\n * @param ev The event.\n */\n onemptied: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the end of playback is reached.\n * @param ev The event\n */\n onended: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when an error occurs during object loading.\n * @param ev The event.\n */\n onerror: ((this: Document, ev: ErrorEvent) => any) | null;\n /**\n * Fires when the object receives focus.\n * @param ev The event.\n */\n onfocus: ((this: Document, ev: FocusEvent) => any) | null;\n onfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onfullscreenerror: ((this: Document, ev: Event) => any) | null;\n oninput: ((this: Document, ev: Event) => any) | null;\n oninvalid: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user presses a key.\n * @param ev The keyboard event\n */\n onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user presses an alphanumeric key.\n * @param ev The event.\n */\n onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user releases a key.\n * @param ev The keyboard event\n */\n onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires immediately after the browser loads the object.\n * @param ev The event.\n */\n onload: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when media data is loaded at the current playback position.\n * @param ev The event.\n */\n onloadeddata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the duration and dimensions of the media have been determined.\n * @param ev The event.\n */\n onloadedmetadata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when Internet Explorer begins looking for media data.\n * @param ev The event.\n */\n onloadstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the object with either mouse button.\n * @param ev The mouse event.\n */\n onmousedown: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse over the object.\n * @param ev The mouse event.\n */\n onmousemove: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer outside the boundaries of the object.\n * @param ev The mouse event.\n */\n onmouseout: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer into the object.\n * @param ev The mouse event.\n */\n onmouseover: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user releases a mouse button while the mouse is over the object.\n * @param ev The mouse event.\n */\n onmouseup: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the wheel button is rotated.\n * @param ev The mouse event\n */\n onmousewheel: ((this: Document, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: Document, ev: Event) => any) | null;\n onmsgesturechange: ((this: Document, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null;\n onmsgestureend: ((this: Document, ev: Event) => any) | null;\n onmsgesturehold: ((this: Document, ev: Event) => any) | null;\n onmsgesturestart: ((this: Document, ev: Event) => any) | null;\n onmsgesturetap: ((this: Document, ev: Event) => any) | null;\n onmsinertiastart: ((this: Document, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null;\n onmspointercancel: ((this: Document, ev: Event) => any) | null;\n onmspointerdown: ((this: Document, ev: Event) => any) | null;\n onmspointerenter: ((this: Document, ev: Event) => any) | null;\n onmspointerleave: ((this: Document, ev: Event) => any) | null;\n onmspointermove: ((this: Document, ev: Event) => any) | null;\n onmspointerout: ((this: Document, ev: Event) => any) | null;\n onmspointerover: ((this: Document, ev: Event) => any) | null;\n onmspointerup: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when an item is removed from a Jump List of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmsthumbnailclick: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback is paused.\n * @param ev The event.\n */\n onpause: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the play method is requested.\n * @param ev The event.\n */\n onplay: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the audio or video has started playing.\n * @param ev The event.\n */\n onplaying: ((this: Document, ev: Event) => any) | null;\n onpointerlockchange: ((this: Document, ev: Event) => any) | null;\n onpointerlockerror: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate progress while downloading media data.\n * @param ev The event.\n */\n onprogress: ((this: Document, ev: ProgressEvent) => any) | null;\n /**\n * Occurs when the playback rate is increased or decreased.\n * @param ev The event.\n */\n onratechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the state of the object has changed.\n * @param ev The event\n */\n onreadystatechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user resets a form.\n * @param ev The event.\n */\n onreset: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user repositions the scroll box in the scroll bar on the object.\n * @param ev The event.\n */\n onscroll: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Occurs when the seek operation ends.\n * @param ev The event.\n */\n onseeked: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the current playback position is moved.\n * @param ev The event.\n */\n onseeking: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the current selection changes.\n * @param ev The event.\n */\n onselect: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the selection state of a document changes.\n * @param ev The event.\n */\n onselectionchange: ((this: Document, ev: Event) => any) | null;\n onselectstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the download has stopped.\n * @param ev The event.\n */\n onstalled: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the Stop button or leaves the Web page.\n * @param ev The event.\n */\n onstop: ((this: Document, ev: Event) => any) | null;\n onsubmit: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs if the load operation has been intentionally halted.\n * @param ev The event.\n */\n onsuspend: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate the current playback position.\n * @param ev The event.\n */\n ontimeupdate: ((this: Document, ev: Event) => any) | null;\n ontouchcancel: ((this: Document, ev: Event) => any) | null;\n ontouchend: ((this: Document, ev: Event) => any) | null;\n ontouchmove: ((this: Document, ev: Event) => any) | null;\n ontouchstart: ((this: Document, ev: Event) => any) | null;\n onvisibilitychange: (this: Document, ev: Event) => any;\n /**\n * Occurs when the volume is changed, or playback is muted or unmuted.\n * @param ev The event.\n */\n onvolumechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback stops because the next frame of a video resource is not available.\n * @param ev The event.\n */\n onwaiting: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null;\n readonly plugins: HTMLCollectionOf;\n readonly pointerLockElement: Element;\n /**\n * Retrieves a value that indicates the current state of the object.\n */\n readonly readyState: string;\n /**\n * Gets the URL of the location that referred the user to the current page.\n */\n readonly referrer: string;\n /**\n * Gets the root svg element in the document hierarchy.\n */\n readonly rootElement: SVGSVGElement;\n /**\n * Retrieves a collection of all script objects in the document.\n */\n readonly scripts: HTMLCollectionOf;\n readonly scrollingElement: Element | null;\n /**\n * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document.\n */\n readonly styleSheets: StyleSheetList;\n /**\n * Contains the title of the document.\n */\n title: string;\n readonly visibilityState: VisibilityState;\n /**\n * Sets or gets the color of the links that the user has visited.\n */\n vlinkColor: string;\n readonly webkitCurrentFullScreenElement: Element | null;\n readonly webkitFullscreenElement: Element | null;\n readonly webkitFullscreenEnabled: boolean;\n readonly webkitIsFullScreen: boolean;\n readonly xmlEncoding: string | null;\n xmlStandalone: boolean;\n /**\n * Gets or sets the version attribute specified in the declaration of an XML document.\n */\n xmlVersion: string | null;\n adoptNode(source: T): T;\n captureEvents(): void;\n caretRangeFromPoint(x: number, y: number): Range;\n clear(): void;\n /**\n * Closes an output stream and forces the sent data to display.\n */\n close(): void;\n /**\n * Creates an attribute object with a specified name.\n * @param name String that sets the attribute object's name.\n */\n createAttribute(name: string): Attr;\n createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;\n createCDATASection(data: string): CDATASection;\n /**\n * Creates a comment object with the specified data.\n * @param data Sets the comment object's data.\n */\n createComment(data: string): Comment;\n /**\n * Creates a new document.\n */\n createDocumentFragment(): DocumentFragment;\n /**\n * Creates an instance of the element for the specified tag.\n * @param tagName The name of an element.\n */\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];\n createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", qualifiedName: string): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"a\"): SVGAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"circle\"): SVGCircleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"clipPath\"): SVGClipPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"componentTransferFunction\"): SVGComponentTransferFunctionElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"defs\"): SVGDefsElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"desc\"): SVGDescElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"ellipse\"): SVGEllipseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feBlend\"): SVGFEBlendElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feColorMatrix\"): SVGFEColorMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComponentTransfer\"): SVGFEComponentTransferElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComposite\"): SVGFECompositeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feConvolveMatrix\"): SVGFEConvolveMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDiffuseLighting\"): SVGFEDiffuseLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDisplacementMap\"): SVGFEDisplacementMapElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDistantLight\"): SVGFEDistantLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFlood\"): SVGFEFloodElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncA\"): SVGFEFuncAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncB\"): SVGFEFuncBElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncG\"): SVGFEFuncGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncR\"): SVGFEFuncRElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feGaussianBlur\"): SVGFEGaussianBlurElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feImage\"): SVGFEImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMerge\"): SVGFEMergeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMergeNode\"): SVGFEMergeNodeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMorphology\"): SVGFEMorphologyElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feOffset\"): SVGFEOffsetElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"fePointLight\"): SVGFEPointLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpecularLighting\"): SVGFESpecularLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpotLight\"): SVGFESpotLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTile\"): SVGFETileElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTurbulence\"): SVGFETurbulenceElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"filter\"): SVGFilterElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"foreignObject\"): SVGForeignObjectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"g\"): SVGGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"image\"): SVGImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"gradient\"): SVGGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"line\"): SVGLineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"linearGradient\"): SVGLinearGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"marker\"): SVGMarkerElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"mask\"): SVGMaskElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"path\"): SVGPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"metadata\"): SVGMetadataElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"pattern\"): SVGPatternElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polygon\"): SVGPolygonElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polyline\"): SVGPolylineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"radialGradient\"): SVGRadialGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"rect\"): SVGRectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"svg\"): SVGSVGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"script\"): SVGScriptElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"stop\"): SVGStopElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"style\"): SVGStyleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"switch\"): SVGSwitchElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"symbol\"): SVGSymbolElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"tspan\"): SVGTSpanElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textContent\"): SVGTextContentElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"text\"): SVGTextElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPath\"): SVGTextPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPositioning\"): SVGTextPositioningElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"title\"): SVGTitleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"use\"): SVGUseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"view\"): SVGViewElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: string): SVGElement;\n createElementNS(namespaceURI: string | null, qualifiedName: string): Element;\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver: Node): XPathNSResolver;\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list\n * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator;\n createProcessingInstruction(target: string, data: string): ProcessingInstruction;\n /**\n * Returns an empty range object that has both of its boundary points positioned at the beginning of the document.\n */\n createRange(): Range;\n /**\n * Creates a text string from the specified value.\n * @param data String that specifies the nodeValue property of the text node.\n */\n createTextNode(data: string): Text;\n createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch;\n createTouchList(...touches: Touch[]): TouchList;\n /**\n * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow.\n * @param filter A custom NodeFilter function to use.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker;\n /**\n * Returns the element for the specified x coordinate and the specified y coordinate.\n * @param x The x-offset\n * @param y The y-offset\n */\n elementFromPoint(x: number, y: number): Element;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n /**\n * Executes a command on the current document, current selection, or the given range.\n * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.\n * @param showUI Display the user interface, defaults to false.\n * @param value Value to assign.\n */\n execCommand(commandId: string, showUI?: boolean, value?: any): boolean;\n /**\n * Displays help information for the given command identifier.\n * @param commandId Displays help information for the given command identifier.\n */\n execCommandShowHelp(commandId: string): boolean;\n exitFullscreen(): void;\n exitPointerLock(): void;\n /**\n * Causes the element to receive the focus and executes the code specified by the onfocus event.\n */\n /** @deprecated */\n focus(): void;\n /**\n * Returns a reference to the first object with the specified value of the ID or NAME attribute.\n * @param elementId String that specifies the ID value. Case-insensitive.\n */\n getElementById(elementId: string): HTMLElement | null;\n getElementsByClassName(classNames: string): HTMLCollectionOf;\n /**\n * Gets a collection of objects based on the value of the NAME or ID attribute.\n * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.\n */\n getElementsByName(elementName: string): NodeListOf;\n /**\n * Retrieves a collection of objects based on the specified element name.\n * @param name Specifies the name of an element.\n */\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n /**\n * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.\n */\n getSelection(): Selection;\n /**\n * Gets a value indicating whether the object currently has focus.\n */\n hasFocus(): boolean;\n importNode(importedNode: T, deep: boolean): T;\n msElementsFromPoint(x: number, y: number): NodeListOf;\n msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf;\n /**\n * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method.\n * @param url Specifies a MIME type for the document.\n * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.\n * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, \"fullscreen=yes, toolbar=yes\"). The following values are supported.\n * @param replace Specifies whether the existing entry for the document is replaced in the history list.\n */\n open(url?: string, name?: string, features?: string, replace?: boolean): Document;\n /**\n * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.\n * @param commandId Specifies a command identifier.\n */\n queryCommandEnabled(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the specified command is in the indeterminate state.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandIndeterm(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates the current state of the command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandState(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the current command is supported on the current range.\n * @param commandId Specifies a command identifier.\n */\n queryCommandSupported(commandId: string): boolean;\n /**\n * Retrieves the string associated with a command.\n * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers.\n */\n queryCommandText(commandId: string): string;\n /**\n * Returns the current value of the document, range, or current selection for the given command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandValue(commandId: string): string;\n releaseEvents(): void;\n webkitCancelFullScreen(): void;\n webkitExitFullscreen(): void;\n /**\n * Writes one or more HTML expressions to a document in the specified window.\n * @param content Specifies the text and HTML tags to write.\n */\n write(...content: string[]): void;\n /**\n * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window.\n * @param content The text and HTML tags to write.\n */\n writeln(...content: string[]): void;\n addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Document: {\n prototype: Document;\n new(): Document;\n};\n\ninterface DocumentEvent {\n createEvent(eventInterface: \"AnimationEvent\"): AnimationEvent;\n createEvent(eventInterface: \"AnimationPlaybackEvent\"): AnimationPlaybackEvent;\n createEvent(eventInterface: \"AudioProcessingEvent\"): AudioProcessingEvent;\n createEvent(eventInterface: \"BeforeUnloadEvent\"): BeforeUnloadEvent;\n createEvent(eventInterface: \"ClipboardEvent\"): ClipboardEvent;\n createEvent(eventInterface: \"CloseEvent\"): CloseEvent;\n createEvent(eventInterface: \"CompositionEvent\"): CompositionEvent;\n createEvent(eventInterface: \"CustomEvent\"): CustomEvent;\n createEvent(eventInterface: \"DeviceLightEvent\"): DeviceLightEvent;\n createEvent(eventInterface: \"DeviceMotionEvent\"): DeviceMotionEvent;\n createEvent(eventInterface: \"DeviceOrientationEvent\"): DeviceOrientationEvent;\n createEvent(eventInterface: \"DragEvent\"): DragEvent;\n createEvent(eventInterface: \"ErrorEvent\"): ErrorEvent;\n createEvent(eventInterface: \"Event\"): Event;\n createEvent(eventInterface: \"Events\"): Event;\n createEvent(eventInterface: \"FocusEvent\"): FocusEvent;\n createEvent(eventInterface: \"FocusNavigationEvent\"): FocusNavigationEvent;\n createEvent(eventInterface: \"GamepadEvent\"): GamepadEvent;\n createEvent(eventInterface: \"HashChangeEvent\"): HashChangeEvent;\n createEvent(eventInterface: \"IDBVersionChangeEvent\"): IDBVersionChangeEvent;\n createEvent(eventInterface: \"KeyboardEvent\"): KeyboardEvent;\n createEvent(eventInterface: \"ListeningStateChangedEvent\"): ListeningStateChangedEvent;\n createEvent(eventInterface: \"MSDCCEvent\"): MSDCCEvent;\n createEvent(eventInterface: \"MSDSHEvent\"): MSDSHEvent;\n createEvent(eventInterface: \"MSMediaKeyMessageEvent\"): MSMediaKeyMessageEvent;\n createEvent(eventInterface: \"MSMediaKeyNeededEvent\"): MSMediaKeyNeededEvent;\n createEvent(eventInterface: \"MediaEncryptedEvent\"): MediaEncryptedEvent;\n createEvent(eventInterface: \"MediaKeyMessageEvent\"): MediaKeyMessageEvent;\n createEvent(eventInterface: \"MediaStreamErrorEvent\"): MediaStreamErrorEvent;\n createEvent(eventInterface: \"MediaStreamEvent\"): MediaStreamEvent;\n createEvent(eventInterface: \"MediaStreamTrackEvent\"): MediaStreamTrackEvent;\n createEvent(eventInterface: \"MessageEvent\"): MessageEvent;\n createEvent(eventInterface: \"MouseEvent\"): MouseEvent;\n createEvent(eventInterface: \"MouseEvents\"): MouseEvent;\n createEvent(eventInterface: \"MutationEvent\"): MutationEvent;\n createEvent(eventInterface: \"MutationEvents\"): MutationEvent;\n createEvent(eventInterface: \"OfflineAudioCompletionEvent\"): OfflineAudioCompletionEvent;\n createEvent(eventInterface: \"OverflowEvent\"): OverflowEvent;\n createEvent(eventInterface: \"PageTransitionEvent\"): PageTransitionEvent;\n createEvent(eventInterface: \"PaymentRequestUpdateEvent\"): PaymentRequestUpdateEvent;\n createEvent(eventInterface: \"PermissionRequestedEvent\"): PermissionRequestedEvent;\n createEvent(eventInterface: \"PointerEvent\"): PointerEvent;\n createEvent(eventInterface: \"PopStateEvent\"): PopStateEvent;\n createEvent(eventInterface: \"ProgressEvent\"): ProgressEvent;\n createEvent(eventInterface: \"PromiseRejectionEvent\"): PromiseRejectionEvent;\n createEvent(eventInterface: \"RTCDTMFToneChangeEvent\"): RTCDTMFToneChangeEvent;\n createEvent(eventInterface: \"RTCDtlsTransportStateChangedEvent\"): RTCDtlsTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCIceCandidatePairChangedEvent\"): RTCIceCandidatePairChangedEvent;\n createEvent(eventInterface: \"RTCIceGathererEvent\"): RTCIceGathererEvent;\n createEvent(eventInterface: \"RTCIceTransportStateChangedEvent\"): RTCIceTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceEvent\"): RTCPeerConnectionIceEvent;\n createEvent(eventInterface: \"RTCSsrcConflictEvent\"): RTCSsrcConflictEvent;\n createEvent(eventInterface: \"SVGZoomEvent\"): SVGZoomEvent;\n createEvent(eventInterface: \"SVGZoomEvents\"): SVGZoomEvent;\n createEvent(eventInterface: \"SecurityPolicyViolationEvent\"): SecurityPolicyViolationEvent;\n createEvent(eventInterface: \"ServiceWorkerMessageEvent\"): ServiceWorkerMessageEvent;\n createEvent(eventInterface: \"SpeechSynthesisEvent\"): SpeechSynthesisEvent;\n createEvent(eventInterface: \"StorageEvent\"): StorageEvent;\n createEvent(eventInterface: \"TextEvent\"): TextEvent;\n createEvent(eventInterface: \"TrackEvent\"): TrackEvent;\n createEvent(eventInterface: \"TransitionEvent\"): TransitionEvent;\n createEvent(eventInterface: \"UIEvent\"): UIEvent;\n createEvent(eventInterface: \"UIEvents\"): UIEvent;\n createEvent(eventInterface: \"VRDisplayEvent\"): VRDisplayEvent;\n createEvent(eventInterface: \"VRDisplayEvent \"): VRDisplayEvent ;\n createEvent(eventInterface: \"WebGLContextEvent\"): WebGLContextEvent;\n createEvent(eventInterface: \"WheelEvent\"): WheelEvent;\n createEvent(eventInterface: string): Event;\n}\n\ninterface DocumentFragment extends Node, ParentNode {\n getElementById(elementId: string): HTMLElement | null;\n}\n\ndeclare var DocumentFragment: {\n prototype: DocumentFragment;\n new(): DocumentFragment;\n};\n\ninterface DocumentOrShadowRoot {\n readonly activeElement: Element | null;\n readonly styleSheets: StyleSheetList;\n elementFromPoint(x: number, y: number): Element | null;\n elementsFromPoint(x: number, y: number): Element[];\n getSelection(): Selection | null;\n}\n\ninterface DocumentType extends Node, ChildNode {\n readonly entities: NamedNodeMap;\n readonly internalSubset: string | null;\n readonly name: string;\n readonly notations: NamedNodeMap;\n readonly publicId: string;\n readonly systemId: string;\n}\n\ndeclare var DocumentType: {\n prototype: DocumentType;\n new(): DocumentType;\n};\n\ninterface DragEvent extends MouseEvent {\n readonly dataTransfer: DataTransfer;\n initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void;\n msConvertURL(file: File, targetType: string, targetURL?: string): void;\n}\n\ndeclare var DragEvent: {\n prototype: DragEvent;\n new(type: \"drag\" | \"dragend\" | \"dragenter\" | \"dragexit\" | \"dragleave\" | \"dragover\" | \"dragstart\" | \"drop\", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent;\n};\n\ninterface DynamicsCompressorNode extends AudioNode {\n readonly attack: AudioParam;\n readonly knee: AudioParam;\n readonly ratio: AudioParam;\n readonly reduction: number;\n readonly release: AudioParam;\n readonly threshold: AudioParam;\n}\n\ndeclare var DynamicsCompressorNode: {\n prototype: DynamicsCompressorNode;\n new(): DynamicsCompressorNode;\n};\n\ninterface EXT_blend_minmax {\n readonly MAX_EXT: number;\n readonly MIN_EXT: number;\n}\n\ninterface EXT_frag_depth {\n}\n\ninterface EXT_sRGB {\n readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number;\n readonly SRGB8_ALPHA8_EXT: number;\n readonly SRGB_ALPHA_EXT: number;\n readonly SRGB_EXT: number;\n}\n\ninterface EXT_shader_texture_lod {\n}\n\ninterface EXT_texture_filter_anisotropic {\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n}\n\ndeclare var EXT_texture_filter_anisotropic: {\n prototype: EXT_texture_filter_anisotropic;\n new(): EXT_texture_filter_anisotropic;\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n};\n\ninterface ElementEventMap extends GlobalEventHandlersEventMap {\n \"ariarequest\": Event;\n \"command\": Event;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSGotPointerCapture\": Event;\n \"MSInertiaStart\": Event;\n \"MSLostPointerCapture\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly attributes: NamedNodeMap;\n readonly classList: DOMTokenList;\n className: string;\n readonly clientHeight: number;\n readonly clientLeft: number;\n readonly clientTop: number;\n readonly clientWidth: number;\n id: string;\n innerHTML: string;\n msContentZoomFactor: number;\n readonly msRegionOverflow: string;\n onariarequest: ((this: Element, ev: Event) => any) | null;\n oncommand: ((this: Element, ev: Event) => any) | null;\n ongotpointercapture: ((this: Element, ev: PointerEvent) => any) | null;\n onlostpointercapture: ((this: Element, ev: PointerEvent) => any) | null;\n onmsgesturechange: ((this: Element, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null;\n onmsgestureend: ((this: Element, ev: Event) => any) | null;\n onmsgesturehold: ((this: Element, ev: Event) => any) | null;\n onmsgesturestart: ((this: Element, ev: Event) => any) | null;\n onmsgesturetap: ((this: Element, ev: Event) => any) | null;\n onmsgotpointercapture: ((this: Element, ev: Event) => any) | null;\n onmsinertiastart: ((this: Element, ev: Event) => any) | null;\n onmslostpointercapture: ((this: Element, ev: Event) => any) | null;\n onmspointercancel: ((this: Element, ev: Event) => any) | null;\n onmspointerdown: ((this: Element, ev: Event) => any) | null;\n onmspointerenter: ((this: Element, ev: Event) => any) | null;\n onmspointerleave: ((this: Element, ev: Event) => any) | null;\n onmspointermove: ((this: Element, ev: Event) => any) | null;\n onmspointerout: ((this: Element, ev: Event) => any) | null;\n onmspointerover: ((this: Element, ev: Event) => any) | null;\n onmspointerup: ((this: Element, ev: Event) => any) | null;\n ontouchcancel: ((this: Element, ev: Event) => any) | null;\n ontouchend: ((this: Element, ev: Event) => any) | null;\n ontouchmove: ((this: Element, ev: Event) => any) | null;\n ontouchstart: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null;\n outerHTML: string;\n readonly prefix: string | null;\n readonly scrollHeight: number;\n scrollLeft: number;\n scrollTop: number;\n readonly scrollWidth: number;\n readonly shadowRoot: ShadowRoot | null;\n slot: string;\n readonly tagName: string;\n attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;\n closest(selector: K): HTMLElementTagNameMap[K] | null;\n closest(selector: K): SVGElementTagNameMap[K] | null;\n closest(selector: string): Element | null;\n getAttribute(qualifiedName: string): string | null;\n getAttributeNS(namespaceURI: string, localName: string): string;\n getAttributeNode(name: string): Attr | null;\n getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n getElementsByClassName(classNames: string): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n hasAttribute(name: string): boolean;\n hasAttributeNS(namespaceURI: string, localName: string): boolean;\n hasAttributes(): boolean;\n insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null;\n insertAdjacentHTML(where: InsertPosition, html: string): void;\n insertAdjacentText(where: InsertPosition, text: string): void;\n matches(selectors: string): boolean;\n msGetRegionContent(): any;\n msGetUntransformedBounds(): ClientRect;\n msMatchesSelector(selectors: string): boolean;\n msReleasePointerCapture(pointerId: number): void;\n msSetPointerCapture(pointerId: number): void;\n msZoomTo(args: MsZoomToOptions): void;\n releasePointerCapture(pointerId: number): void;\n removeAttribute(qualifiedName: string): void;\n removeAttributeNS(namespaceURI: string, localName: string): void;\n removeAttributeNode(oldAttr: Attr): Attr;\n requestFullscreen(): void;\n requestPointerLock(): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x: number, y: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x: number, y: number): void;\n scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x: number, y: number): void;\n setAttribute(qualifiedName: string, value: string): void;\n setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;\n setAttributeNode(newAttr: Attr): Attr;\n setAttributeNodeNS(newAttr: Attr): Attr;\n setPointerCapture(pointerId: number): void;\n webkitMatchesSelector(selectors: string): boolean;\n webkitRequestFullScreen(): void;\n webkitRequestFullscreen(): void;\n addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Element: {\n prototype: Element;\n new(): Element;\n};\n\ninterface ElementCSSInlineStyle {\n readonly style: CSSStyleDeclaration;\n}\n\ninterface ElementCreationOptions {\n is?: string;\n}\n\ninterface ElementDefinitionOptions {\n extends: string;\n}\n\ninterface ElementTraversal {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n readonly nextElementSibling: Element | null;\n readonly previousElementSibling: Element | null;\n}\n\ninterface ErrorEvent extends Event {\n readonly colno: number;\n readonly error: any;\n readonly filename: string;\n readonly lineno: number;\n readonly message: string;\n initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;\n}\n\ndeclare var ErrorEvent: {\n prototype: ErrorEvent;\n new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent;\n};\n\ninterface Event {\n readonly bubbles: boolean;\n cancelBubble: boolean;\n readonly cancelable: boolean;\n readonly currentTarget: EventTarget | null;\n readonly defaultPrevented: boolean;\n readonly eventPhase: number;\n readonly isTrusted: boolean;\n returnValue: boolean;\n readonly scoped: boolean;\n readonly srcElement: Element | null;\n readonly target: EventTarget | null;\n readonly timeStamp: number;\n readonly type: string;\n deepPath(): EventTarget[];\n initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;\n preventDefault(): void;\n stopImmediatePropagation(): void;\n stopPropagation(): void;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n}\n\ndeclare var Event: {\n prototype: Event;\n new(typeArg: string, eventInitDict?: EventInit): Event;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n};\n\ninterface EventListenerObject {\n handleEvent(evt: Event): void;\n}\n\ninterface EventSource extends EventTarget {\n readonly CLOSED: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n onerror: (evt: MessageEvent) => any;\n onmessage: (evt: MessageEvent) => any;\n onopen: (evt: MessageEvent) => any;\n readonly readyState: number;\n readonly url: string;\n readonly withCredentials: boolean;\n close(): void;\n}\n\ndeclare var EventSource: {\n prototype: EventSource;\n new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;\n};\n\ninterface EventSourceInit {\n readonly withCredentials: boolean;\n}\n\ninterface EventTarget {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;\n dispatchEvent(evt: Event): boolean;\n removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;\n}\n\ndeclare var EventTarget: {\n prototype: EventTarget;\n new(): EventTarget;\n};\n\ninterface ExtensionScriptApis {\n extensionIdToShortId(extensionId: string): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n genericWebRuntimeCallout(to: any, from: any, payload: string): void;\n getExtensionId(): string;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericPersistentCallbackHandler(callbackHandler: Function): void;\n registerWebRuntimeCallbackHandler(handler: Function): any;\n}\n\ndeclare var ExtensionScriptApis: {\n prototype: ExtensionScriptApis;\n new(): ExtensionScriptApis;\n};\n\ninterface External {\n}\n\ndeclare var External: {\n prototype: External;\n new(): External;\n};\n\ninterface File extends Blob {\n readonly lastModified: number;\n /** @deprecated */\n readonly lastModifiedDate: Date;\n readonly name: string;\n readonly webkitRelativePath: string;\n}\n\ndeclare var File: {\n prototype: File;\n new (parts: (ArrayBuffer | ArrayBufferView | Blob | string)[], filename: string, properties?: FilePropertyBag): File;\n};\n\ninterface FileList {\n readonly length: number;\n item(index: number): File | null;\n [index: number]: File;\n}\n\ndeclare var FileList: {\n prototype: FileList;\n new(): FileList;\n};\n\ninterface FilePropertyBag extends BlobPropertyBag {\n lastModified?: number;\n}\n\ninterface FileReaderEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n}\n\ninterface FileReader extends EventTarget {\n readonly error: DOMException | null;\n onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onerror: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onload: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: any;\n abort(): void;\n readAsArrayBuffer(blob: Blob): void;\n readAsBinaryString(blob: Blob): void;\n readAsDataURL(blob: Blob): void;\n readAsText(blob: Blob, label?: string): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var FileReader: {\n prototype: FileReader;\n new(): FileReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface FocusEvent extends UIEvent {\n readonly relatedTarget: EventTarget;\n initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void;\n}\n\ndeclare var FocusEvent: {\n prototype: FocusEvent;\n new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent;\n};\n\ninterface FocusNavigationEvent extends Event {\n readonly navigationReason: NavigationReason;\n readonly originHeight: number;\n readonly originLeft: number;\n readonly originTop: number;\n readonly originWidth: number;\n requestFocus(): void;\n}\n\ndeclare var FocusNavigationEvent: {\n prototype: FocusNavigationEvent;\n new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent;\n};\n\ninterface FormData {\n append(name: string, value: string | Blob, fileName?: string): void;\n delete(name: string): void;\n get(name: string): FormDataEntryValue | null;\n getAll(name: string): FormDataEntryValue[];\n has(name: string): boolean;\n set(name: string, value: string | Blob, fileName?: string): void;\n}\n\ndeclare var FormData: {\n prototype: FormData;\n new(): FormData;\n new(form: HTMLFormElement): FormData;\n};\n\ninterface GainNode extends AudioNode {\n readonly gain: AudioParam;\n}\n\ndeclare var GainNode: {\n prototype: GainNode;\n new(): GainNode;\n};\n\ninterface Gamepad {\n readonly axes: number[];\n readonly buttons: GamepadButton[];\n readonly connected: boolean;\n readonly displayId: number;\n readonly hand: GamepadHand;\n readonly hapticActuators: GamepadHapticActuator[];\n readonly id: string;\n readonly index: number;\n readonly mapping: GamepadMappingType;\n readonly pose: GamepadPose | null;\n readonly timestamp: number;\n}\n\ndeclare var Gamepad: {\n prototype: Gamepad;\n new(): Gamepad;\n};\n\ninterface GamepadButton {\n readonly pressed: boolean;\n readonly touched: boolean;\n readonly value: number;\n}\n\ndeclare var GamepadButton: {\n prototype: GamepadButton;\n new(): GamepadButton;\n};\n\ninterface GamepadEvent extends Event {\n readonly gamepad: Gamepad;\n}\n\ndeclare var GamepadEvent: {\n prototype: GamepadEvent;\n new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent;\n};\n\ninterface GamepadHapticActuator {\n readonly type: GamepadHapticActuatorType;\n pulse(value: number, duration: number): Promise;\n}\n\ndeclare var GamepadHapticActuator: {\n prototype: GamepadHapticActuator;\n new(): GamepadHapticActuator;\n};\n\ninterface GamepadPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n}\n\ndeclare var GamepadPose: {\n prototype: GamepadPose;\n new(): GamepadPose;\n};\n\ninterface Geolocation {\n clearWatch(watchId: number): void;\n getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;\n watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;\n}\n\ndeclare var Geolocation: {\n prototype: Geolocation;\n new(): Geolocation;\n};\n\ninterface GetSVGDocument {\n getSVGDocument(): Document;\n}\n\ninterface GlobalEventHandlersEventMap {\n \"pointercancel\": PointerEvent;\n \"pointerdown\": PointerEvent;\n \"pointerenter\": PointerEvent;\n \"pointerleave\": PointerEvent;\n \"pointermove\": PointerEvent;\n \"pointerout\": PointerEvent;\n \"pointerover\": PointerEvent;\n \"pointerup\": PointerEvent;\n \"wheel\": WheelEvent;\n}\n\ninterface GlobalEventHandlers {\n onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null;\n addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface GlobalFetch {\n fetch(input?: Request | string, init?: RequestInit): Promise;\n}\n\ninterface HTMLAllCollection {\n readonly length: number;\n item(nameOrIndex?: string): HTMLCollection | Element | null;\n namedItem(name: string): HTMLCollection | Element | null;\n [index: number]: Element;\n}\n\ndeclare var HTMLAllCollection: {\n prototype: HTMLAllCollection;\n new(): HTMLAllCollection;\n};\n\ninterface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {\n Methods: string;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n /** @deprecated */\n coords: string;\n download: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n readonly mimeType: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n readonly nameProp: string;\n readonly protocolLong: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n type: string;\n urn: string;\n addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAnchorElement: {\n prototype: HTMLAnchorElement;\n new(): HTMLAnchorElement;\n};\n\ninterface HTMLAppletElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n /** @deprecated */\n alt: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n /** @deprecated */\n object: string;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAppletElement: {\n prototype: HTMLAppletElement;\n new(): HTMLAppletElement;\n};\n\ninterface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n coords: string;\n download: string;\n /**\n * Sets or gets whether clicks in this region cause action.\n */\n /** @deprecated */\n noHref: boolean;\n rel: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAreaElement: {\n prototype: HTMLAreaElement;\n new(): HTMLAreaElement;\n};\n\ninterface HTMLAreasCollection extends HTMLCollectionBase {\n}\n\ndeclare var HTMLAreasCollection: {\n prototype: HTMLAreasCollection;\n new(): HTMLAreasCollection;\n};\n\ninterface HTMLAudioElement extends HTMLMediaElement {\n addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAudioElement: {\n prototype: HTMLAudioElement;\n new(): HTMLAudioElement;\n};\n\ninterface HTMLBRElement extends HTMLElement {\n /**\n * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document.\n */\n /** @deprecated */\n clear: string;\n addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBRElement: {\n prototype: HTMLBRElement;\n new(): HTMLBRElement;\n};\n\ninterface HTMLBaseElement extends HTMLElement {\n /**\n * Gets or sets the baseline URL on which relative links are based.\n */\n href: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseElement: {\n prototype: HTMLBaseElement;\n new(): HTMLBaseElement;\n};\n\ninterface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /**\n * Sets or retrieves the font size of the object.\n */\n /** @deprecated */\n size: number;\n addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseFontElement: {\n prototype: HTMLBaseFontElement;\n new(): HTMLBaseFontElement;\n};\n\ninterface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLBodyElement extends HTMLElement, WindowEventHandlers {\n /** @deprecated */\n aLink: string;\n /** @deprecated */\n background: string;\n /** @deprecated */\n bgColor: string;\n bgProperties: string;\n /** @deprecated */\n link: string;\n /** @deprecated */\n noWrap: boolean;\n onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null;\n onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null;\n /** @deprecated */\n text: string;\n /** @deprecated */\n vLink: string;\n addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBodyElement: {\n prototype: HTMLBodyElement;\n new(): HTMLBodyElement;\n};\n\ninterface HTMLButtonElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n status: any;\n /**\n * Gets the classification and default behavior of the button.\n */\n type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the default or selected value of the control.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLButtonElement: {\n prototype: HTMLButtonElement;\n new(): HTMLButtonElement;\n};\n\ninterface HTMLCanvasElement extends HTMLElement {\n /**\n * Gets or sets the height of a canvas element on a document.\n */\n height: number;\n /**\n * Gets or sets the width of a canvas element on a document.\n */\n width: number;\n /**\n * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.\n * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext(\"2d\"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext(\"experimental-webgl\");\n */\n getContext(contextId: \"2d\", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null;\n getContext(contextId: \"webgl\" | \"experimental-webgl\", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null;\n getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null;\n /**\n * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.\n */\n msToBlob(): Blob;\n toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void;\n /**\n * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element.\n * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.\n */\n toDataURL(type?: string, ...args: any[]): string;\n addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLCanvasElement: {\n prototype: HTMLCanvasElement;\n new(): HTMLCanvasElement;\n};\n\ninterface HTMLCollectionBase {\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Retrieves an object from various collections.\n */\n item(index: number): Element;\n [index: number]: Element;\n}\n\ninterface HTMLCollection extends HTMLCollectionBase {\n /**\n * Retrieves a select object or an object from an options collection.\n */\n namedItem(name: string): Element | null;\n}\n\ndeclare var HTMLCollection: {\n prototype: HTMLCollection;\n new(): HTMLCollection;\n};\n\ninterface HTMLCollectionOf extends HTMLCollectionBase {\n item(index: number): T;\n namedItem(name: string): T;\n [index: number]: T;\n}\n\ninterface HTMLDListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDListElement: {\n prototype: HTMLDListElement;\n new(): HTMLDListElement;\n};\n\ninterface HTMLDataElement extends HTMLElement {\n value: string;\n addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataElement: {\n prototype: HTMLDataElement;\n new(): HTMLDataElement;\n};\n\ninterface HTMLDataListElement extends HTMLElement {\n readonly options: HTMLCollectionOf;\n addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataListElement: {\n prototype: HTMLDataListElement;\n new(): HTMLDataListElement;\n};\n\ninterface HTMLDetailsElement extends HTMLElement {\n open: boolean;\n addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDetailsElement: {\n prototype: HTMLDetailsElement;\n new(): HTMLDetailsElement;\n};\n\ninterface HTMLDialogElement extends HTMLElement {\n open: boolean;\n returnValue: string;\n close(returnValue?: string): void;\n show(): void;\n showModal(): void;\n addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDialogElement: {\n prototype: HTMLDialogElement;\n new(): HTMLDialogElement;\n};\n\ninterface HTMLDirectoryElement extends HTMLElement {\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDirectoryElement: {\n prototype: HTMLDirectoryElement;\n new(): HTMLDirectoryElement;\n};\n\ninterface HTMLDivElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n noWrap: boolean;\n addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDivElement: {\n prototype: HTMLDivElement;\n new(): HTMLDivElement;\n};\n\ninterface HTMLDocument extends Document {\n addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDocument: {\n prototype: HTMLDocument;\n new(): HTMLDocument;\n};\n\ninterface HTMLElementEventMap extends ElementEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforecopy\": Event;\n \"beforecut\": Event;\n \"beforedeactivate\": Event;\n \"beforepaste\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"copy\": ClipboardEvent;\n \"cuechange\": Event;\n \"cut\": ClipboardEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSManipulationStateChanged\": Event;\n \"paste\": ClipboardEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n}\n\ninterface HTMLElement extends Element, ElementCSSInlineStyle {\n accessKey: string;\n contentEditable: string;\n readonly dataset: DOMStringMap;\n dir: string;\n draggable: boolean;\n hidden: boolean;\n hideFocus: boolean;\n innerText: string;\n readonly isContentEditable: boolean;\n lang: string;\n readonly offsetHeight: number;\n readonly offsetLeft: number;\n readonly offsetParent: Element;\n readonly offsetTop: number;\n readonly offsetWidth: number;\n onabort: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecut: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null;\n onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oncanplay: ((this: HTMLElement, ev: Event) => any) | null;\n oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null;\n onchange: ((this: HTMLElement, ev: Event) => any) | null;\n onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null;\n oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n oncuechange: ((this: HTMLElement, ev: Event) => any) | null;\n oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n ondeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondurationchange: ((this: HTMLElement, ev: Event) => any) | null;\n onemptied: ((this: HTMLElement, ev: Event) => any) | null;\n onended: ((this: HTMLElement, ev: Event) => any) | null;\n onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null;\n onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oninput: ((this: HTMLElement, ev: Event) => any) | null;\n oninvalid: ((this: HTMLElement, ev: Event) => any) | null;\n onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onload: ((this: HTMLElement, ev: Event) => any) | null;\n onloadeddata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadstart: ((this: HTMLElement, ev: Event) => any) | null;\n onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null;\n onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n onpause: ((this: HTMLElement, ev: Event) => any) | null;\n onplay: ((this: HTMLElement, ev: Event) => any) | null;\n onplaying: ((this: HTMLElement, ev: Event) => any) | null;\n onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null;\n onratechange: ((this: HTMLElement, ev: Event) => any) | null;\n onreset: ((this: HTMLElement, ev: Event) => any) | null;\n onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onseeked: ((this: HTMLElement, ev: Event) => any) | null;\n onseeking: ((this: HTMLElement, ev: Event) => any) | null;\n onselect: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onselectstart: ((this: HTMLElement, ev: Event) => any) | null;\n onstalled: ((this: HTMLElement, ev: Event) => any) | null;\n onsubmit: ((this: HTMLElement, ev: Event) => any) | null;\n onsuspend: ((this: HTMLElement, ev: Event) => any) | null;\n ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null;\n onvolumechange: ((this: HTMLElement, ev: Event) => any) | null;\n onwaiting: ((this: HTMLElement, ev: Event) => any) | null;\n outerText: string;\n spellcheck: boolean;\n tabIndex: number;\n title: string;\n animate(keyframes: AnimationKeyFrame | AnimationKeyFrame[], options: number | AnimationOptions): Animation;\n blur(): void;\n click(): void;\n dragDrop(): boolean;\n focus(): void;\n msGetInputContext(): MSInputMethodContext;\n addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLElement: {\n prototype: HTMLElement;\n new(): HTMLElement;\n};\n\ninterface HTMLEmbedElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n hidden: any;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * Retrieves the palette used for the embedded document.\n */\n readonly palette: string;\n /**\n * Retrieves the URL of the plug-in used to view an embedded document.\n */\n readonly pluginspage: string;\n readonly readyState: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrieves the height and width units of the embed object.\n */\n units: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLEmbedElement: {\n prototype: HTMLEmbedElement;\n new(): HTMLEmbedElement;\n};\n\ninterface HTMLFieldSetElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n align: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n name: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFieldSetElement: {\n prototype: HTMLFieldSetElement;\n new(): HTMLFieldSetElement;\n};\n\ninterface HTMLFontElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFontElement: {\n prototype: HTMLFontElement;\n new(): HTMLFontElement;\n};\n\ninterface HTMLFormControlsCollection extends HTMLCollectionBase {\n namedItem(name: string): HTMLCollection | Element | null;\n}\n\ndeclare var HTMLFormControlsCollection: {\n prototype: HTMLFormControlsCollection;\n new(): HTMLFormControlsCollection;\n};\n\ninterface HTMLFormElement extends HTMLElement {\n /**\n * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form.\n */\n acceptCharset: string;\n /**\n * Sets or retrieves the URL to which the form content is sent for processing.\n */\n action: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Retrieves a collection, in source order, of all controls in a given form.\n */\n readonly elements: HTMLFormControlsCollection;\n /**\n * Sets or retrieves the MIME encoding for the form.\n */\n encoding: string;\n /**\n * Sets or retrieves the encoding type for the form.\n */\n enctype: string;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Sets or retrieves how to send the form data to the server.\n */\n method: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Designates a form that is not validated when submitted.\n */\n noValidate: boolean;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a form object or an object from an elements collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): any;\n /**\n * Retrieves a form object or an object from an elements collection.\n */\n namedItem(name: string): any;\n reportValidity(): boolean;\n /**\n * Fires when the user resets a form.\n */\n reset(): void;\n /**\n * Fires when a FORM is about to be submitted.\n */\n submit(): void;\n addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLFormElement: {\n prototype: HTMLFormElement;\n new(): HTMLFormElement;\n};\n\ninterface HTMLFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Specifies the properties of a border drawn around an object.\n */\n border: string;\n /**\n * Sets or retrieves the border color of the object.\n */\n borderColor: any;\n /**\n * Retrieves the document object of the page or frame.\n */\n /** @deprecated */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n /** @deprecated */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the amount of additional space between the frames.\n */\n frameSpacing: any;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string | number;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n /** @deprecated */\n name: string;\n /**\n * Sets or retrieves whether the user can resize the frame.\n */\n /** @deprecated */\n noResize: boolean;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n /** @deprecated */\n src: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string | number;\n addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameElement: {\n prototype: HTMLFrameElement;\n new(): HTMLFrameElement;\n};\n\ninterface HTMLFrameSetElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers {\n /**\n * Sets or retrieves the frame widths of the object.\n */\n /** @deprecated */\n cols: string;\n name: string;\n onorientationchange: ((this: HTMLFrameSetElement, ev: Event) => any) | null;\n onresize: ((this: HTMLFrameSetElement, ev: UIEvent) => any) | null;\n /**\n * Sets or retrieves the frame heights of the object.\n */\n /** @deprecated */\n rows: string;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLFrameSetElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameSetElement: {\n prototype: HTMLFrameSetElement;\n new(): HTMLFrameSetElement;\n};\n\ninterface HTMLHRElement extends HTMLElement, DOML2DeprecatedColorProperty, DOML2DeprecatedSizeProperty {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the horizontal rule is drawn with 3-D shading.\n */\n /** @deprecated */\n noShade: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHRElement: {\n prototype: HTMLHRElement;\n new(): HTMLHRElement;\n};\n\ninterface HTMLHeadElement extends HTMLElement {\n /** @deprecated */\n profile: string;\n addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadElement: {\n prototype: HTMLHeadElement;\n new(): HTMLHeadElement;\n};\n\ninterface HTMLHeadingElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadingElement: {\n prototype: HTMLHeadingElement;\n new(): HTMLHeadingElement;\n};\n\ninterface HTMLHtmlElement extends HTMLElement {\n /**\n * Sets or retrieves the DTD version that governs the current document.\n */\n /** @deprecated */\n version: string;\n addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHtmlElement: {\n prototype: HTMLHtmlElement;\n new(): HTMLHtmlElement;\n};\n\ninterface HTMLHyperlinkElementUtils {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n toString(): string;\n}\n\ninterface HTMLIFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLIFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n allowFullscreen: boolean;\n allowPaymentRequest: boolean;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n name: string;\n readonly sandbox: DOMTokenList;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrives the content of the page that is to contain.\n */\n srcdoc: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLIFrameElement: {\n prototype: HTMLIFrameElement;\n new(): HTMLIFrameElement;\n};\n\ninterface HTMLImageElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies the properties of a border drawn around an object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves whether the object is fully loaded.\n */\n readonly complete: boolean;\n crossOrigin: string | null;\n readonly currentSrc: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves whether the image is a server-side image map.\n */\n isMap: boolean;\n /**\n * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object.\n */\n longDesc: string;\n /** @deprecated */\n lowsrc: string;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * The original height of the image resource before sizing.\n */\n readonly naturalHeight: number;\n /**\n * The original width of the image resource before sizing.\n */\n readonly naturalWidth: number;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Sets or retrieves the vertical margin for the object.\n */\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n readonly x: number;\n readonly y: number;\n msGetAsCastingSource(): any;\n addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLImageElement: {\n prototype: HTMLImageElement;\n new(): HTMLImageElement;\n};\n\ninterface HTMLInputElement extends HTMLElement {\n /**\n * Sets or retrieves a comma-separated list of content types.\n */\n accept: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n checked: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n defaultChecked: boolean;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Returns a FileList object on a file type input object.\n */\n readonly files: FileList | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n indeterminate: boolean;\n /**\n * Specifies the ID of a pre-defined datalist of options for an input element.\n */\n readonly list: HTMLElement | null;\n /**\n * Defines the maximum acceptable value for an input element with type=\"number\".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field.\n */\n max: string;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n /**\n * Defines the minimum acceptable value for an input element with type=\"number\". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field.\n */\n min: string;\n minLength: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a string containing a regular expression that the user's input must match.\n */\n pattern: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n selectionDirection: string | null;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number | null;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number | null;\n size: number;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n /**\n * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field.\n */\n step: string;\n /**\n * Returns the content type of the object.\n */\n type: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n /** @deprecated */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns the value of the data at the cursor's current position.\n */\n value: string;\n valueAsDate: any;\n /**\n * Returns the input field value as a number.\n */\n valueAsNumber: number;\n webkitdirectory: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Makes the selection equal to the current object.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n /**\n * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value.\n * @param n Value to decrement the value by.\n */\n stepDown(n?: number): void;\n /**\n * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value.\n * @param n Value to increment the value by.\n */\n stepUp(n?: number): void;\n addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLInputElement: {\n prototype: HTMLInputElement;\n new(): HTMLInputElement;\n};\n\ninterface HTMLLIElement extends HTMLElement {\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of a list item.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLIElement: {\n prototype: HTMLLIElement;\n new(): HTMLLIElement;\n};\n\ninterface HTMLLabelElement extends HTMLElement {\n readonly control: HTMLInputElement | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the object to which the given label object is assigned.\n */\n htmlFor: string;\n addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLabelElement: {\n prototype: HTMLLabelElement;\n new(): HTMLLabelElement;\n};\n\ninterface HTMLLegendElement extends HTMLElement {\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n /** @deprecated */\n align: string;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLegendElement: {\n prototype: HTMLLegendElement;\n new(): HTMLLegendElement;\n};\n\ninterface HTMLLinkElement extends HTMLElement, LinkStyle {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves a destination URL or an anchor point.\n */\n href: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n import?: Document;\n integrity: string;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n /** @deprecated */\n target: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLinkElement: {\n prototype: HTMLLinkElement;\n new(): HTMLLinkElement;\n};\n\ninterface HTMLMainElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMainElement: {\n prototype: HTMLMainElement;\n new(): HTMLMainElement;\n};\n\ninterface HTMLMapElement extends HTMLElement {\n /**\n * Retrieves a collection of the area objects defined for the given map object.\n */\n readonly areas: HTMLAreasCollection;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMapElement: {\n prototype: HTMLMapElement;\n new(): HTMLMapElement;\n};\n\ninterface HTMLMarqueeElementEventMap extends HTMLElementEventMap {\n \"bounce\": Event;\n \"finish\": Event;\n \"start\": Event;\n}\n\ninterface HTMLMarqueeElement extends HTMLElement {\n /** @deprecated */\n behavior: string;\n /** @deprecated */\n bgColor: string;\n /** @deprecated */\n direction: string;\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /** @deprecated */\n loop: number;\n /** @deprecated */\n onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n scrollAmount: number;\n /** @deprecated */\n scrollDelay: number;\n /** @deprecated */\n trueSpeed: boolean;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n /** @deprecated */\n start(): void;\n /** @deprecated */\n stop(): void;\n addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMarqueeElement: {\n prototype: HTMLMarqueeElement;\n new(): HTMLMarqueeElement;\n};\n\ninterface HTMLMediaElementEventMap extends HTMLElementEventMap {\n \"encrypted\": MediaEncryptedEvent;\n \"msneedkey\": Event;\n}\n\ninterface HTMLMediaElement extends HTMLElement {\n /**\n * Returns an AudioTrackList object with the audio tracks for a given video element.\n */\n readonly audioTracks: AudioTrackList;\n /**\n * Gets or sets a value that indicates whether to start playing the media automatically.\n */\n autoplay: boolean;\n /**\n * Gets a collection of buffered time ranges.\n */\n readonly buffered: TimeRanges;\n /**\n * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player).\n */\n controls: boolean;\n crossOrigin: string | null;\n /**\n * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement.\n */\n readonly currentSrc: string;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n currentTime: number;\n defaultMuted: boolean;\n /**\n * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource.\n */\n defaultPlaybackRate: number;\n /**\n * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming.\n */\n readonly duration: number;\n /**\n * Gets information about whether the playback has ended or not.\n */\n readonly ended: boolean;\n /**\n * Returns an object representing the current error state of the audio or video element.\n */\n readonly error: MediaError | null;\n /**\n * Gets or sets a flag to specify whether playback should restart after it completes.\n */\n loop: boolean;\n readonly mediaKeys: MediaKeys | null;\n /**\n * Specifies the purpose of the audio or video media, such as background audio or alerts.\n */\n msAudioCategory: string;\n /**\n * Specifies the output device id that the audio will be sent to.\n */\n msAudioDeviceType: string;\n readonly msGraphicsTrustStatus: MSGraphicsTrust;\n /**\n * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element.\n */\n /** @deprecated */\n readonly msKeys: MSMediaKeys;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Specifies whether or not to enable low-latency playback on the media element.\n */\n msRealTime: boolean;\n /**\n * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted.\n */\n muted: boolean;\n /**\n * Gets the current network activity for the element.\n */\n readonly networkState: number;\n onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null;\n /** @deprecated */\n onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null;\n /**\n * Gets a flag that specifies whether playback is paused.\n */\n readonly paused: boolean;\n /**\n * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource.\n */\n playbackRate: number;\n /**\n * Gets TimeRanges for the current media resource that has been played.\n */\n readonly played: TimeRanges;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n preload: string;\n readonly readyState: number;\n /**\n * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.\n */\n readonly seekable: TimeRanges;\n /**\n * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource.\n */\n readonly seeking: boolean;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcObject: MediaStream | MediaSource | Blob | null;\n readonly textTracks: TextTrackList;\n readonly videoTracks: VideoTrackList;\n /**\n * Gets or sets the volume level for audio portions of the media element.\n */\n volume: number;\n addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack;\n /**\n * Returns a string that specifies whether the client can play a given media resource type.\n */\n canPlayType(type: string): CanPlayTypeResult;\n /**\n * Resets the audio or video object and loads a new media resource.\n */\n load(): void;\n /**\n * Clears all effects from the media pipeline.\n */\n msClearEffects(): void;\n msGetAsCastingSource(): any;\n /**\n * Inserts the specified audio effect into media pipeline.\n */\n msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n /** @deprecated */\n msSetMediaKeys(mediaKeys: MSMediaKeys): void;\n /**\n * Specifies the media protection manager for a given media pipeline.\n */\n msSetMediaProtectionManager(mediaProtectionManager?: any): void;\n /**\n * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not.\n */\n pause(): void;\n /**\n * Loads and starts playback of a media resource.\n */\n play(): Promise;\n setMediaKeys(mediaKeys: MediaKeys | null): Promise;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMediaElement: {\n prototype: HTMLMediaElement;\n new(): HTMLMediaElement;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n};\n\ninterface HTMLMenuElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n type: string;\n addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMenuElement: {\n prototype: HTMLMenuElement;\n new(): HTMLMenuElement;\n};\n\ninterface HTMLMetaElement extends HTMLElement {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Gets or sets meta-information to associate with httpEquiv or name.\n */\n content: string;\n /**\n * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header.\n */\n httpEquiv: string;\n /**\n * Sets or retrieves the value specified in the content attribute of the meta object.\n */\n name: string;\n /**\n * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object.\n */\n /** @deprecated */\n scheme: string;\n /**\n * Sets or retrieves the URL property that will be loaded after the specified time has elapsed.\n */\n /** @deprecated */\n url: string;\n addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMetaElement: {\n prototype: HTMLMetaElement;\n new(): HTMLMetaElement;\n};\n\ninterface HTMLMeterElement extends HTMLElement {\n high: number;\n low: number;\n max: number;\n min: number;\n optimum: number;\n value: number;\n addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMeterElement: {\n prototype: HTMLMeterElement;\n new(): HTMLMeterElement;\n};\n\ninterface HTMLModElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n /**\n * Sets or retrieves the date and time of a modification to the object.\n */\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLModElement: {\n prototype: HTMLModElement;\n new(): HTMLModElement;\n};\n\ninterface HTMLOListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /**\n * The starting number.\n */\n start: number;\n type: string;\n addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOListElement: {\n prototype: HTMLOListElement;\n new(): HTMLOListElement;\n};\n\ninterface HTMLObjectElement extends HTMLElement, GetSVGDocument {\n /**\n * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element.\n */\n readonly BaseHref: string;\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n border: string;\n /**\n * Sets or retrieves the URL of the file containing the compiled Java class.\n */\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n /**\n * Sets or retrieves the Internet media type for the code associated with the object.\n */\n /** @deprecated */\n codeType: string;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Sets or retrieves the URL that references the data of the object.\n */\n data: string;\n /** @deprecated */\n declare: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly readyState: number;\n /**\n * Sets or retrieves a message to be displayed while an object is loading.\n */\n /** @deprecated */\n standby: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n typemustmatch: boolean;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLObjectElement: {\n prototype: HTMLObjectElement;\n new(): HTMLObjectElement;\n};\n\ninterface HTMLOptGroupElement extends HTMLElement {\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptGroupElement: {\n prototype: HTMLOptGroupElement;\n new(): HTMLOptGroupElement;\n};\n\ninterface HTMLOptionElement extends HTMLElement {\n /**\n * Sets or retrieves the status of an option.\n */\n defaultSelected: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the ordinal position of an option in a list box.\n */\n readonly index: number;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n /**\n * Sets or retrieves whether the option in the list box is the default item.\n */\n selected: boolean;\n /**\n * Sets or retrieves the text string specified by the option tag.\n */\n text: string;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptionElement: {\n prototype: HTMLOptionElement;\n new(): HTMLOptionElement;\n};\n\ninterface HTMLOptionsCollection extends HTMLCollectionOf {\n length: number;\n selectedIndex: number;\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void;\n remove(index: number): void;\n}\n\ndeclare var HTMLOptionsCollection: {\n prototype: HTMLOptionsCollection;\n new(): HTMLOptionsCollection;\n};\n\ninterface HTMLOutputElement extends HTMLElement {\n defaultValue: string;\n readonly form: HTMLFormElement | null;\n readonly htmlFor: DOMTokenList;\n name: string;\n readonly type: string;\n readonly validationMessage: string;\n readonly validity: ValidityState;\n value: string;\n readonly willValidate: boolean;\n checkValidity(): boolean;\n reportValidity(): boolean;\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOutputElement: {\n prototype: HTMLOutputElement;\n new(): HTMLOutputElement;\n};\n\ninterface HTMLParagraphElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n clear: string;\n addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParagraphElement: {\n prototype: HTMLParagraphElement;\n new(): HTMLParagraphElement;\n};\n\ninterface HTMLParamElement extends HTMLElement {\n /**\n * Sets or retrieves the name of an input parameter for an element.\n */\n name: string;\n /**\n * Sets or retrieves the content type of the resource designated by the value attribute.\n */\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of an input parameter for an element.\n */\n value: string;\n /**\n * Sets or retrieves the data type of the value attribute.\n */\n /** @deprecated */\n valueType: string;\n addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParamElement: {\n prototype: HTMLParamElement;\n new(): HTMLParamElement;\n};\n\ninterface HTMLPictureElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPictureElement: {\n prototype: HTMLPictureElement;\n new(): HTMLPictureElement;\n};\n\ninterface HTMLPreElement extends HTMLElement {\n /**\n * Sets or gets a value that you can use to implement your own width functionality for the object.\n */\n /** @deprecated */\n width: number;\n addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPreElement: {\n prototype: HTMLPreElement;\n new(): HTMLPreElement;\n};\n\ninterface HTMLProgressElement extends HTMLElement {\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Defines the maximum, or \"done\" value for a progress element.\n */\n max: number;\n /**\n * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar).\n */\n readonly position: number;\n /**\n * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLProgressElement: {\n prototype: HTMLProgressElement;\n new(): HTMLProgressElement;\n};\n\ninterface HTMLQuoteElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLQuoteElement: {\n prototype: HTMLQuoteElement;\n new(): HTMLQuoteElement;\n};\n\ninterface HTMLScriptElement extends HTMLElement {\n async: boolean;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n charset: string;\n crossOrigin: string | null;\n /**\n * Sets or retrieves the status of the script.\n */\n defer: boolean;\n /**\n * Sets or retrieves the event for which the script is written.\n */\n /** @deprecated */\n event: string;\n /**\n * Sets or retrieves the object that is bound to the event script.\n */\n /** @deprecated */\n htmlFor: string;\n integrity: string;\n noModule: boolean;\n /**\n * Retrieves the URL to an external file that contains the source code or data.\n */\n src: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n /**\n * Sets or retrieves the MIME type for the associated scripting engine.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLScriptElement: {\n prototype: HTMLScriptElement;\n new(): HTMLScriptElement;\n};\n\ninterface HTMLSelectElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n length: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly options: HTMLOptionsCollection;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the index of the selected option in a select object.\n */\n selectedIndex: number;\n readonly selectedOptions: HTMLCollectionOf;\n /**\n * Sets or retrieves the number of rows in the list box.\n */\n size: number;\n /**\n * Retrieves the type of select control based on the value of the MULTIPLE attribute.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Adds an element to the areas, controlRange, or options collection.\n * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.\n * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): Element | null;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made.\n */\n namedItem(name: string): any;\n /**\n * Removes an element from the collection.\n * @param index Number that specifies the zero-based index of the element to remove from the collection.\n */\n remove(index?: number): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLSelectElement: {\n prototype: HTMLSelectElement;\n new(): HTMLSelectElement;\n};\n\ninterface HTMLSlotElement extends HTMLElement {\n name: string;\n assignedNodes(options?: AssignedNodesOptions): Node[];\n addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface HTMLSourceElement extends HTMLElement {\n /**\n * Gets or sets the intended media type of the media source.\n */\n media: string;\n /** @deprecated */\n msKeySystem: string;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Gets or sets the MIME type of a media resource.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSourceElement: {\n prototype: HTMLSourceElement;\n new(): HTMLSourceElement;\n};\n\ninterface HTMLSpanElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSpanElement: {\n prototype: HTMLSpanElement;\n new(): HTMLSpanElement;\n};\n\ninterface HTMLStyleElement extends HTMLElement, LinkStyle {\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Retrieves the CSS language in which the style sheet is written.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLStyleElement: {\n prototype: HTMLStyleElement;\n new(): HTMLStyleElement;\n};\n\ninterface HTMLSummaryElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSummaryElement: {\n prototype: HTMLSummaryElement;\n new(): HTMLSummaryElement;\n};\n\ninterface HTMLTableCaptionElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the caption or legend.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCaptionElement: {\n prototype: HTMLTableCaptionElement;\n new(): HTMLTableCaptionElement;\n};\n\ninterface HTMLTableCellElement extends HTMLElement {\n /**\n * Sets or retrieves abbreviated text for the object.\n */\n abbr: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a comma-delimited list of conceptual categories associated with the object.\n */\n /** @deprecated */\n axis: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves the position of the object in the cells collection of a row.\n */\n readonly cellIndex: number;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number columns in the table that the object should span.\n */\n colSpan: number;\n /**\n * Sets or retrieves a list of header cells that provide information for the object.\n */\n headers: string;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n /** @deprecated */\n noWrap: boolean;\n /**\n * Sets or retrieves how many rows in a table the cell should span.\n */\n rowSpan: number;\n /**\n * Sets or retrieves the group of cells in a table to which the object's information applies.\n */\n scope: string;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCellElement: {\n prototype: HTMLTableCellElement;\n new(): HTMLTableCellElement;\n};\n\ninterface HTMLTableColElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the object relative to the display or table.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of columns in the group.\n */\n span: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableColElement: {\n prototype: HTMLTableColElement;\n new(): HTMLTableColElement;\n};\n\ninterface HTMLTableDataCellElement extends HTMLTableCellElement {\n addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableDataCellElement: {\n prototype: HTMLTableDataCellElement;\n new(): HTMLTableDataCellElement;\n};\n\ninterface HTMLTableElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves the caption object of a table.\n */\n caption: HTMLTableCaptionElement | null;\n /**\n * Sets or retrieves the amount of space between the border of the cell and the content of the cell.\n */\n /** @deprecated */\n cellPadding: string;\n /**\n * Sets or retrieves the amount of space between cells in a table.\n */\n /** @deprecated */\n cellSpacing: string;\n /**\n * Sets or retrieves the way the border frame around the table is displayed.\n */\n /** @deprecated */\n frame: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /**\n * Sets or retrieves which dividing lines (inner borders) are displayed.\n */\n /** @deprecated */\n rules: string;\n /**\n * Sets or retrieves a description and/or structure of the object.\n */\n /** @deprecated */\n summary: string;\n /**\n * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order.\n */\n readonly tBodies: HTMLCollectionOf;\n /**\n * Retrieves the tFoot object of the table.\n */\n tFoot: HTMLTableSectionElement | null;\n /**\n * Retrieves the tHead object of the table.\n */\n tHead: HTMLTableSectionElement | null;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n /**\n * Creates an empty caption element in the table.\n */\n createCaption(): HTMLTableCaptionElement;\n /**\n * Creates an empty tBody element in the table.\n */\n createTBody(): HTMLTableSectionElement;\n /**\n * Creates an empty tFoot element in the table.\n */\n createTFoot(): HTMLTableSectionElement;\n /**\n * Returns the tHead element object if successful, or null otherwise.\n */\n createTHead(): HTMLTableSectionElement;\n /**\n * Deletes the caption element and its contents from the table.\n */\n deleteCaption(): void;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Deletes the tFoot element and its contents from the table.\n */\n deleteTFoot(): void;\n /**\n * Deletes the tHead element and its contents from the table.\n */\n deleteTHead(): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableElement: {\n prototype: HTMLTableElement;\n new(): HTMLTableElement;\n};\n\ninterface HTMLTableHeaderCellElement extends HTMLTableCellElement {\n scope: string;\n addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableHeaderCellElement: {\n prototype: HTMLTableHeaderCellElement;\n new(): HTMLTableHeaderCellElement;\n};\n\ninterface HTMLTableRowElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves a collection of all cells in the table row.\n */\n readonly cells: HTMLCollectionOf;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Retrieves the position of the object in the rows collection for the table.\n */\n readonly rowIndex: number;\n /**\n * Retrieves the position of the object in the collection.\n */\n readonly sectionRowIndex: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified cell from the table row, as well as from the cells collection.\n * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted.\n */\n deleteCell(index?: number): void;\n /**\n * Creates a new cell in the table row, and adds the cell to the cells collection.\n * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.\n */\n insertCell(index?: number): HTMLTableDataCellElement;\n addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableRowElement: {\n prototype: HTMLTableRowElement;\n new(): HTMLTableRowElement;\n};\n\ninterface HTMLTableSectionElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableSectionElement: {\n prototype: HTMLTableSectionElement;\n new(): HTMLTableSectionElement;\n};\n\ninterface HTMLTemplateElement extends HTMLElement {\n readonly content: DocumentFragment;\n addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTemplateElement: {\n prototype: HTMLTemplateElement;\n new(): HTMLTemplateElement;\n};\n\ninterface HTMLTextAreaElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n cols: number;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n minLength: number;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n /**\n * Sets or retrieves the value indicated whether the content of the object is read-only.\n */\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n rows: number;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number;\n /**\n * Retrieves the type of control.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Retrieves or sets the text in the entry field of the textArea element.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Sets or retrieves how to handle wordwrapping in the object.\n */\n wrap: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Highlights the input area of a form element.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTextAreaElement: {\n prototype: HTMLTextAreaElement;\n new(): HTMLTextAreaElement;\n};\n\ninterface HTMLTimeElement extends HTMLElement {\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTimeElement: {\n prototype: HTMLTimeElement;\n new(): HTMLTimeElement;\n};\n\ninterface HTMLTitleElement extends HTMLElement {\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTitleElement: {\n prototype: HTMLTitleElement;\n new(): HTMLTitleElement;\n};\n\ninterface HTMLTrackElement extends HTMLElement {\n default: boolean;\n kind: string;\n label: string;\n readonly readyState: number;\n src: string;\n srclang: string;\n readonly track: TextTrack;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTrackElement: {\n prototype: HTMLTrackElement;\n new(): HTMLTrackElement;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n};\n\ninterface HTMLUListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUListElement: {\n prototype: HTMLUListElement;\n new(): HTMLUListElement;\n};\n\ninterface HTMLUnknownElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUnknownElement: {\n prototype: HTMLUnknownElement;\n new(): HTMLUnknownElement;\n};\n\ninterface HTMLVideoElementEventMap extends HTMLMediaElementEventMap {\n \"MSVideoFormatChanged\": Event;\n \"MSVideoFrameStepCompleted\": Event;\n \"MSVideoOptimalLayoutChanged\": Event;\n}\n\ninterface HTMLVideoElement extends HTMLMediaElement {\n /**\n * Gets or sets the height of the video element.\n */\n height: number;\n msHorizontalMirror: boolean;\n readonly msIsLayoutOptimalForPlayback: boolean;\n readonly msIsStereo3D: boolean;\n msStereo3DPackingMode: string;\n msStereo3DRenderMode: string;\n msZoom: boolean;\n onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n /**\n * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available.\n */\n poster: string;\n /**\n * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoHeight: number;\n /**\n * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoWidth: number;\n readonly webkitDisplayingFullscreen: boolean;\n readonly webkitSupportsFullscreen: boolean;\n /**\n * Gets or sets the width of the video element.\n */\n width: number;\n getVideoPlaybackQuality(): VideoPlaybackQuality;\n msFrameStep(forward: boolean): void;\n msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void;\n webkitEnterFullScreen(): void;\n webkitEnterFullscreen(): void;\n webkitExitFullScreen(): void;\n webkitExitFullscreen(): void;\n addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLVideoElement: {\n prototype: HTMLVideoElement;\n new(): HTMLVideoElement;\n};\n\ninterface HTMLegendElement {\n readonly form: HTMLFormElement | null;\n}\n\ndeclare var HTMLegendElement: {\n prototype: HTMLegendElement;\n new(): HTMLegendElement;\n};\n\ninterface HashChangeEvent extends Event {\n readonly newURL: string;\n readonly oldURL: string;\n}\n\ndeclare var HashChangeEvent: {\n prototype: HashChangeEvent;\n new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent;\n};\n\ninterface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n forEach(callback: Function, thisArg?: any): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n}\n\ndeclare var Headers: {\n prototype: Headers;\n new(init?: HeadersInit): Headers;\n};\n\ninterface History {\n readonly length: number;\n scrollRestoration: ScrollRestoration;\n readonly state: any;\n back(distance?: any): void;\n forward(distance?: any): void;\n go(delta?: any): void;\n pushState(data: any, title?: string, url?: string | null): void;\n replaceState(data: any, title?: string, url?: string | null): void;\n}\n\ndeclare var History: {\n prototype: History;\n new(): History;\n};\n\ninterface HkdfCtrParams extends Algorithm {\n context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n hash: string | Algorithm;\n label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface IDBArrayKey extends Array {\n}\n\ninterface IDBCursor {\n readonly direction: IDBCursorDirection;\n readonly key: IDBKeyRange | number | string | Date | IDBArrayKey;\n readonly primaryKey: any;\n readonly source: IDBObjectStore | IDBIndex;\n advance(count: number): void;\n continue(key?: IDBKeyRange | number | string | Date | IDBArrayKey): void;\n delete(): IDBRequest;\n update(value: any): IDBRequest;\n readonly NEXT: string;\n readonly NEXT_NO_DUPLICATE: string;\n readonly PREV: string;\n readonly PREV_NO_DUPLICATE: string;\n}\n\ndeclare var IDBCursor: {\n prototype: IDBCursor;\n new(): IDBCursor;\n readonly NEXT: string;\n readonly NEXT_NO_DUPLICATE: string;\n readonly PREV: string;\n readonly PREV_NO_DUPLICATE: string;\n};\n\ninterface IDBCursorWithValue extends IDBCursor {\n readonly value: any;\n}\n\ndeclare var IDBCursorWithValue: {\n prototype: IDBCursorWithValue;\n new(): IDBCursorWithValue;\n};\n\ninterface IDBDatabaseEventMap {\n \"abort\": Event;\n \"error\": Event;\n}\n\ninterface IDBDatabase extends EventTarget {\n readonly name: string;\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBDatabase, ev: Event) => any) | null;\n onerror: ((this: IDBDatabase, ev: Event) => any) | null;\n onversionchange: ((this: IDBDatabase, ev: Event) => any) | null;\n readonly version: number;\n close(): void;\n createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;\n deleteObjectStore(name: string): void;\n transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;\n addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBDatabase: {\n prototype: IDBDatabase;\n new(): IDBDatabase;\n};\n\ninterface IDBEnvironment {\n readonly indexedDB: IDBFactory;\n}\n\ninterface IDBFactory {\n cmp(first: any, second: any): number;\n deleteDatabase(name: string): IDBOpenDBRequest;\n open(name: string, version?: number): IDBOpenDBRequest;\n}\n\ndeclare var IDBFactory: {\n prototype: IDBFactory;\n new(): IDBFactory;\n};\n\ninterface IDBIndex {\n readonly keyPath: string | string[];\n multiEntry: boolean;\n readonly name: string;\n readonly objectStore: IDBObjectStore;\n readonly unique: boolean;\n count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n get(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n getKey(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n openKeyCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n}\n\ndeclare var IDBIndex: {\n prototype: IDBIndex;\n new(): IDBIndex;\n};\n\ninterface IDBKeyRange {\n readonly lower: any;\n readonly lowerOpen: boolean;\n readonly upper: any;\n readonly upperOpen: boolean;\n}\n\ndeclare var IDBKeyRange: {\n prototype: IDBKeyRange;\n new(): IDBKeyRange;\n bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;\n lowerBound(lower: any, open?: boolean): IDBKeyRange;\n only(value: any): IDBKeyRange;\n upperBound(upper: any, open?: boolean): IDBKeyRange;\n};\n\ninterface IDBObjectStore {\n autoIncrement: boolean;\n readonly indexNames: DOMStringList;\n readonly keyPath: string | string[] | null;\n readonly name: string;\n readonly transaction: IDBTransaction;\n add(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n clear(): IDBRequest;\n count(key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;\n delete(key: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n deleteIndex(indexName: string): void;\n get(key: any): IDBRequest;\n index(name: string): IDBIndex;\n openCursor(range?: IDBKeyRange | number | string | Date | IDBArrayKey, direction?: IDBCursorDirection): IDBRequest;\n put(value: any, key?: IDBKeyRange | number | string | Date | IDBArrayKey): IDBRequest;\n}\n\ndeclare var IDBObjectStore: {\n prototype: IDBObjectStore;\n new(): IDBObjectStore;\n};\n\ninterface IDBOpenDBRequestEventMap extends IDBRequestEventMap {\n \"blocked\": Event;\n \"upgradeneeded\": IDBVersionChangeEvent;\n}\n\ninterface IDBOpenDBRequest extends IDBRequest {\n onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;\n onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;\n addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBOpenDBRequest: {\n prototype: IDBOpenDBRequest;\n new(): IDBOpenDBRequest;\n};\n\ninterface IDBRequestEventMap {\n \"error\": Event;\n \"success\": Event;\n}\n\ninterface IDBRequest extends EventTarget {\n readonly error: DOMException;\n onerror: ((this: IDBRequest, ev: Event) => any) | null;\n onsuccess: ((this: IDBRequest, ev: Event) => any) | null;\n readonly readyState: IDBRequestReadyState;\n readonly result: any;\n readonly source: IDBObjectStore | IDBIndex | IDBCursor;\n readonly transaction: IDBTransaction;\n addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBRequest: {\n prototype: IDBRequest;\n new(): IDBRequest;\n};\n\ninterface IDBTransactionEventMap {\n \"abort\": Event;\n \"complete\": Event;\n \"error\": Event;\n}\n\ninterface IDBTransaction extends EventTarget {\n readonly db: IDBDatabase;\n readonly error: DOMException;\n readonly mode: IDBTransactionMode;\n onabort: ((this: IDBTransaction, ev: Event) => any) | null;\n oncomplete: ((this: IDBTransaction, ev: Event) => any) | null;\n onerror: ((this: IDBTransaction, ev: Event) => any) | null;\n abort(): void;\n objectStore(name: string): IDBObjectStore;\n readonly READ_ONLY: string;\n readonly READ_WRITE: string;\n readonly VERSION_CHANGE: string;\n addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBTransaction: {\n prototype: IDBTransaction;\n new(): IDBTransaction;\n readonly READ_ONLY: string;\n readonly READ_WRITE: string;\n readonly VERSION_CHANGE: string;\n};\n\ninterface IDBVersionChangeEvent extends Event {\n readonly newVersion: number | null;\n readonly oldVersion: number;\n}\n\ndeclare var IDBVersionChangeEvent: {\n prototype: IDBVersionChangeEvent;\n new(): IDBVersionChangeEvent;\n};\n\ninterface IIRFilterNode extends AudioNode {\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var IIRFilterNode: {\n prototype: IIRFilterNode;\n new(): IIRFilterNode;\n};\n\ninterface ImageBitmap {\n readonly height: number;\n readonly width: number;\n close(): void;\n}\n\ninterface ImageBitmapOptions {\n colorSpaceConversion?: \"none\" | \"default\";\n imageOrientation?: \"none\" | \"flipY\";\n premultiplyAlpha?: \"none\" | \"premultiply\" | \"default\";\n resizeHeight?: number;\n resizeQuality?: \"pixelated\" | \"low\" | \"medium\" | \"high\";\n resizeWidth?: number;\n}\n\ninterface ImageData {\n readonly data: Uint8ClampedArray;\n readonly height: number;\n readonly width: number;\n}\n\ndeclare var ImageData: {\n prototype: ImageData;\n new(width: number, height: number): ImageData;\n new(array: Uint8ClampedArray, width: number, height: number): ImageData;\n};\n\ninterface IntersectionObserver {\n readonly root: Element | null;\n readonly rootMargin: string;\n readonly thresholds: number[];\n disconnect(): void;\n observe(target: Element): void;\n takeRecords(): IntersectionObserverEntry[];\n unobserve(target: Element): void;\n}\n\ndeclare var IntersectionObserver: {\n prototype: IntersectionObserver;\n new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;\n};\n\ninterface IntersectionObserverEntry {\n readonly boundingClientRect: ClientRect | DOMRect;\n readonly intersectionRatio: number;\n readonly intersectionRect: ClientRect | DOMRect;\n readonly isIntersecting: boolean;\n readonly rootBounds: ClientRect | DOMRect;\n readonly target: Element;\n readonly time: number;\n}\n\ndeclare var IntersectionObserverEntry: {\n prototype: IntersectionObserverEntry;\n new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry;\n};\n\ninterface KeyboardEvent extends UIEvent {\n readonly altKey: boolean;\n /** @deprecated */\n char: string;\n /** @deprecated */\n readonly charCode: number;\n readonly code: string;\n readonly ctrlKey: boolean;\n readonly key: string;\n /** @deprecated */\n readonly keyCode: number;\n readonly location: number;\n readonly metaKey: boolean;\n readonly repeat: boolean;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly which: number;\n getModifierState(keyArg: string): boolean;\n /** @deprecated */\n initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n}\n\ndeclare var KeyboardEvent: {\n prototype: KeyboardEvent;\n new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n};\n\ninterface LinkStyle {\n readonly sheet: StyleSheet | null;\n}\n\ninterface ListeningStateChangedEvent extends Event {\n readonly label: string;\n readonly state: ListeningState;\n}\n\ndeclare var ListeningStateChangedEvent: {\n prototype: ListeningStateChangedEvent;\n new(): ListeningStateChangedEvent;\n};\n\ninterface Location {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n assign(url: string): void;\n reload(forcedReload?: boolean): void;\n replace(url: string): void;\n toString(): string;\n}\n\ndeclare var Location: {\n prototype: Location;\n new(): Location;\n};\n\ninterface MSAssertion {\n readonly id: string;\n readonly type: MSCredentialType;\n}\n\ndeclare var MSAssertion: {\n prototype: MSAssertion;\n new(): MSAssertion;\n};\n\ninterface MSBlobBuilder {\n append(data: any, endings?: string): void;\n getBlob(contentType?: string): Blob;\n}\n\ndeclare var MSBlobBuilder: {\n prototype: MSBlobBuilder;\n new(): MSBlobBuilder;\n};\n\ninterface MSCredentials {\n getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise;\n makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise;\n}\n\ndeclare var MSCredentials: {\n prototype: MSCredentials;\n new(): MSCredentials;\n};\n\ninterface MSDCCEvent extends Event {\n readonly maxFr: number;\n readonly maxFs: number;\n}\n\ndeclare var MSDCCEvent: {\n prototype: MSDCCEvent;\n new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent;\n};\n\ninterface MSDSHEvent extends Event {\n readonly sources: number[];\n readonly timestamp: number;\n}\n\ndeclare var MSDSHEvent: {\n prototype: MSDSHEvent;\n new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent;\n};\n\ninterface MSFIDOCredentialAssertion extends MSAssertion {\n readonly algorithm: string | Algorithm;\n readonly attestation: any;\n readonly publicKey: string;\n readonly transportHints: MSTransportType[];\n}\n\ndeclare var MSFIDOCredentialAssertion: {\n prototype: MSFIDOCredentialAssertion;\n new(): MSFIDOCredentialAssertion;\n};\n\ninterface MSFIDOSignature {\n readonly authnrData: string;\n readonly clientData: string;\n readonly signature: string;\n}\n\ndeclare var MSFIDOSignature: {\n prototype: MSFIDOSignature;\n new(): MSFIDOSignature;\n};\n\ninterface MSFIDOSignatureAssertion extends MSAssertion {\n readonly signature: MSFIDOSignature;\n}\n\ndeclare var MSFIDOSignatureAssertion: {\n prototype: MSFIDOSignatureAssertion;\n new(): MSFIDOSignatureAssertion;\n};\n\ninterface MSFileSaver {\n msSaveBlob(blob: any, defaultName?: string): boolean;\n msSaveOrOpenBlob(blob: any, defaultName?: string): boolean;\n}\n\ninterface MSGesture {\n target: Element;\n addPointer(pointerId: number): void;\n stop(): void;\n}\n\ndeclare var MSGesture: {\n prototype: MSGesture;\n new(): MSGesture;\n};\n\ninterface MSGestureEvent extends UIEvent {\n readonly clientX: number;\n readonly clientY: number;\n readonly expansion: number;\n readonly gestureObject: any;\n readonly hwTimestamp: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly rotation: number;\n readonly scale: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly translationX: number;\n readonly translationY: number;\n readonly velocityAngular: number;\n readonly velocityExpansion: number;\n readonly velocityX: number;\n readonly velocityY: number;\n initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n}\n\ndeclare var MSGestureEvent: {\n prototype: MSGestureEvent;\n new(): MSGestureEvent;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n};\n\ninterface MSGraphicsTrust {\n readonly constrictionActive: boolean;\n readonly status: string;\n}\n\ndeclare var MSGraphicsTrust: {\n prototype: MSGraphicsTrust;\n new(): MSGraphicsTrust;\n};\n\ninterface MSInputMethodContextEventMap {\n \"MSCandidateWindowHide\": Event;\n \"MSCandidateWindowShow\": Event;\n \"MSCandidateWindowUpdate\": Event;\n}\n\ninterface MSInputMethodContext extends EventTarget {\n readonly compositionEndOffset: number;\n readonly compositionStartOffset: number;\n oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null;\n readonly target: HTMLElement;\n getCandidateWindowClientRect(): ClientRect;\n getCompositionAlternatives(): string[];\n hasComposition(): boolean;\n isCandidateWindowVisible(): boolean;\n addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSInputMethodContext: {\n prototype: MSInputMethodContext;\n new(): MSInputMethodContext;\n};\n\ninterface MSMediaKeyError {\n readonly code: number;\n readonly systemCode: number;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n}\n\ndeclare var MSMediaKeyError: {\n prototype: MSMediaKeyError;\n new(): MSMediaKeyError;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n};\n\ninterface MSMediaKeyMessageEvent extends Event {\n readonly destinationURL: string | null;\n readonly message: Uint8Array;\n}\n\ndeclare var MSMediaKeyMessageEvent: {\n prototype: MSMediaKeyMessageEvent;\n new(): MSMediaKeyMessageEvent;\n};\n\ninterface MSMediaKeyNeededEvent extends Event {\n readonly initData: Uint8Array | null;\n}\n\ndeclare var MSMediaKeyNeededEvent: {\n prototype: MSMediaKeyNeededEvent;\n new(): MSMediaKeyNeededEvent;\n};\n\ninterface MSMediaKeySession extends EventTarget {\n readonly error: MSMediaKeyError | null;\n readonly keySystem: string;\n readonly sessionId: string;\n close(): void;\n update(key: Uint8Array): void;\n}\n\ndeclare var MSMediaKeySession: {\n prototype: MSMediaKeySession;\n new(): MSMediaKeySession;\n};\n\ninterface MSMediaKeys {\n readonly keySystem: string;\n createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession;\n}\n\ndeclare var MSMediaKeys: {\n prototype: MSMediaKeys;\n new(keySystem: string): MSMediaKeys;\n isTypeSupported(keySystem: string, type?: string | null): boolean;\n isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string;\n};\n\ninterface MSNavigatorDoNotTrack {\n confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean;\n confirmWebWideTrackingException(args: ExceptionInformation): boolean;\n removeSiteSpecificTrackingException(args: ExceptionInformation): void;\n removeWebWideTrackingException(args: ExceptionInformation): void;\n storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void;\n storeWebWideTrackingException(args: StoreExceptionsInformation): void;\n}\n\ninterface MSPointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var MSPointerEvent: {\n prototype: MSPointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent;\n};\n\ninterface MSStream {\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n}\n\ndeclare var MSStream: {\n prototype: MSStream;\n new(): MSStream;\n};\n\ninterface MSStreamReaderEventMap {\n \"abort\": UIEvent;\n \"error\": ErrorEvent;\n \"load\": Event;\n \"loadend\": ProgressEvent;\n \"loadstart\": Event;\n \"progress\": ProgressEvent;\n}\n\ninterface MSStreamReader extends EventTarget {\n readonly error: DOMError;\n onabort: ((this: MSStreamReader, ev: UIEvent) => any) | null;\n onerror: ((this: MSStreamReader, ev: ErrorEvent) => any) | null;\n onload: ((this: MSStreamReader, ev: Event) => any) | null;\n onloadend: ((this: MSStreamReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: MSStreamReader, ev: Event) => any) | null;\n onprogress: ((this: MSStreamReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: any;\n abort(): void;\n readAsArrayBuffer(stream: MSStream, size?: number): void;\n readAsBinaryString(stream: MSStream, size?: number): void;\n readAsBlob(stream: MSStream, size?: number): void;\n readAsDataURL(stream: MSStream, size?: number): void;\n readAsText(stream: MSStream, encoding?: string, size?: number): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSStreamReader, ev: MSStreamReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSStreamReader: {\n prototype: MSStreamReader;\n new(): MSStreamReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface MediaDeviceInfo {\n readonly deviceId: string;\n readonly groupId: string;\n readonly kind: MediaDeviceKind;\n readonly label: string;\n}\n\ndeclare var MediaDeviceInfo: {\n prototype: MediaDeviceInfo;\n new(): MediaDeviceInfo;\n};\n\ninterface MediaDevicesEventMap {\n \"devicechange\": Event;\n}\n\ninterface MediaDevices extends EventTarget {\n ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;\n enumerateDevices(): Promise;\n getSupportedConstraints(): MediaTrackSupportedConstraints;\n getUserMedia(constraints: MediaStreamConstraints): Promise;\n addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaDevices: {\n prototype: MediaDevices;\n new(): MediaDevices;\n};\n\ninterface MediaElementAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaElementAudioSourceNode: {\n prototype: MediaElementAudioSourceNode;\n new(): MediaElementAudioSourceNode;\n};\n\ninterface MediaEncryptedEvent extends Event {\n readonly initData: ArrayBuffer | null;\n readonly initDataType: string;\n}\n\ndeclare var MediaEncryptedEvent: {\n prototype: MediaEncryptedEvent;\n new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent;\n};\n\ninterface MediaError {\n readonly code: number;\n readonly msExtendedCode: number;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n}\n\ndeclare var MediaError: {\n prototype: MediaError;\n new(): MediaError;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n};\n\ninterface MediaKeyMessageEvent extends Event {\n readonly message: ArrayBuffer;\n readonly messageType: MediaKeyMessageType;\n}\n\ndeclare var MediaKeyMessageEvent: {\n prototype: MediaKeyMessageEvent;\n new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent;\n};\n\ninterface MediaKeySession extends EventTarget {\n readonly closed: Promise;\n readonly expiration: number;\n readonly keyStatuses: MediaKeyStatusMap;\n readonly sessionId: string;\n close(): Promise;\n generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n load(sessionId: string): Promise;\n remove(): Promise;\n update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeySession: {\n prototype: MediaKeySession;\n new(): MediaKeySession;\n};\n\ninterface MediaKeyStatusMap {\n readonly size: number;\n forEach(callback: Function, thisArg?: any): void;\n get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus;\n has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean;\n}\n\ndeclare var MediaKeyStatusMap: {\n prototype: MediaKeyStatusMap;\n new(): MediaKeyStatusMap;\n};\n\ninterface MediaKeySystemAccess {\n readonly keySystem: string;\n createMediaKeys(): Promise;\n getConfiguration(): MediaKeySystemConfiguration;\n}\n\ndeclare var MediaKeySystemAccess: {\n prototype: MediaKeySystemAccess;\n new(): MediaKeySystemAccess;\n};\n\ninterface MediaKeys {\n createSession(sessionType?: MediaKeySessionType): MediaKeySession;\n setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeys: {\n prototype: MediaKeys;\n new(): MediaKeys;\n};\n\ninterface MediaList {\n readonly length: number;\n mediaText: string;\n appendMedium(medium: string): void;\n deleteMedium(medium: string): void;\n item(index: number): string | null;\n toString(): number;\n [index: number]: string;\n}\n\ndeclare var MediaList: {\n prototype: MediaList;\n new(): MediaList;\n};\n\ninterface MediaQueryList {\n readonly matches: boolean;\n readonly media: string;\n addListener(listener: MediaQueryListListener): void;\n removeListener(listener: MediaQueryListListener): void;\n}\n\ndeclare var MediaQueryList: {\n prototype: MediaQueryList;\n new(): MediaQueryList;\n};\n\ninterface MediaSource extends EventTarget {\n readonly activeSourceBuffers: SourceBufferList;\n duration: number;\n readonly readyState: string;\n readonly sourceBuffers: SourceBufferList;\n addSourceBuffer(type: string): SourceBuffer;\n endOfStream(error?: number): void;\n removeSourceBuffer(sourceBuffer: SourceBuffer): void;\n}\n\ndeclare var MediaSource: {\n prototype: MediaSource;\n new(): MediaSource;\n isTypeSupported(type: string): boolean;\n};\n\ninterface MediaStreamEventMap {\n \"active\": Event;\n \"addtrack\": MediaStreamTrackEvent;\n \"inactive\": Event;\n \"removetrack\": MediaStreamTrackEvent;\n}\n\ninterface MediaStream extends EventTarget {\n readonly active: boolean;\n readonly id: string;\n onactive: ((this: MediaStream, ev: Event) => any) | null;\n onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n oninactive: ((this: MediaStream, ev: Event) => any) | null;\n onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n addTrack(track: MediaStreamTrack): void;\n clone(): MediaStream;\n getAudioTracks(): MediaStreamTrack[];\n getTrackById(trackId: string): MediaStreamTrack | null;\n getTracks(): MediaStreamTrack[];\n getVideoTracks(): MediaStreamTrack[];\n removeTrack(track: MediaStreamTrack): void;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStream: {\n prototype: MediaStream;\n new(): MediaStream;\n new(stream: MediaStream): MediaStream;\n new(tracks: MediaStreamTrack[]): MediaStream;\n};\n\ninterface MediaStreamAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaStreamAudioSourceNode: {\n prototype: MediaStreamAudioSourceNode;\n new(): MediaStreamAudioSourceNode;\n};\n\ninterface MediaStreamError {\n readonly constraintName: string | null;\n readonly message: string | null;\n readonly name: string;\n}\n\ndeclare var MediaStreamError: {\n prototype: MediaStreamError;\n new(): MediaStreamError;\n};\n\ninterface MediaStreamErrorEvent extends Event {\n readonly error: MediaStreamError | null;\n}\n\ndeclare var MediaStreamErrorEvent: {\n prototype: MediaStreamErrorEvent;\n new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent;\n};\n\ninterface MediaStreamEvent extends Event {\n readonly stream: MediaStream | null;\n}\n\ndeclare var MediaStreamEvent: {\n prototype: MediaStreamEvent;\n new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent;\n};\n\ninterface MediaStreamTrackEventMap {\n \"ended\": MediaStreamErrorEvent;\n \"mute\": Event;\n \"overconstrained\": MediaStreamErrorEvent;\n \"unmute\": Event;\n}\n\ninterface MediaStreamTrack extends EventTarget {\n enabled: boolean;\n readonly id: string;\n readonly kind: string;\n readonly label: string;\n readonly muted: boolean;\n onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n readonly readonly: boolean;\n readonly readyState: MediaStreamTrackState;\n readonly remote: boolean;\n applyConstraints(constraints: MediaTrackConstraints): Promise;\n clone(): MediaStreamTrack;\n getCapabilities(): MediaTrackCapabilities;\n getConstraints(): MediaTrackConstraints;\n getSettings(): MediaTrackSettings;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStreamTrack: {\n prototype: MediaStreamTrack;\n new(): MediaStreamTrack;\n};\n\ninterface MediaStreamTrackEvent extends Event {\n readonly track: MediaStreamTrack;\n}\n\ndeclare var MediaStreamTrackEvent: {\n prototype: MediaStreamTrackEvent;\n new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent;\n};\n\ninterface MessageChannel {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\ndeclare var MessageChannel: {\n prototype: MessageChannel;\n new(): MessageChannel;\n};\n\ninterface MessageEvent extends Event {\n readonly data: any;\n readonly origin: string;\n readonly ports: ReadonlyArray;\n readonly source: Window | null;\n initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void;\n}\n\ndeclare var MessageEvent: {\n prototype: MessageEvent;\n new(type: string, eventInitDict?: MessageEventInit): MessageEvent;\n};\n\ninterface MessagePortEventMap {\n \"message\": MessageEvent;\n}\n\ninterface MessagePort extends EventTarget {\n onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;\n close(): void;\n postMessage(message?: any, transfer?: any[]): void;\n start(): void;\n addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MessagePort: {\n prototype: MessagePort;\n new(): MessagePort;\n};\n\ninterface MimeType {\n readonly description: string;\n readonly enabledPlugin: Plugin;\n readonly suffixes: string;\n readonly type: string;\n}\n\ndeclare var MimeType: {\n prototype: MimeType;\n new(): MimeType;\n};\n\ninterface MimeTypeArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(type: string): Plugin;\n [index: number]: Plugin;\n}\n\ndeclare var MimeTypeArray: {\n prototype: MimeTypeArray;\n new(): MimeTypeArray;\n};\n\ninterface MouseEvent extends UIEvent {\n readonly altKey: boolean;\n readonly button: number;\n readonly buttons: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly ctrlKey: boolean;\n /** @deprecated */\n readonly fromElement: Element;\n readonly layerX: number;\n readonly layerY: number;\n readonly metaKey: boolean;\n readonly movementX: number;\n readonly movementY: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly relatedTarget: EventTarget;\n readonly screenX: number;\n readonly screenY: number;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly toElement: Element;\n /** @deprecated */\n readonly which: number;\n readonly x: number;\n readonly y: number;\n getModifierState(keyArg: string): boolean;\n initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;\n}\n\ndeclare var MouseEvent: {\n prototype: MouseEvent;\n new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;\n};\n\ninterface MutationEvent extends Event {\n readonly attrChange: number;\n readonly attrName: string;\n readonly newValue: string;\n readonly prevValue: string;\n readonly relatedNode: Node;\n initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n}\n\ndeclare var MutationEvent: {\n prototype: MutationEvent;\n new(): MutationEvent;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n};\n\ninterface MutationObserver {\n disconnect(): void;\n observe(target: Node, options: MutationObserverInit): void;\n takeRecords(): MutationRecord[];\n}\n\ndeclare var MutationObserver: {\n prototype: MutationObserver;\n new(callback: MutationCallback): MutationObserver;\n};\n\ninterface MutationRecord {\n readonly addedNodes: NodeList;\n readonly attributeName: string | null;\n readonly attributeNamespace: string | null;\n readonly nextSibling: Node | null;\n readonly oldValue: string | null;\n readonly previousSibling: Node | null;\n readonly removedNodes: NodeList;\n readonly target: Node;\n readonly type: MutationRecordType;\n}\n\ndeclare var MutationRecord: {\n prototype: MutationRecord;\n new(): MutationRecord;\n};\n\ninterface NamedNodeMap {\n readonly length: number;\n getNamedItem(qualifiedName: string): Attr | null;\n getNamedItemNS(namespace: string | null, localName: string): Attr | null;\n item(index: number): Attr | null;\n removeNamedItem(qualifiedName: string): Attr;\n removeNamedItemNS(namespace: string | null, localName: string): Attr;\n setNamedItem(attr: Attr): Attr | null;\n setNamedItemNS(attr: Attr): Attr | null;\n [index: number]: Attr;\n}\n\ndeclare var NamedNodeMap: {\n prototype: NamedNodeMap;\n new(): NamedNodeMap;\n};\n\ninterface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage {\n readonly activeVRDisplays: ReadonlyArray;\n readonly authentication: WebAuthentication;\n readonly cookieEnabled: boolean;\n readonly doNotTrack: string | null;\n gamepadInputEmulation: GamepadInputEmulationType;\n readonly geolocation: Geolocation;\n readonly maxTouchPoints: number;\n readonly mimeTypes: MimeTypeArray;\n readonly msManipulationViewsEnabled: boolean;\n readonly msMaxTouchPoints: number;\n readonly msPointerEnabled: boolean;\n readonly plugins: PluginArray;\n readonly pointerEnabled: boolean;\n readonly serviceWorker: ServiceWorkerContainer;\n readonly webdriver: boolean;\n getGamepads(): (Gamepad | null)[];\n getVRDisplays(): Promise;\n javaEnabled(): boolean;\n msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;\n requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise;\n vibrate(pattern: number | number[]): boolean;\n}\n\ndeclare var Navigator: {\n prototype: Navigator;\n new(): Navigator;\n};\n\ninterface NavigatorBeacon {\n sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean;\n}\n\ninterface NavigatorConcurrentHardware {\n readonly hardwareConcurrency: number;\n}\n\ninterface NavigatorContentUtils {\n}\n\ninterface NavigatorID {\n readonly appCodeName: string;\n readonly appName: string;\n readonly appVersion: string;\n readonly platform: string;\n readonly product: string;\n readonly productSub: string;\n readonly userAgent: string;\n readonly vendor: string;\n readonly vendorSub: string;\n}\n\ninterface NavigatorLanguage {\n readonly language: string;\n readonly languages: ReadonlyArray;\n}\n\ninterface NavigatorOnLine {\n readonly onLine: boolean;\n}\n\ninterface NavigatorStorageUtils {\n}\n\ninterface NavigatorUserMedia {\n readonly mediaDevices: MediaDevices;\n getDisplayMedia(constraints: MediaStreamConstraints): Promise;\n getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;\n}\n\ninterface Node extends EventTarget {\n readonly baseURI: string | null;\n readonly childNodes: NodeListOf;\n readonly firstChild: Node | null;\n readonly lastChild: Node | null;\n readonly localName: string | null;\n readonly namespaceURI: string | null;\n readonly nextSibling: Node | null;\n readonly nodeName: string;\n readonly nodeType: number;\n nodeValue: string | null;\n readonly ownerDocument: Document;\n readonly parentElement: HTMLElement | null;\n readonly parentNode: Node | null;\n readonly previousSibling: Node | null;\n textContent: string | null;\n appendChild(newChild: T): T;\n cloneNode(deep?: boolean): Node;\n compareDocumentPosition(other: Node): number;\n contains(child: Node): boolean;\n hasChildNodes(): boolean;\n insertBefore(newChild: T, refChild: Node | null): T;\n isDefaultNamespace(namespaceURI: string | null): boolean;\n isEqualNode(arg: Node): boolean;\n isSameNode(other: Node): boolean;\n lookupNamespaceURI(prefix: string | null): string | null;\n lookupPrefix(namespaceURI: string | null): string | null;\n normalize(): void;\n removeChild(oldChild: T): T;\n replaceChild(newChild: Node, oldChild: T): T;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n}\n\ndeclare var Node: {\n prototype: Node;\n new(): Node;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n};\n\ninterface NodeFilter {\n acceptNode(node: Node): number;\n}\n\ndeclare var NodeFilter: {\n readonly FILTER_ACCEPT: number;\n readonly FILTER_REJECT: number;\n readonly FILTER_SKIP: number;\n readonly SHOW_ALL: number;\n readonly SHOW_ATTRIBUTE: number;\n readonly SHOW_CDATA_SECTION: number;\n readonly SHOW_COMMENT: number;\n readonly SHOW_DOCUMENT: number;\n readonly SHOW_DOCUMENT_FRAGMENT: number;\n readonly SHOW_DOCUMENT_TYPE: number;\n readonly SHOW_ELEMENT: number;\n readonly SHOW_ENTITY: number;\n readonly SHOW_ENTITY_REFERENCE: number;\n readonly SHOW_NOTATION: number;\n readonly SHOW_PROCESSING_INSTRUCTION: number;\n readonly SHOW_TEXT: number;\n};\n\ninterface NodeIterator {\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n detach(): void;\n nextNode(): Node | null;\n previousNode(): Node | null;\n}\n\ndeclare var NodeIterator: {\n prototype: NodeIterator;\n new(): NodeIterator;\n};\n\ninterface NodeList {\n readonly length: number;\n item(index: number): Node;\n [index: number]: Node;\n}\n\ndeclare var NodeList: {\n prototype: NodeList;\n new(): NodeList;\n};\n\ninterface NodeListOf extends NodeList {\n length: number;\n item(index: number): TNode;\n [index: number]: TNode;\n}\n\ninterface NodeSelector {\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface NotificationEventMap {\n \"click\": Event;\n \"close\": Event;\n \"error\": Event;\n \"show\": Event;\n}\n\ninterface Notification extends EventTarget {\n readonly body: string | null;\n readonly data: any;\n readonly dir: NotificationDirection;\n readonly icon: string | null;\n readonly lang: string | null;\n onclick: ((this: Notification, ev: Event) => any) | null;\n onclose: ((this: Notification, ev: Event) => any) | null;\n onerror: ((this: Notification, ev: Event) => any) | null;\n onshow: ((this: Notification, ev: Event) => any) | null;\n readonly permission: NotificationPermission;\n readonly tag: string | null;\n readonly title: string;\n close(): void;\n addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Notification: {\n prototype: Notification;\n new(title: string, options?: NotificationOptions): Notification;\n requestPermission(callback?: NotificationPermissionCallback): Promise;\n};\n\ninterface OES_element_index_uint {\n}\n\ndeclare var OES_element_index_uint: {\n prototype: OES_element_index_uint;\n new(): OES_element_index_uint;\n};\n\ninterface OES_standard_derivatives {\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n}\n\ndeclare var OES_standard_derivatives: {\n prototype: OES_standard_derivatives;\n new(): OES_standard_derivatives;\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n};\n\ninterface OES_texture_float {\n}\n\ndeclare var OES_texture_float: {\n prototype: OES_texture_float;\n new(): OES_texture_float;\n};\n\ninterface OES_texture_float_linear {\n}\n\ndeclare var OES_texture_float_linear: {\n prototype: OES_texture_float_linear;\n new(): OES_texture_float_linear;\n};\n\ninterface OES_texture_half_float {\n readonly HALF_FLOAT_OES: number;\n}\n\ndeclare var OES_texture_half_float: {\n prototype: OES_texture_half_float;\n new(): OES_texture_half_float;\n readonly HALF_FLOAT_OES: number;\n};\n\ninterface OES_texture_half_float_linear {\n}\n\ndeclare var OES_texture_half_float_linear: {\n prototype: OES_texture_half_float_linear;\n new(): OES_texture_half_float_linear;\n};\n\ninterface OES_vertex_array_object {\n readonly VERTEX_ARRAY_BINDING_OES: number;\n bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n createVertexArrayOES(): WebGLVertexArrayObjectOES;\n deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES;\n}\n\ninterface OfflineAudioCompletionEvent extends Event {\n readonly renderedBuffer: AudioBuffer;\n}\n\ndeclare var OfflineAudioCompletionEvent: {\n prototype: OfflineAudioCompletionEvent;\n new(): OfflineAudioCompletionEvent;\n};\n\ninterface OfflineAudioContextEventMap extends AudioContextEventMap {\n \"complete\": OfflineAudioCompletionEvent;\n}\n\ninterface OfflineAudioContext extends AudioContextBase {\n readonly length: number;\n oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null;\n startRendering(): Promise;\n suspend(suspendTime: number): Promise;\n addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OfflineAudioContext: {\n prototype: OfflineAudioContext;\n new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext;\n};\n\ninterface OscillatorNodeEventMap {\n \"ended\": Event;\n}\n\ninterface OscillatorNode extends AudioNode {\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n onended: ((this: OscillatorNode, ev: Event) => any) | null;\n type: OscillatorType;\n setPeriodicWave(periodicWave: PeriodicWave): void;\n start(when?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OscillatorNode, ev: OscillatorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OscillatorNode: {\n prototype: OscillatorNode;\n new(): OscillatorNode;\n};\n\ninterface OverflowEvent extends UIEvent {\n readonly horizontalOverflow: boolean;\n readonly orient: number;\n readonly verticalOverflow: boolean;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n}\n\ndeclare var OverflowEvent: {\n prototype: OverflowEvent;\n new(): OverflowEvent;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n};\n\ninterface PageTransitionEvent extends Event {\n readonly persisted: boolean;\n}\n\ndeclare var PageTransitionEvent: {\n prototype: PageTransitionEvent;\n new(): PageTransitionEvent;\n};\n\ninterface PannerNode extends AudioNode {\n coneInnerAngle: number;\n coneOuterAngle: number;\n coneOuterGain: number;\n distanceModel: DistanceModelType;\n maxDistance: number;\n panningModel: PanningModelType;\n refDistance: number;\n rolloffFactor: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n /** @deprecated */\n setVelocity(x: number, y: number, z: number): void;\n}\n\ndeclare var PannerNode: {\n prototype: PannerNode;\n new(): PannerNode;\n};\n\ninterface ParentNode {\n readonly children: HTMLCollection;\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface ParentNode {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n}\n\ninterface Path2D extends CanvasPathMethods {\n}\n\ndeclare var Path2D: {\n prototype: Path2D;\n new(d?: Path2D | string): Path2D;\n};\n\ninterface PaymentAddress {\n readonly addressLine: string[];\n readonly city: string;\n readonly country: string;\n readonly dependentLocality: string;\n readonly languageCode: string;\n readonly organization: string;\n readonly phone: string;\n readonly postalCode: string;\n readonly recipient: string;\n readonly region: string;\n readonly sortingCode: string;\n toJSON(): any;\n}\n\ndeclare var PaymentAddress: {\n prototype: PaymentAddress;\n new(): PaymentAddress;\n};\n\ninterface PaymentRequestEventMap {\n \"shippingaddresschange\": Event;\n \"shippingoptionchange\": Event;\n}\n\ninterface PaymentRequest extends EventTarget {\n readonly id: string;\n onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null;\n onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n readonly shippingType: PaymentShippingType | null;\n abort(): Promise;\n canMakePayment(): Promise;\n show(): Promise;\n addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var PaymentRequest: {\n prototype: PaymentRequest;\n new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest;\n};\n\ninterface PaymentRequestUpdateEvent extends Event {\n updateWith(detailsPromise: Promise): void;\n}\n\ndeclare var PaymentRequestUpdateEvent: {\n prototype: PaymentRequestUpdateEvent;\n new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;\n};\n\ninterface PaymentResponse {\n readonly details: any;\n readonly methodName: string;\n readonly payerEmail: string | null;\n readonly payerName: string | null;\n readonly payerPhone: string | null;\n readonly requestId: string;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n complete(result?: PaymentComplete): Promise;\n toJSON(): any;\n}\n\ndeclare var PaymentResponse: {\n prototype: PaymentResponse;\n new(): PaymentResponse;\n};\n\ninterface PerfWidgetExternal {\n readonly activeNetworkRequestCount: number;\n readonly averageFrameTime: number;\n readonly averagePaintTime: number;\n readonly extraInformationEnabled: boolean;\n readonly independentRenderingEnabled: boolean;\n readonly irDisablingContentString: string;\n readonly irStatusAvailable: boolean;\n readonly maxCpuSpeed: number;\n readonly paintRequestsPerSecond: number;\n readonly performanceCounter: number;\n readonly performanceCounterFrequency: number;\n addEventListener(eventType: string, callback: Function): void;\n getMemoryUsage(): number;\n getProcessCpuUsage(): number;\n getRecentCpuUsage(last: number | null): any;\n getRecentFrames(last: number | null): any;\n getRecentMemoryUsage(last: number | null): any;\n getRecentPaintRequests(last: number | null): any;\n removeEventListener(eventType: string, callback: Function): void;\n repositionWindow(x: number, y: number): void;\n resizeWindow(width: number, height: number): void;\n}\n\ndeclare var PerfWidgetExternal: {\n prototype: PerfWidgetExternal;\n new(): PerfWidgetExternal;\n};\n\ninterface Performance {\n /** @deprecated */\n readonly navigation: PerformanceNavigation;\n readonly timeOrigin: number;\n /** @deprecated */\n readonly timing: PerformanceTiming;\n clearMarks(markName?: string): void;\n clearMeasures(measureName?: string): void;\n clearResourceTimings(): void;\n getEntries(): any;\n getEntriesByName(name: string, type?: string): any;\n getEntriesByType(type: string): any;\n /** @deprecated */\n getMarks(markName?: string): any;\n /** @deprecated */\n getMeasures(measureName?: string): any;\n mark(markName: string): void;\n measure(measureName: string, startMarkName?: string, endMarkName?: string): void;\n now(): number;\n setResourceTimingBufferSize(maxSize: number): void;\n toJSON(): any;\n}\n\ndeclare var Performance: {\n prototype: Performance;\n new(): Performance;\n};\n\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceEntry: {\n prototype: PerformanceEntry;\n new(): PerformanceEntry;\n};\n\ninterface PerformanceMark extends PerformanceEntry {\n}\n\ndeclare var PerformanceMark: {\n prototype: PerformanceMark;\n new(): PerformanceMark;\n};\n\ninterface PerformanceMeasure extends PerformanceEntry {\n}\n\ndeclare var PerformanceMeasure: {\n prototype: PerformanceMeasure;\n new(): PerformanceMeasure;\n};\n\ninterface PerformanceNavigation {\n readonly redirectCount: number;\n readonly type: number;\n toJSON(): any;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n}\n\ndeclare var PerformanceNavigation: {\n prototype: PerformanceNavigation;\n new(): PerformanceNavigation;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n};\n\ninterface PerformanceNavigationTiming extends PerformanceEntry {\n /** @deprecated */\n readonly connectEnd: number;\n /** @deprecated */\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n /** @deprecated */\n readonly domLoading: number;\n /** @deprecated */\n readonly domainLookupEnd: number;\n /** @deprecated */\n readonly domainLookupStart: number;\n /** @deprecated */\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n /** @deprecated */\n readonly navigationStart: number;\n readonly redirectCount: number;\n /** @deprecated */\n readonly redirectEnd: number;\n /** @deprecated */\n readonly redirectStart: number;\n /** @deprecated */\n readonly requestStart: number;\n /** @deprecated */\n readonly responseEnd: number;\n /** @deprecated */\n readonly responseStart: number;\n readonly type: NavigationType;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n readonly workerStart: number;\n}\n\ndeclare var PerformanceNavigationTiming: {\n prototype: PerformanceNavigationTiming;\n new(): PerformanceNavigationTiming;\n};\n\ninterface PerformanceResourceTiming extends PerformanceEntry {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly initiatorType: string;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly workerStart: number;\n}\n\ndeclare var PerformanceResourceTiming: {\n prototype: PerformanceResourceTiming;\n new(): PerformanceResourceTiming;\n};\n\ninterface PerformanceTiming {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly domLoading: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly msFirstPaint: number;\n readonly navigationStart: number;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceTiming: {\n prototype: PerformanceTiming;\n new(): PerformanceTiming;\n};\n\ninterface PeriodicWave {\n}\n\ndeclare var PeriodicWave: {\n prototype: PeriodicWave;\n new(): PeriodicWave;\n};\n\ninterface PermissionRequest extends DeferredPermissionRequest {\n readonly state: MSWebViewPermissionState;\n defer(): void;\n}\n\ndeclare var PermissionRequest: {\n prototype: PermissionRequest;\n new(): PermissionRequest;\n};\n\ninterface PermissionRequestedEvent extends Event {\n readonly permissionRequest: PermissionRequest;\n}\n\ndeclare var PermissionRequestedEvent: {\n prototype: PermissionRequestedEvent;\n new(): PermissionRequestedEvent;\n};\n\ninterface Plugin {\n readonly description: string;\n readonly filename: string;\n readonly length: number;\n readonly name: string;\n readonly version: string;\n item(index: number): MimeType;\n namedItem(type: string): MimeType;\n [index: number]: MimeType;\n}\n\ndeclare var Plugin: {\n prototype: Plugin;\n new(): Plugin;\n};\n\ninterface PluginArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(name: string): Plugin;\n refresh(reload?: boolean): void;\n [index: number]: Plugin;\n}\n\ndeclare var PluginArray: {\n prototype: PluginArray;\n new(): PluginArray;\n};\n\ninterface PointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var PointerEvent: {\n prototype: PointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): PointerEvent;\n};\n\ninterface PopStateEvent extends Event {\n readonly state: any;\n}\n\ndeclare var PopStateEvent: {\n prototype: PopStateEvent;\n new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent;\n};\n\ninterface Position {\n readonly coords: Coordinates;\n readonly timestamp: number;\n}\n\ndeclare var Position: {\n prototype: Position;\n new(): Position;\n};\n\ninterface PositionError {\n readonly code: number;\n readonly message: string;\n toString(): string;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n}\n\ndeclare var PositionError: {\n prototype: PositionError;\n new(): PositionError;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n};\n\ninterface ProcessingInstruction extends CharacterData {\n readonly target: string;\n}\n\ndeclare var ProcessingInstruction: {\n prototype: ProcessingInstruction;\n new(): ProcessingInstruction;\n};\n\ninterface ProgressEvent extends Event {\n readonly lengthComputable: boolean;\n readonly loaded: number;\n readonly total: number;\n initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;\n}\n\ndeclare var ProgressEvent: {\n prototype: ProgressEvent;\n new(typeArg: string, eventInitDict?: ProgressEventInit): ProgressEvent;\n};\n\ninterface PromiseRejectionEvent extends Event {\n readonly promise: PromiseLike;\n readonly reason: any;\n}\n\ninterface PromiseRejectionEventInit extends EventInit {\n promise: PromiseLike;\n reason?: any;\n}\n\ninterface PushManager {\n readonly supportedContentEncodings: ReadonlyArray;\n getSubscription(): Promise;\n permissionState(options?: PushSubscriptionOptionsInit): Promise;\n subscribe(options?: PushSubscriptionOptionsInit): Promise;\n}\n\ndeclare var PushManager: {\n prototype: PushManager;\n new(): PushManager;\n};\n\ninterface PushSubscription {\n readonly endpoint: string;\n readonly expirationTime: number | null;\n readonly options: PushSubscriptionOptions;\n getKey(name: PushEncryptionKeyName): ArrayBuffer | null;\n toJSON(): any;\n unsubscribe(): Promise;\n}\n\ndeclare var PushSubscription: {\n prototype: PushSubscription;\n new(): PushSubscription;\n};\n\ninterface PushSubscriptionOptions {\n readonly applicationServerKey: ArrayBuffer | null;\n readonly userVisibleOnly: boolean;\n}\n\ndeclare var PushSubscriptionOptions: {\n prototype: PushSubscriptionOptions;\n new(): PushSubscriptionOptions;\n};\n\ninterface RTCDTMFToneChangeEvent extends Event {\n readonly tone: string;\n}\n\ndeclare var RTCDTMFToneChangeEvent: {\n prototype: RTCDTMFToneChangeEvent;\n new(typeArg: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent;\n};\n\ninterface RTCDtlsTransportEventMap {\n \"dtlsstatechange\": RTCDtlsTransportStateChangedEvent;\n \"error\": Event;\n}\n\ninterface RTCDtlsTransport extends RTCStatsProvider {\n ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null;\n onerror: ((this: RTCDtlsTransport, ev: Event) => any) | null;\n readonly state: RTCDtlsTransportState;\n readonly transport: RTCIceTransport;\n getLocalParameters(): RTCDtlsParameters;\n getRemoteCertificates(): ArrayBuffer[];\n getRemoteParameters(): RTCDtlsParameters | null;\n start(remoteParameters: RTCDtlsParameters): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtlsTransport: {\n prototype: RTCDtlsTransport;\n new(transport: RTCIceTransport): RTCDtlsTransport;\n};\n\ninterface RTCDtlsTransportStateChangedEvent extends Event {\n readonly state: RTCDtlsTransportState;\n}\n\ndeclare var RTCDtlsTransportStateChangedEvent: {\n prototype: RTCDtlsTransportStateChangedEvent;\n new(): RTCDtlsTransportStateChangedEvent;\n};\n\ninterface RTCDtmfSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDtmfSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n readonly duration: number;\n readonly interToneGap: number;\n ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly sender: RTCRtpSender;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtmfSender: {\n prototype: RTCDtmfSender;\n new(sender: RTCRtpSender): RTCDtmfSender;\n};\n\ninterface RTCIceCandidate {\n candidate: string | null;\n sdpMLineIndex: number | null;\n sdpMid: string | null;\n toJSON(): any;\n}\n\ndeclare var RTCIceCandidate: {\n prototype: RTCIceCandidate;\n new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate;\n};\n\ninterface RTCIceCandidatePairChangedEvent extends Event {\n readonly pair: RTCIceCandidatePair;\n}\n\ndeclare var RTCIceCandidatePairChangedEvent: {\n prototype: RTCIceCandidatePairChangedEvent;\n new(): RTCIceCandidatePairChangedEvent;\n};\n\ninterface RTCIceGathererEventMap {\n \"error\": Event;\n \"localcandidate\": RTCIceGathererEvent;\n}\n\ninterface RTCIceGatherer extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n onerror: ((this: RTCIceGatherer, ev: Event) => any) | null;\n onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null;\n createAssociatedGatherer(): RTCIceGatherer;\n getLocalCandidates(): RTCIceCandidateDictionary[];\n getLocalParameters(): RTCIceParameters;\n addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceGatherer: {\n prototype: RTCIceGatherer;\n new(options: RTCIceGatherOptions): RTCIceGatherer;\n};\n\ninterface RTCIceGathererEvent extends Event {\n readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete;\n}\n\ndeclare var RTCIceGathererEvent: {\n prototype: RTCIceGathererEvent;\n new(): RTCIceGathererEvent;\n};\n\ninterface RTCIceTransportEventMap {\n \"candidatepairchange\": RTCIceCandidatePairChangedEvent;\n \"icestatechange\": RTCIceTransportStateChangedEvent;\n}\n\ninterface RTCIceTransport extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n readonly iceGatherer: RTCIceGatherer | null;\n oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null;\n onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null;\n readonly role: RTCIceRole;\n readonly state: RTCIceTransportState;\n addRemoteCandidate(remoteCandidate: RTCIceCandidateDictionary | RTCIceCandidateComplete): void;\n createAssociatedTransport(): RTCIceTransport;\n getNominatedCandidatePair(): RTCIceCandidatePair | null;\n getRemoteCandidates(): RTCIceCandidateDictionary[];\n getRemoteParameters(): RTCIceParameters | null;\n setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void;\n start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceTransport: {\n prototype: RTCIceTransport;\n new(): RTCIceTransport;\n};\n\ninterface RTCIceTransportStateChangedEvent extends Event {\n readonly state: RTCIceTransportState;\n}\n\ndeclare var RTCIceTransportStateChangedEvent: {\n prototype: RTCIceTransportStateChangedEvent;\n new(): RTCIceTransportStateChangedEvent;\n};\n\ninterface RTCPeerConnectionEventMap {\n \"addstream\": MediaStreamEvent;\n \"icecandidate\": RTCPeerConnectionIceEvent;\n \"iceconnectionstatechange\": Event;\n \"icegatheringstatechange\": Event;\n \"negotiationneeded\": Event;\n \"removestream\": MediaStreamEvent;\n \"signalingstatechange\": Event;\n}\n\ninterface RTCPeerConnection extends EventTarget {\n readonly canTrickleIceCandidates: boolean | null;\n readonly iceConnectionState: RTCIceConnectionState;\n readonly iceGatheringState: RTCIceGatheringState;\n readonly localDescription: RTCSessionDescription | null;\n onaddstream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null;\n onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null;\n oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onremovestream: ((this: RTCPeerConnection, ev: MediaStreamEvent) => any) | null;\n onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n readonly remoteDescription: RTCSessionDescription | null;\n readonly signalingState: RTCSignalingState;\n addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise;\n addStream(stream: MediaStream): void;\n close(): void;\n createAnswer(options?: RTCOfferOptions): Promise;\n createOffer(options?: RTCOfferOptions): Promise;\n getConfiguration(): RTCConfiguration;\n getLocalStreams(): MediaStream[];\n getRemoteStreams(): MediaStream[];\n getStats(selector: MediaStreamTrack | null, successCallback?: RTCStatsCallback, failureCallback?: RTCPeerConnectionErrorCallback): Promise;\n getStreamById(streamId: string): MediaStream | null;\n removeStream(stream: MediaStream): void;\n setLocalDescription(description: RTCSessionDescriptionInit): Promise;\n setRemoteDescription(description: RTCSessionDescriptionInit): Promise;\n addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCPeerConnection: {\n prototype: RTCPeerConnection;\n new(configuration: RTCConfiguration): RTCPeerConnection;\n};\n\ninterface RTCPeerConnectionIceEvent extends Event {\n readonly candidate: RTCIceCandidate;\n}\n\ndeclare var RTCPeerConnectionIceEvent: {\n prototype: RTCPeerConnectionIceEvent;\n new(type: string, eventInitDict: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent;\n};\n\ninterface RTCRtpReceiverEventMap {\n \"error\": Event;\n \"msdecodercapacitychange\": Event;\n \"msdsh\": Event;\n}\n\ninterface RTCRtpReceiver extends RTCStatsProvider {\n onerror: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n onmsdecodercapacitychange: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n onmsdsh: ((this: RTCRtpReceiver, ev: Event) => any) | null;\n readonly rtcpTransport: RTCDtlsTransport;\n readonly track: MediaStreamTrack | null;\n readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport;\n getContributingSources(): RTCRtpContributingSource[];\n receive(parameters: RTCRtpParameters): void;\n requestSendCSRC(csrc: number): void;\n setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCRtpReceiver, ev: RTCRtpReceiverEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCRtpReceiver: {\n prototype: RTCRtpReceiver;\n new(transport: RTCDtlsTransport | RTCSrtpSdesTransport, kind: string, rtcpTransport?: RTCDtlsTransport): RTCRtpReceiver;\n getCapabilities(kind?: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpSenderEventMap {\n \"error\": Event;\n \"ssrcconflict\": RTCSsrcConflictEvent;\n}\n\ninterface RTCRtpSender extends RTCStatsProvider {\n onerror: ((this: RTCRtpSender, ev: Event) => any) | null;\n onssrcconflict: ((this: RTCRtpSender, ev: RTCSsrcConflictEvent) => any) | null;\n readonly rtcpTransport: RTCDtlsTransport;\n readonly track: MediaStreamTrack;\n readonly transport: RTCDtlsTransport | RTCSrtpSdesTransport;\n send(parameters: RTCRtpParameters): void;\n setTrack(track: MediaStreamTrack): void;\n setTransport(transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): void;\n stop(): void;\n addEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCRtpSender, ev: RTCRtpSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCRtpSender: {\n prototype: RTCRtpSender;\n new(track: MediaStreamTrack, transport: RTCDtlsTransport | RTCSrtpSdesTransport, rtcpTransport?: RTCDtlsTransport): RTCRtpSender;\n getCapabilities(kind?: string): RTCRtpCapabilities;\n};\n\ninterface RTCSessionDescription {\n sdp: string | null;\n type: RTCSdpType | null;\n toJSON(): any;\n}\n\ndeclare var RTCSessionDescription: {\n prototype: RTCSessionDescription;\n new(descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription;\n};\n\ninterface RTCSrtpSdesTransportEventMap {\n \"error\": Event;\n}\n\ninterface RTCSrtpSdesTransport extends EventTarget {\n onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null;\n readonly transport: RTCIceTransport;\n addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSrtpSdesTransport: {\n prototype: RTCSrtpSdesTransport;\n new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport;\n getLocalParameters(): RTCSrtpSdesParameters[];\n};\n\ninterface RTCSsrcConflictEvent extends Event {\n readonly ssrc: number;\n}\n\ndeclare var RTCSsrcConflictEvent: {\n prototype: RTCSsrcConflictEvent;\n new(): RTCSsrcConflictEvent;\n};\n\ninterface RTCStatsProvider extends EventTarget {\n getStats(): Promise;\n msGetStats(): Promise;\n}\n\ndeclare var RTCStatsProvider: {\n prototype: RTCStatsProvider;\n new(): RTCStatsProvider;\n};\n\ninterface RandomSource {\n getRandomValues(array: T): T;\n}\n\ndeclare var RandomSource: {\n prototype: RandomSource;\n new(): RandomSource;\n};\n\ninterface Range {\n readonly collapsed: boolean;\n readonly commonAncestorContainer: Node;\n readonly endContainer: Node;\n readonly endOffset: number;\n readonly startContainer: Node;\n readonly startOffset: number;\n cloneContents(): DocumentFragment;\n cloneRange(): Range;\n collapse(toStart?: boolean): void;\n compareBoundaryPoints(how: number, sourceRange: Range): number;\n createContextualFragment(fragment: string): DocumentFragment;\n deleteContents(): void;\n detach(): void;\n expand(Unit: ExpandGranularity): boolean;\n extractContents(): DocumentFragment;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n insertNode(node: Node): void;\n isPointInRange(node: Node, offset: number): boolean;\n selectNode(node: Node): void;\n selectNodeContents(node: Node): void;\n setEnd(node: Node, offset: number): void;\n setEndAfter(node: Node): void;\n setEndBefore(node: Node): void;\n setStart(node: Node, offset: number): void;\n setStartAfter(node: Node): void;\n setStartBefore(node: Node): void;\n surroundContents(newParent: Node): void;\n toString(): string;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n}\n\ndeclare var Range: {\n prototype: Range;\n new(): Range;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n};\n\ninterface ReadableStream {\n readonly locked: boolean;\n cancel(): Promise;\n getReader(): ReadableStreamReader;\n}\n\ndeclare var ReadableStream: {\n prototype: ReadableStream;\n new(): ReadableStream;\n};\n\ninterface ReadableStreamReader {\n cancel(): Promise;\n read(): Promise;\n releaseLock(): void;\n}\n\ndeclare var ReadableStreamReader: {\n prototype: ReadableStreamReader;\n new(): ReadableStreamReader;\n};\n\ninterface Request extends Body {\n readonly cache: RequestCache;\n readonly credentials: RequestCredentials;\n readonly destination: RequestDestination;\n readonly headers: Headers;\n readonly integrity: string;\n readonly keepalive: boolean;\n readonly method: string;\n readonly mode: RequestMode;\n readonly redirect: RequestRedirect;\n readonly referrer: string;\n readonly referrerPolicy: ReferrerPolicy;\n readonly signal: AbortSignal | null;\n readonly type: RequestType;\n readonly url: string;\n clone(): Request;\n}\n\ndeclare var Request: {\n prototype: Request;\n new(input: Request | string, init?: RequestInit): Request;\n};\n\ninterface Response extends Body {\n readonly body: ReadableStream | null;\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\ndeclare var Response: {\n prototype: Response;\n new(body?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null, init?: ResponseInit): Response;\n error(): Response;\n redirect(url: string, status?: number): Response;\n};\n\ninterface SVGAElement extends SVGGraphicsElement, SVGURIReference {\n readonly target: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGAElement: {\n prototype: SVGAElement;\n new(): SVGAElement;\n};\n\ninterface SVGAngle {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n}\n\ndeclare var SVGAngle: {\n prototype: SVGAngle;\n new(): SVGAngle;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n};\n\ninterface SVGAnimatedAngle {\n readonly animVal: SVGAngle;\n readonly baseVal: SVGAngle;\n}\n\ndeclare var SVGAnimatedAngle: {\n prototype: SVGAnimatedAngle;\n new(): SVGAnimatedAngle;\n};\n\ninterface SVGAnimatedBoolean {\n readonly animVal: boolean;\n baseVal: boolean;\n}\n\ndeclare var SVGAnimatedBoolean: {\n prototype: SVGAnimatedBoolean;\n new(): SVGAnimatedBoolean;\n};\n\ninterface SVGAnimatedEnumeration {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedEnumeration: {\n prototype: SVGAnimatedEnumeration;\n new(): SVGAnimatedEnumeration;\n};\n\ninterface SVGAnimatedInteger {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedInteger: {\n prototype: SVGAnimatedInteger;\n new(): SVGAnimatedInteger;\n};\n\ninterface SVGAnimatedLength {\n readonly animVal: SVGLength;\n readonly baseVal: SVGLength;\n}\n\ndeclare var SVGAnimatedLength: {\n prototype: SVGAnimatedLength;\n new(): SVGAnimatedLength;\n};\n\ninterface SVGAnimatedLengthList {\n readonly animVal: SVGLengthList;\n readonly baseVal: SVGLengthList;\n}\n\ndeclare var SVGAnimatedLengthList: {\n prototype: SVGAnimatedLengthList;\n new(): SVGAnimatedLengthList;\n};\n\ninterface SVGAnimatedNumber {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedNumber: {\n prototype: SVGAnimatedNumber;\n new(): SVGAnimatedNumber;\n};\n\ninterface SVGAnimatedNumberList {\n readonly animVal: SVGNumberList;\n readonly baseVal: SVGNumberList;\n}\n\ndeclare var SVGAnimatedNumberList: {\n prototype: SVGAnimatedNumberList;\n new(): SVGAnimatedNumberList;\n};\n\ninterface SVGAnimatedPoints {\n readonly animatedPoints: SVGPointList;\n readonly points: SVGPointList;\n}\n\ninterface SVGAnimatedPreserveAspectRatio {\n readonly animVal: SVGPreserveAspectRatio;\n readonly baseVal: SVGPreserveAspectRatio;\n}\n\ndeclare var SVGAnimatedPreserveAspectRatio: {\n prototype: SVGAnimatedPreserveAspectRatio;\n new(): SVGAnimatedPreserveAspectRatio;\n};\n\ninterface SVGAnimatedRect {\n readonly animVal: SVGRect;\n readonly baseVal: SVGRect;\n}\n\ndeclare var SVGAnimatedRect: {\n prototype: SVGAnimatedRect;\n new(): SVGAnimatedRect;\n};\n\ninterface SVGAnimatedString {\n readonly animVal: string;\n baseVal: string;\n}\n\ndeclare var SVGAnimatedString: {\n prototype: SVGAnimatedString;\n new(): SVGAnimatedString;\n};\n\ninterface SVGAnimatedTransformList {\n readonly animVal: SVGTransformList;\n readonly baseVal: SVGTransformList;\n}\n\ndeclare var SVGAnimatedTransformList: {\n prototype: SVGAnimatedTransformList;\n new(): SVGAnimatedTransformList;\n};\n\ninterface SVGCircleElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGCircleElement: {\n prototype: SVGCircleElement;\n new(): SVGCircleElement;\n};\n\ninterface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes {\n readonly clipPathUnits: SVGAnimatedEnumeration;\n addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGClipPathElement: {\n prototype: SVGClipPathElement;\n new(): SVGClipPathElement;\n};\n\ninterface SVGComponentTransferFunctionElement extends SVGElement {\n readonly amplitude: SVGAnimatedNumber;\n readonly exponent: SVGAnimatedNumber;\n readonly intercept: SVGAnimatedNumber;\n readonly offset: SVGAnimatedNumber;\n readonly slope: SVGAnimatedNumber;\n readonly tableValues: SVGAnimatedNumberList;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGComponentTransferFunctionElement: {\n prototype: SVGComponentTransferFunctionElement;\n new(): SVGComponentTransferFunctionElement;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n};\n\ninterface SVGDefsElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDefsElement: {\n prototype: SVGDefsElement;\n new(): SVGDefsElement;\n};\n\ninterface SVGDescElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDescElement: {\n prototype: SVGDescElement;\n new(): SVGDescElement;\n};\n\ninterface SVGElementEventMap extends ElementEventMap {\n \"click\": MouseEvent;\n \"dblclick\": MouseEvent;\n \"focusin\": FocusEvent;\n \"focusout\": FocusEvent;\n \"load\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n}\n\ninterface SVGElement extends Element, ElementCSSInlineStyle {\n readonly className: any;\n onclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onload: ((this: SVGElement, ev: Event) => any) | null;\n onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null;\n readonly ownerSVGElement: SVGSVGElement | null;\n readonly viewportElement: SVGElement | null;\n /** @deprecated */\n xmlbase: string;\n addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGElement: {\n prototype: SVGElement;\n new(): SVGElement;\n};\n\ninterface SVGElementInstance extends EventTarget {\n readonly childNodes: SVGElementInstanceList;\n readonly correspondingElement: SVGElement;\n readonly correspondingUseElement: SVGUseElement;\n readonly firstChild: SVGElementInstance;\n readonly lastChild: SVGElementInstance;\n readonly nextSibling: SVGElementInstance;\n readonly parentNode: SVGElementInstance;\n readonly previousSibling: SVGElementInstance;\n}\n\ndeclare var SVGElementInstance: {\n prototype: SVGElementInstance;\n new(): SVGElementInstance;\n};\n\ninterface SVGElementInstanceList {\n /** @deprecated */\n readonly length: number;\n /** @deprecated */\n item(index: number): SVGElementInstance;\n}\n\ndeclare var SVGElementInstanceList: {\n prototype: SVGElementInstanceList;\n new(): SVGElementInstanceList;\n};\n\ninterface SVGEllipseElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGEllipseElement: {\n prototype: SVGEllipseElement;\n new(): SVGEllipseElement;\n};\n\ninterface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly mode: SVGAnimatedEnumeration;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEBlendElement: {\n prototype: SVGFEBlendElement;\n new(): SVGFEBlendElement;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n};\n\ninterface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly type: SVGAnimatedEnumeration;\n readonly values: SVGAnimatedNumberList;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEColorMatrixElement: {\n prototype: SVGFEColorMatrixElement;\n new(): SVGFEColorMatrixElement;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEComponentTransferElement: {\n prototype: SVGFEComponentTransferElement;\n new(): SVGFEComponentTransferElement;\n};\n\ninterface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly k1: SVGAnimatedNumber;\n readonly k2: SVGAnimatedNumber;\n readonly k3: SVGAnimatedNumber;\n readonly k4: SVGAnimatedNumber;\n readonly operator: SVGAnimatedEnumeration;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFECompositeElement: {\n prototype: SVGFECompositeElement;\n new(): SVGFECompositeElement;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n};\n\ninterface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly bias: SVGAnimatedNumber;\n readonly divisor: SVGAnimatedNumber;\n readonly edgeMode: SVGAnimatedEnumeration;\n readonly in1: SVGAnimatedString;\n readonly kernelMatrix: SVGAnimatedNumberList;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly orderX: SVGAnimatedInteger;\n readonly orderY: SVGAnimatedInteger;\n readonly preserveAlpha: SVGAnimatedBoolean;\n readonly targetX: SVGAnimatedInteger;\n readonly targetY: SVGAnimatedInteger;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEConvolveMatrixElement: {\n prototype: SVGFEConvolveMatrixElement;\n new(): SVGFEConvolveMatrixElement;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n};\n\ninterface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly diffuseConstant: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDiffuseLightingElement: {\n prototype: SVGFEDiffuseLightingElement;\n new(): SVGFEDiffuseLightingElement;\n};\n\ninterface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly scale: SVGAnimatedNumber;\n readonly xChannelSelector: SVGAnimatedEnumeration;\n readonly yChannelSelector: SVGAnimatedEnumeration;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDisplacementMapElement: {\n prototype: SVGFEDisplacementMapElement;\n new(): SVGFEDisplacementMapElement;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n};\n\ninterface SVGFEDistantLightElement extends SVGElement {\n readonly azimuth: SVGAnimatedNumber;\n readonly elevation: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDistantLightElement: {\n prototype: SVGFEDistantLightElement;\n new(): SVGFEDistantLightElement;\n};\n\ninterface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFloodElement: {\n prototype: SVGFEFloodElement;\n new(): SVGFEFloodElement;\n};\n\ninterface SVGFEFuncAElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncAElement: {\n prototype: SVGFEFuncAElement;\n new(): SVGFEFuncAElement;\n};\n\ninterface SVGFEFuncBElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncBElement: {\n prototype: SVGFEFuncBElement;\n new(): SVGFEFuncBElement;\n};\n\ninterface SVGFEFuncGElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncGElement: {\n prototype: SVGFEFuncGElement;\n new(): SVGFEFuncGElement;\n};\n\ninterface SVGFEFuncRElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncRElement: {\n prototype: SVGFEFuncRElement;\n new(): SVGFEFuncRElement;\n};\n\ninterface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly stdDeviationX: SVGAnimatedNumber;\n readonly stdDeviationY: SVGAnimatedNumber;\n setStdDeviation(stdDeviationX: number, stdDeviationY: number): void;\n addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEGaussianBlurElement: {\n prototype: SVGFEGaussianBlurElement;\n new(): SVGFEGaussianBlurElement;\n};\n\ninterface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEImageElement: {\n prototype: SVGFEImageElement;\n new(): SVGFEImageElement;\n};\n\ninterface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeElement: {\n prototype: SVGFEMergeElement;\n new(): SVGFEMergeElement;\n};\n\ninterface SVGFEMergeNodeElement extends SVGElement {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeNodeElement: {\n prototype: SVGFEMergeNodeElement;\n new(): SVGFEMergeNodeElement;\n};\n\ninterface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly operator: SVGAnimatedEnumeration;\n readonly radiusX: SVGAnimatedNumber;\n readonly radiusY: SVGAnimatedNumber;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMorphologyElement: {\n prototype: SVGFEMorphologyElement;\n new(): SVGFEMorphologyElement;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n};\n\ninterface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly dx: SVGAnimatedNumber;\n readonly dy: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEOffsetElement: {\n prototype: SVGFEOffsetElement;\n new(): SVGFEOffsetElement;\n};\n\ninterface SVGFEPointLightElement extends SVGElement {\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEPointLightElement: {\n prototype: SVGFEPointLightElement;\n new(): SVGFEPointLightElement;\n};\n\ninterface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly specularConstant: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpecularLightingElement: {\n prototype: SVGFESpecularLightingElement;\n new(): SVGFESpecularLightingElement;\n};\n\ninterface SVGFESpotLightElement extends SVGElement {\n readonly limitingConeAngle: SVGAnimatedNumber;\n readonly pointsAtX: SVGAnimatedNumber;\n readonly pointsAtY: SVGAnimatedNumber;\n readonly pointsAtZ: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpotLightElement: {\n prototype: SVGFESpotLightElement;\n new(): SVGFESpotLightElement;\n};\n\ninterface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETileElement: {\n prototype: SVGFETileElement;\n new(): SVGFETileElement;\n};\n\ninterface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly baseFrequencyX: SVGAnimatedNumber;\n readonly baseFrequencyY: SVGAnimatedNumber;\n readonly numOctaves: SVGAnimatedInteger;\n readonly seed: SVGAnimatedNumber;\n readonly stitchTiles: SVGAnimatedEnumeration;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETurbulenceElement: {\n prototype: SVGFETurbulenceElement;\n new(): SVGFETurbulenceElement;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n /** @deprecated */\n readonly filterResX: SVGAnimatedInteger;\n /** @deprecated */\n readonly filterResY: SVGAnimatedInteger;\n readonly filterUnits: SVGAnimatedEnumeration;\n readonly height: SVGAnimatedLength;\n readonly primitiveUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n /** @deprecated */\n setFilterRes(filterResX: number, filterResY: number): void;\n addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFilterElement: {\n prototype: SVGFilterElement;\n new(): SVGFilterElement;\n};\n\ninterface SVGFilterPrimitiveStandardAttributes {\n readonly height: SVGAnimatedLength;\n readonly result: SVGAnimatedString;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n}\n\ninterface SVGFitToViewBox {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly viewBox: SVGAnimatedRect;\n}\n\ninterface SVGForeignObjectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGForeignObjectElement: {\n prototype: SVGForeignObjectElement;\n new(): SVGForeignObjectElement;\n};\n\ninterface SVGGElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGElement: {\n prototype: SVGGElement;\n new(): SVGGElement;\n};\n\ninterface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n readonly gradientTransform: SVGAnimatedTransformList;\n readonly gradientUnits: SVGAnimatedEnumeration;\n readonly spreadMethod: SVGAnimatedEnumeration;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGradientElement: {\n prototype: SVGGradientElement;\n new(): SVGGradientElement;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n};\n\ninterface SVGGraphicsElement extends SVGElement, SVGTests {\n /** @deprecated */\n readonly farthestViewportElement: SVGElement | null;\n /** @deprecated */\n readonly nearestViewportElement: SVGElement | null;\n readonly transform: SVGAnimatedTransformList;\n getBBox(): SVGRect;\n getCTM(): SVGMatrix | null;\n getScreenCTM(): SVGMatrix | null;\n /** @deprecated */\n getTransformToElement(element: SVGElement): SVGMatrix;\n addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGraphicsElement: {\n prototype: SVGGraphicsElement;\n new(): SVGGraphicsElement;\n};\n\ninterface SVGImageElement extends SVGGraphicsElement, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGImageElement: {\n prototype: SVGImageElement;\n new(): SVGImageElement;\n};\n\ninterface SVGLength {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n}\n\ndeclare var SVGLength: {\n prototype: SVGLength;\n new(): SVGLength;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n};\n\ninterface SVGLengthList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGLength): SVGLength;\n clear(): void;\n getItem(index: number): SVGLength;\n initialize(newItem: SVGLength): SVGLength;\n insertItemBefore(newItem: SVGLength, index: number): SVGLength;\n removeItem(index: number): SVGLength;\n replaceItem(newItem: SVGLength, index: number): SVGLength;\n}\n\ndeclare var SVGLengthList: {\n prototype: SVGLengthList;\n new(): SVGLengthList;\n};\n\ninterface SVGLineElement extends SVGGraphicsElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLineElement: {\n prototype: SVGLineElement;\n new(): SVGLineElement;\n};\n\ninterface SVGLinearGradientElement extends SVGGradientElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLinearGradientElement: {\n prototype: SVGLinearGradientElement;\n new(): SVGLinearGradientElement;\n};\n\ninterface SVGMarkerElement extends SVGElement, SVGFitToViewBox {\n readonly markerHeight: SVGAnimatedLength;\n readonly markerUnits: SVGAnimatedEnumeration;\n readonly markerWidth: SVGAnimatedLength;\n readonly orientAngle: SVGAnimatedAngle;\n readonly orientType: SVGAnimatedEnumeration;\n readonly refX: SVGAnimatedLength;\n readonly refY: SVGAnimatedLength;\n setOrientToAngle(angle: SVGAngle): void;\n setOrientToAuto(): void;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMarkerElement: {\n prototype: SVGMarkerElement;\n new(): SVGMarkerElement;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n};\n\ninterface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes {\n readonly height: SVGAnimatedLength;\n readonly maskContentUnits: SVGAnimatedEnumeration;\n readonly maskUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMaskElement: {\n prototype: SVGMaskElement;\n new(): SVGMaskElement;\n};\n\ninterface SVGMatrix {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n flipX(): SVGMatrix;\n flipY(): SVGMatrix;\n inverse(): SVGMatrix;\n multiply(secondMatrix: SVGMatrix): SVGMatrix;\n rotate(angle: number): SVGMatrix;\n rotateFromVector(x: number, y: number): SVGMatrix;\n scale(scaleFactor: number): SVGMatrix;\n scaleNonUniform(scaleFactorX: number, scaleFactorY: number): SVGMatrix;\n skewX(angle: number): SVGMatrix;\n skewY(angle: number): SVGMatrix;\n translate(x: number, y: number): SVGMatrix;\n}\n\ndeclare var SVGMatrix: {\n prototype: SVGMatrix;\n new(): SVGMatrix;\n};\n\ninterface SVGMetadataElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMetadataElement: {\n prototype: SVGMetadataElement;\n new(): SVGMetadataElement;\n};\n\ninterface SVGNumber {\n value: number;\n}\n\ndeclare var SVGNumber: {\n prototype: SVGNumber;\n new(): SVGNumber;\n};\n\ninterface SVGNumberList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGNumber): SVGNumber;\n clear(): void;\n getItem(index: number): SVGNumber;\n initialize(newItem: SVGNumber): SVGNumber;\n insertItemBefore(newItem: SVGNumber, index: number): SVGNumber;\n removeItem(index: number): SVGNumber;\n replaceItem(newItem: SVGNumber, index: number): SVGNumber;\n}\n\ndeclare var SVGNumberList: {\n prototype: SVGNumberList;\n new(): SVGNumberList;\n};\n\ninterface SVGPathElement extends SVGGraphicsElement {\n /** @deprecated */\n readonly pathSegList: SVGPathSegList;\n /** @deprecated */\n createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs;\n /** @deprecated */\n createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel;\n /** @deprecated */\n createSVGPathSegClosePath(): SVGPathSegClosePath;\n /** @deprecated */\n createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel;\n /** @deprecated */\n createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel;\n /** @deprecated */\n createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel;\n /** @deprecated */\n createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs;\n /** @deprecated */\n createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel;\n /** @deprecated */\n createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs;\n /** @deprecated */\n createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel;\n /** @deprecated */\n getPathSegAtLength(distance: number): number;\n getPointAtLength(distance: number): SVGPoint;\n getTotalLength(): number;\n addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPathElement: {\n prototype: SVGPathElement;\n new(): SVGPathElement;\n};\n\ninterface SVGPathSeg {\n readonly pathSegType: number;\n readonly pathSegTypeAsLetter: string;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n}\n\ndeclare var SVGPathSeg: {\n prototype: SVGPathSeg;\n new(): SVGPathSeg;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n};\n\ninterface SVGPathSegArcAbs extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcAbs: {\n prototype: SVGPathSegArcAbs;\n new(): SVGPathSegArcAbs;\n};\n\ninterface SVGPathSegArcRel extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcRel: {\n prototype: SVGPathSegArcRel;\n new(): SVGPathSegArcRel;\n};\n\ninterface SVGPathSegClosePath extends SVGPathSeg {\n}\n\ndeclare var SVGPathSegClosePath: {\n prototype: SVGPathSegClosePath;\n new(): SVGPathSegClosePath;\n};\n\ninterface SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicAbs: {\n prototype: SVGPathSegCurvetoCubicAbs;\n new(): SVGPathSegCurvetoCubicAbs;\n};\n\ninterface SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicRel: {\n prototype: SVGPathSegCurvetoCubicRel;\n new(): SVGPathSegCurvetoCubicRel;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothAbs: {\n prototype: SVGPathSegCurvetoCubicSmoothAbs;\n new(): SVGPathSegCurvetoCubicSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothRel: {\n prototype: SVGPathSegCurvetoCubicSmoothRel;\n new(): SVGPathSegCurvetoCubicSmoothRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticAbs: {\n prototype: SVGPathSegCurvetoQuadraticAbs;\n new(): SVGPathSegCurvetoQuadraticAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticRel: {\n prototype: SVGPathSegCurvetoQuadraticRel;\n new(): SVGPathSegCurvetoQuadraticRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothAbs: {\n prototype: SVGPathSegCurvetoQuadraticSmoothAbs;\n new(): SVGPathSegCurvetoQuadraticSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothRel: {\n prototype: SVGPathSegCurvetoQuadraticSmoothRel;\n new(): SVGPathSegCurvetoQuadraticSmoothRel;\n};\n\ninterface SVGPathSegLinetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoAbs: {\n prototype: SVGPathSegLinetoAbs;\n new(): SVGPathSegLinetoAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalAbs: {\n prototype: SVGPathSegLinetoHorizontalAbs;\n new(): SVGPathSegLinetoHorizontalAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalRel: {\n prototype: SVGPathSegLinetoHorizontalRel;\n new(): SVGPathSegLinetoHorizontalRel;\n};\n\ninterface SVGPathSegLinetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoRel: {\n prototype: SVGPathSegLinetoRel;\n new(): SVGPathSegLinetoRel;\n};\n\ninterface SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalAbs: {\n prototype: SVGPathSegLinetoVerticalAbs;\n new(): SVGPathSegLinetoVerticalAbs;\n};\n\ninterface SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalRel: {\n prototype: SVGPathSegLinetoVerticalRel;\n new(): SVGPathSegLinetoVerticalRel;\n};\n\ninterface SVGPathSegList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPathSeg): SVGPathSeg;\n clear(): void;\n getItem(index: number): SVGPathSeg;\n initialize(newItem: SVGPathSeg): SVGPathSeg;\n insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg;\n removeItem(index: number): SVGPathSeg;\n replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg;\n}\n\ndeclare var SVGPathSegList: {\n prototype: SVGPathSegList;\n new(): SVGPathSegList;\n};\n\ninterface SVGPathSegMovetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoAbs: {\n prototype: SVGPathSegMovetoAbs;\n new(): SVGPathSegMovetoAbs;\n};\n\ninterface SVGPathSegMovetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoRel: {\n prototype: SVGPathSegMovetoRel;\n new(): SVGPathSegMovetoRel;\n};\n\ninterface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly patternContentUnits: SVGAnimatedEnumeration;\n readonly patternTransform: SVGAnimatedTransformList;\n readonly patternUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPatternElement: {\n prototype: SVGPatternElement;\n new(): SVGPatternElement;\n};\n\ninterface SVGPoint {\n x: number;\n y: number;\n matrixTransform(matrix: SVGMatrix): SVGPoint;\n}\n\ndeclare var SVGPoint: {\n prototype: SVGPoint;\n new(): SVGPoint;\n};\n\ninterface SVGPointList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPoint): SVGPoint;\n clear(): void;\n getItem(index: number): SVGPoint;\n initialize(newItem: SVGPoint): SVGPoint;\n insertItemBefore(newItem: SVGPoint, index: number): SVGPoint;\n removeItem(index: number): SVGPoint;\n replaceItem(newItem: SVGPoint, index: number): SVGPoint;\n}\n\ndeclare var SVGPointList: {\n prototype: SVGPointList;\n new(): SVGPointList;\n};\n\ninterface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolygonElement: {\n prototype: SVGPolygonElement;\n new(): SVGPolygonElement;\n};\n\ninterface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolylineElement: {\n prototype: SVGPolylineElement;\n new(): SVGPolylineElement;\n};\n\ninterface SVGPreserveAspectRatio {\n align: number;\n meetOrSlice: number;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n}\n\ndeclare var SVGPreserveAspectRatio: {\n prototype: SVGPreserveAspectRatio;\n new(): SVGPreserveAspectRatio;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n};\n\ninterface SVGRadialGradientElement extends SVGGradientElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly fx: SVGAnimatedLength;\n readonly fy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRadialGradientElement: {\n prototype: SVGRadialGradientElement;\n new(): SVGRadialGradientElement;\n};\n\ninterface SVGRect {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var SVGRect: {\n prototype: SVGRect;\n new(): SVGRect;\n};\n\ninterface SVGRectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRectElement: {\n prototype: SVGRectElement;\n new(): SVGRectElement;\n};\n\ninterface SVGSVGElementEventMap extends SVGElementEventMap {\n \"SVGAbort\": Event;\n \"SVGError\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"SVGUnload\": Event;\n \"SVGZoom\": SVGZoomEvent;\n}\n\ninterface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n contentScriptType: string;\n /** @deprecated */\n contentStyleType: string;\n currentScale: number;\n readonly currentTranslate: SVGPoint;\n readonly height: SVGAnimatedLength;\n onabort: ((this: SVGSVGElement, ev: Event) => any) | null;\n onerror: ((this: SVGSVGElement, ev: Event) => any) | null;\n onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onunload: ((this: SVGSVGElement, ev: Event) => any) | null;\n onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null;\n /** @deprecated */\n readonly pixelUnitToMillimeterX: number;\n /** @deprecated */\n readonly pixelUnitToMillimeterY: number;\n /** @deprecated */\n readonly screenPixelToMillimeterX: number;\n /** @deprecated */\n readonly screenPixelToMillimeterY: number;\n /** @deprecated */\n readonly viewport: SVGRect;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n checkEnclosure(element: SVGElement, rect: SVGRect): boolean;\n checkIntersection(element: SVGElement, rect: SVGRect): boolean;\n createSVGAngle(): SVGAngle;\n createSVGLength(): SVGLength;\n createSVGMatrix(): SVGMatrix;\n createSVGNumber(): SVGNumber;\n createSVGPoint(): SVGPoint;\n createSVGRect(): SVGRect;\n createSVGTransform(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n deselectAll(): void;\n /** @deprecated */\n forceRedraw(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n /** @deprecated */\n getCurrentTime(): number;\n getElementById(elementId: string): Element;\n getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n /** @deprecated */\n pauseAnimations(): void;\n /** @deprecated */\n setCurrentTime(seconds: number): void;\n /** @deprecated */\n suspendRedraw(maxWaitMilliseconds: number): number;\n /** @deprecated */\n unpauseAnimations(): void;\n /** @deprecated */\n unsuspendRedraw(suspendHandleID: number): void;\n /** @deprecated */\n unsuspendRedrawAll(): void;\n addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSVGElement: {\n prototype: SVGSVGElement;\n new(): SVGSVGElement;\n};\n\ninterface SVGScriptElement extends SVGElement, SVGURIReference {\n type: string;\n addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGScriptElement: {\n prototype: SVGScriptElement;\n new(): SVGScriptElement;\n};\n\ninterface SVGStopElement extends SVGElement {\n readonly offset: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStopElement: {\n prototype: SVGStopElement;\n new(): SVGStopElement;\n};\n\ninterface SVGStringList {\n readonly numberOfItems: number;\n appendItem(newItem: string): string;\n clear(): void;\n getItem(index: number): string;\n initialize(newItem: string): string;\n insertItemBefore(newItem: string, index: number): string;\n removeItem(index: number): string;\n replaceItem(newItem: string, index: number): string;\n}\n\ndeclare var SVGStringList: {\n prototype: SVGStringList;\n new(): SVGStringList;\n};\n\ninterface SVGStylable {\n className: any;\n}\n\ndeclare var SVGStylable: {\n prototype: SVGStylable;\n new(): SVGStylable;\n};\n\ninterface SVGStyleElement extends SVGElement {\n disabled: boolean;\n media: string;\n title: string;\n type: string;\n addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStyleElement: {\n prototype: SVGStyleElement;\n new(): SVGStyleElement;\n};\n\ninterface SVGSwitchElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSwitchElement: {\n prototype: SVGSwitchElement;\n new(): SVGSwitchElement;\n};\n\ninterface SVGSymbolElement extends SVGElement, SVGFitToViewBox {\n addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSymbolElement: {\n prototype: SVGSymbolElement;\n new(): SVGSymbolElement;\n};\n\ninterface SVGTSpanElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTSpanElement: {\n prototype: SVGTSpanElement;\n new(): SVGTSpanElement;\n};\n\ninterface SVGTests {\n readonly requiredExtensions: SVGStringList;\n /** @deprecated */\n readonly requiredFeatures: SVGStringList;\n readonly systemLanguage: SVGStringList;\n /** @deprecated */\n hasExtension(extension: string): boolean;\n}\n\ninterface SVGTextContentElement extends SVGGraphicsElement {\n readonly lengthAdjust: SVGAnimatedEnumeration;\n readonly textLength: SVGAnimatedLength;\n getCharNumAtPosition(point: SVGPoint): number;\n getComputedTextLength(): number;\n getEndPositionOfChar(charnum: number): SVGPoint;\n getExtentOfChar(charnum: number): SVGRect;\n getNumberOfChars(): number;\n getRotationOfChar(charnum: number): number;\n getStartPositionOfChar(charnum: number): SVGPoint;\n getSubStringLength(charnum: number, nchars: number): number;\n selectSubString(charnum: number, nchars: number): void;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextContentElement: {\n prototype: SVGTextContentElement;\n new(): SVGTextContentElement;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n};\n\ninterface SVGTextElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextElement: {\n prototype: SVGTextElement;\n new(): SVGTextElement;\n};\n\ninterface SVGTextPathElement extends SVGTextContentElement, SVGURIReference {\n readonly method: SVGAnimatedEnumeration;\n readonly spacing: SVGAnimatedEnumeration;\n readonly startOffset: SVGAnimatedLength;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPathElement: {\n prototype: SVGTextPathElement;\n new(): SVGTextPathElement;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n};\n\ninterface SVGTextPositioningElement extends SVGTextContentElement {\n readonly dx: SVGAnimatedLengthList;\n readonly dy: SVGAnimatedLengthList;\n readonly rotate: SVGAnimatedNumberList;\n readonly x: SVGAnimatedLengthList;\n readonly y: SVGAnimatedLengthList;\n addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPositioningElement: {\n prototype: SVGTextPositioningElement;\n new(): SVGTextPositioningElement;\n};\n\ninterface SVGTitleElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTitleElement: {\n prototype: SVGTitleElement;\n new(): SVGTitleElement;\n};\n\ninterface SVGTransform {\n readonly angle: number;\n readonly matrix: SVGMatrix;\n readonly type: number;\n setMatrix(matrix: SVGMatrix): void;\n setRotate(angle: number, cx: number, cy: number): void;\n setScale(sx: number, sy: number): void;\n setSkewX(angle: number): void;\n setSkewY(angle: number): void;\n setTranslate(tx: number, ty: number): void;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n}\n\ndeclare var SVGTransform: {\n prototype: SVGTransform;\n new(): SVGTransform;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n};\n\ninterface SVGTransformList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGTransform): SVGTransform;\n clear(): void;\n consolidate(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n getItem(index: number): SVGTransform;\n initialize(newItem: SVGTransform): SVGTransform;\n insertItemBefore(newItem: SVGTransform, index: number): SVGTransform;\n removeItem(index: number): SVGTransform;\n replaceItem(newItem: SVGTransform, index: number): SVGTransform;\n}\n\ndeclare var SVGTransformList: {\n prototype: SVGTransformList;\n new(): SVGTransformList;\n};\n\ninterface SVGURIReference {\n readonly href: SVGAnimatedString;\n}\n\ninterface SVGUnitTypes {\n readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number;\n readonly SVG_UNIT_TYPE_UNKNOWN: number;\n readonly SVG_UNIT_TYPE_USERSPACEONUSE: number;\n}\ndeclare var SVGUnitTypes: SVGUnitTypes;\n\ninterface SVGUseElement extends SVGGraphicsElement, SVGURIReference {\n readonly animatedInstanceRoot: SVGElementInstance | null;\n readonly height: SVGAnimatedLength;\n readonly instanceRoot: SVGElementInstance | null;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGUseElement: {\n prototype: SVGUseElement;\n new(): SVGUseElement;\n};\n\ninterface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n readonly viewTarget: SVGStringList;\n addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGViewElement: {\n prototype: SVGViewElement;\n new(): SVGViewElement;\n};\n\ninterface SVGZoomAndPan {\n readonly zoomAndPan: number;\n}\n\ndeclare var SVGZoomAndPan: {\n readonly SVG_ZOOMANDPAN_DISABLE: number;\n readonly SVG_ZOOMANDPAN_MAGNIFY: number;\n readonly SVG_ZOOMANDPAN_UNKNOWN: number;\n};\n\ninterface SVGZoomEvent extends UIEvent {\n readonly newScale: number;\n readonly newTranslate: SVGPoint;\n readonly previousScale: number;\n readonly previousTranslate: SVGPoint;\n readonly zoomRectScreen: SVGRect;\n}\n\ndeclare var SVGZoomEvent: {\n prototype: SVGZoomEvent;\n new(): SVGZoomEvent;\n};\n\ninterface ScopedCredential {\n readonly id: ArrayBuffer;\n readonly type: ScopedCredentialType;\n}\n\ndeclare var ScopedCredential: {\n prototype: ScopedCredential;\n new(): ScopedCredential;\n};\n\ninterface ScopedCredentialInfo {\n readonly credential: ScopedCredential;\n readonly publicKey: CryptoKey;\n}\n\ndeclare var ScopedCredentialInfo: {\n prototype: ScopedCredentialInfo;\n new(): ScopedCredentialInfo;\n};\n\ninterface ScreenEventMap {\n \"MSOrientationChange\": Event;\n}\n\ninterface Screen extends EventTarget {\n readonly availHeight: number;\n readonly availWidth: number;\n /** @deprecated */\n bufferDepth: number;\n readonly colorDepth: number;\n readonly deviceXDPI: number;\n readonly deviceYDPI: number;\n readonly fontSmoothingEnabled: boolean;\n readonly height: number;\n readonly logicalXDPI: number;\n readonly logicalYDPI: number;\n readonly msOrientation: string;\n onmsorientationchange: ((this: Screen, ev: Event) => any) | null;\n readonly pixelDepth: number;\n readonly systemXDPI: number;\n readonly systemYDPI: number;\n readonly width: number;\n lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean;\n msLockOrientation(orientations: string | string[]): boolean;\n msUnlockOrientation(): void;\n unlockOrientation(): void;\n addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Screen: {\n prototype: Screen;\n new(): Screen;\n};\n\ninterface ScriptProcessorNodeEventMap {\n \"audioprocess\": AudioProcessingEvent;\n}\n\ninterface ScriptProcessorNode extends AudioNode {\n /** @deprecated */\n readonly bufferSize: number;\n /** @deprecated */\n onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null;\n addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ScriptProcessorNode: {\n prototype: ScriptProcessorNode;\n new(): ScriptProcessorNode;\n};\n\ninterface ScrollIntoViewOptions extends ScrollOptions {\n block?: ScrollLogicalPosition;\n inline?: ScrollLogicalPosition;\n}\n\ninterface ScrollOptions {\n behavior?: ScrollBehavior;\n}\n\ninterface ScrollToOptions extends ScrollOptions {\n left?: number;\n top?: number;\n}\n\ninterface SecurityPolicyViolationEvent extends Event {\n readonly blockedURI: string;\n readonly columnNumber: number;\n readonly documentURI: string;\n readonly effectiveDirective: string;\n readonly lineNumber: number;\n readonly originalPolicy: string;\n readonly referrer: string;\n readonly sourceFile: string;\n readonly statusCode: number;\n readonly violatedDirective: string;\n}\n\ndeclare var SecurityPolicyViolationEvent: {\n prototype: SecurityPolicyViolationEvent;\n new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent;\n};\n\ninterface Selection {\n readonly anchorNode: Node;\n readonly anchorOffset: number;\n readonly baseNode: Node;\n readonly baseOffset: number;\n readonly extentNode: Node;\n readonly extentOffset: number;\n readonly focusNode: Node;\n readonly focusOffset: number;\n readonly isCollapsed: boolean;\n readonly rangeCount: number;\n readonly type: string;\n addRange(range: Range): void;\n collapse(parentNode: Node, offset: number): void;\n collapseToEnd(): void;\n collapseToStart(): void;\n containsNode(node: Node, partlyContained: boolean): boolean;\n deleteFromDocument(): void;\n empty(): void;\n extend(newNode: Node, offset: number): void;\n getRangeAt(index: number): Range;\n removeAllRanges(): void;\n removeRange(range: Range): void;\n selectAllChildren(parentNode: Node): void;\n setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void;\n setPosition(parentNode: Node, offset: number): void;\n toString(): string;\n}\n\ndeclare var Selection: {\n prototype: Selection;\n new(): Selection;\n};\n\ninterface ServiceUIFrameContext {\n getCachedFrameMessage(key: string): string;\n postFrameMessage(key: string, data: string): void;\n}\ndeclare var ServiceUIFrameContext: ServiceUIFrameContext;\n\ninterface ServiceWorkerEventMap extends AbstractWorkerEventMap {\n \"statechange\": Event;\n}\n\ninterface ServiceWorker extends EventTarget, AbstractWorker {\n onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;\n readonly scriptURL: string;\n readonly state: ServiceWorkerState;\n postMessage(message: any, transfer?: any[]): void;\n addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorker: {\n prototype: ServiceWorker;\n new(): ServiceWorker;\n};\n\ninterface ServiceWorkerContainerEventMap {\n \"controllerchange\": Event;\n \"message\": ServiceWorkerMessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface ServiceWorkerContainer extends EventTarget {\n readonly controller: ServiceWorker | null;\n oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;\n onmessage: ((this: ServiceWorkerContainer, ev: ServiceWorkerMessageEvent) => any) | null;\n onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n readonly ready: Promise;\n getRegistration(clientURL?: string): Promise;\n getRegistrations(): Promise;\n register(scriptURL: string, options?: RegistrationOptions): Promise;\n startMessages(): void;\n addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerContainer: {\n prototype: ServiceWorkerContainer;\n new(): ServiceWorkerContainer;\n};\n\ninterface ServiceWorkerMessageEvent extends Event {\n readonly data: any;\n readonly lastEventId: string;\n readonly origin: string;\n readonly ports: ReadonlyArray | null;\n readonly source: ServiceWorker | MessagePort | null;\n}\n\ndeclare var ServiceWorkerMessageEvent: {\n prototype: ServiceWorkerMessageEvent;\n new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent;\n};\n\ninterface ServiceWorkerRegistrationEventMap {\n \"updatefound\": Event;\n}\n\ninterface ServiceWorkerRegistration extends EventTarget {\n readonly active: ServiceWorker | null;\n readonly installing: ServiceWorker | null;\n onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null;\n readonly pushManager: PushManager;\n readonly scope: string;\n readonly sync: SyncManager;\n readonly waiting: ServiceWorker | null;\n getNotifications(filter?: GetNotificationOptions): Promise;\n showNotification(title: string, options?: NotificationOptions): Promise;\n unregister(): Promise;\n update(): Promise;\n addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerRegistration: {\n prototype: ServiceWorkerRegistration;\n new(): ServiceWorkerRegistration;\n};\n\ninterface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment {\n readonly host: Element;\n innerHTML: string;\n}\n\ninterface ShadowRootInit {\n delegatesFocus?: boolean;\n mode: \"open\" | \"closed\";\n}\n\ninterface SourceBuffer extends EventTarget {\n appendWindowEnd: number;\n appendWindowStart: number;\n readonly audioTracks: AudioTrackList;\n readonly buffered: TimeRanges;\n mode: AppendMode;\n timestampOffset: number;\n readonly updating: boolean;\n readonly videoTracks: VideoTrackList;\n abort(): void;\n appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n appendStream(stream: MSStream, maxSize?: number): void;\n remove(start: number, end: number): void;\n}\n\ndeclare var SourceBuffer: {\n prototype: SourceBuffer;\n new(): SourceBuffer;\n};\n\ninterface SourceBufferList extends EventTarget {\n readonly length: number;\n item(index: number): SourceBuffer;\n [index: number]: SourceBuffer;\n}\n\ndeclare var SourceBufferList: {\n prototype: SourceBufferList;\n new(): SourceBufferList;\n};\n\ninterface SpeechSynthesisEventMap {\n \"voiceschanged\": Event;\n}\n\ninterface SpeechSynthesis extends EventTarget {\n onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null;\n readonly paused: boolean;\n readonly pending: boolean;\n readonly speaking: boolean;\n cancel(): void;\n getVoices(): SpeechSynthesisVoice[];\n pause(): void;\n resume(): void;\n speak(utterance: SpeechSynthesisUtterance): void;\n addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesis: {\n prototype: SpeechSynthesis;\n new(): SpeechSynthesis;\n};\n\ninterface SpeechSynthesisEvent extends Event {\n readonly charIndex: number;\n readonly charLength: number;\n readonly elapsedTime: number;\n readonly name: string;\n readonly utterance: SpeechSynthesisUtterance;\n}\n\ndeclare var SpeechSynthesisEvent: {\n prototype: SpeechSynthesisEvent;\n new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent;\n};\n\ninterface SpeechSynthesisUtteranceEventMap {\n \"boundary\": Event;\n \"end\": Event;\n \"error\": Event;\n \"mark\": Event;\n \"pause\": Event;\n \"resume\": Event;\n \"start\": Event;\n}\n\ninterface SpeechSynthesisUtterance extends EventTarget {\n lang: string;\n onboundary: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n pitch: number;\n rate: number;\n text: string;\n voice: SpeechSynthesisVoice;\n volume: number;\n addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesisUtterance: {\n prototype: SpeechSynthesisUtterance;\n new(): SpeechSynthesisUtterance;\n new(text: string): SpeechSynthesisUtterance;\n};\n\ninterface SpeechSynthesisVoice {\n readonly default: boolean;\n readonly lang: string;\n readonly localService: boolean;\n readonly name: string;\n readonly voiceURI: string;\n}\n\ndeclare var SpeechSynthesisVoice: {\n prototype: SpeechSynthesisVoice;\n new(): SpeechSynthesisVoice;\n};\n\ninterface StereoPannerNode extends AudioNode {\n readonly pan: AudioParam;\n}\n\ndeclare var StereoPannerNode: {\n prototype: StereoPannerNode;\n new(): StereoPannerNode;\n};\n\ninterface Storage {\n readonly length: number;\n clear(): void;\n getItem(key: string): string | null;\n key(index: number): string | null;\n removeItem(key: string): void;\n setItem(key: string, value: string): void;\n [key: string]: any;\n}\n\ndeclare var Storage: {\n prototype: Storage;\n new(): Storage;\n};\n\ninterface StorageEvent extends Event {\n readonly key: string | null;\n readonly newValue: string | null;\n readonly oldValue: string | null;\n readonly storageArea: Storage | null;\n readonly url: string;\n}\n\ndeclare var StorageEvent: {\n prototype: StorageEvent;\n new (type: string, eventInitDict?: StorageEventInit): StorageEvent;\n};\n\ninterface StorageEventInit extends EventInit {\n key?: string;\n newValue?: string;\n oldValue?: string;\n storageArea?: Storage;\n url: string;\n}\n\ninterface StyleMedia {\n readonly type: string;\n matchMedium(mediaquery: string): boolean;\n}\n\ndeclare var StyleMedia: {\n prototype: StyleMedia;\n new(): StyleMedia;\n};\n\ninterface StyleSheet {\n disabled: boolean;\n readonly href: string | null;\n readonly media: MediaList;\n readonly ownerNode: Node;\n readonly parentStyleSheet: StyleSheet | null;\n readonly title: string | null;\n readonly type: string;\n}\n\ndeclare var StyleSheet: {\n prototype: StyleSheet;\n new(): StyleSheet;\n};\n\ninterface StyleSheetList {\n readonly length: number;\n item(index: number): StyleSheet | null;\n [index: number]: StyleSheet;\n}\n\ndeclare var StyleSheetList: {\n prototype: StyleSheetList;\n new(): StyleSheetList;\n};\n\ninterface SubtleCrypto {\n decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike;\n deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n exportKey(format: \"jwk\", key: CryptoKey): PromiseLike;\n exportKey(format: \"raw\" | \"pkcs8\" | \"spki\", key: CryptoKey): PromiseLike;\n exportKey(format: string, key: CryptoKey): PromiseLike;\n generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"jwk\", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"raw\" | \"pkcs8\" | \"spki\", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike;\n}\n\ndeclare var SubtleCrypto: {\n prototype: SubtleCrypto;\n new(): SubtleCrypto;\n};\n\ninterface SyncManager {\n getTags(): Promise;\n register(tag: string): Promise;\n}\n\ndeclare var SyncManager: {\n prototype: SyncManager;\n new(): SyncManager;\n};\n\ninterface Text extends CharacterData {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly wholeText: string;\n splitText(offset: number): Text;\n}\n\ndeclare var Text: {\n prototype: Text;\n new(data?: string): Text;\n};\n\ninterface TextDecoder {\n readonly encoding: string;\n readonly fatal: boolean;\n readonly ignoreBOM: boolean;\n decode(input?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: TextDecodeOptions): string;\n}\n\ndeclare var TextDecoder: {\n prototype: TextDecoder;\n new(label?: string, options?: TextDecoderOptions): TextDecoder;\n};\n\ninterface TextEncoder {\n readonly encoding: string;\n encode(input?: string): Uint8Array;\n}\n\ndeclare var TextEncoder: {\n prototype: TextEncoder;\n new(): TextEncoder;\n};\n\ninterface TextEvent extends UIEvent {\n readonly data: string;\n initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n}\n\ndeclare var TextEvent: {\n prototype: TextEvent;\n new(): TextEvent;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n};\n\ninterface TextMetrics {\n readonly width: number;\n}\n\ndeclare var TextMetrics: {\n prototype: TextMetrics;\n new(): TextMetrics;\n};\n\ninterface TextTrackEventMap {\n \"cuechange\": Event;\n \"error\": Event;\n \"load\": Event;\n}\n\ninterface TextTrack extends EventTarget {\n readonly activeCues: TextTrackCueList;\n readonly cues: TextTrackCueList;\n readonly inBandMetadataTrackDispatchType: string;\n readonly kind: string;\n readonly label: string;\n readonly language: string;\n mode: TextTrackMode | number;\n oncuechange: ((this: TextTrack, ev: Event) => any) | null;\n onerror: ((this: TextTrack, ev: Event) => any) | null;\n onload: ((this: TextTrack, ev: Event) => any) | null;\n readonly readyState: number;\n addCue(cue: TextTrackCue): void;\n removeCue(cue: TextTrackCue): void;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrack: {\n prototype: TextTrack;\n new(): TextTrack;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n};\n\ninterface TextTrackCueEventMap {\n \"enter\": Event;\n \"exit\": Event;\n}\n\ninterface TextTrackCue extends EventTarget {\n endTime: number;\n id: string;\n onenter: ((this: TextTrackCue, ev: Event) => any) | null;\n onexit: ((this: TextTrackCue, ev: Event) => any) | null;\n pauseOnExit: boolean;\n startTime: number;\n text: string;\n readonly track: TextTrack;\n getCueAsHTML(): DocumentFragment;\n addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrackCue: {\n prototype: TextTrackCue;\n new(startTime: number, endTime: number, text: string): TextTrackCue;\n};\n\ninterface TextTrackCueList {\n readonly length: number;\n getCueById(id: string): TextTrackCue;\n item(index: number): TextTrackCue;\n [index: number]: TextTrackCue;\n}\n\ndeclare var TextTrackCueList: {\n prototype: TextTrackCueList;\n new(): TextTrackCueList;\n};\n\ninterface TextTrackListEventMap {\n \"addtrack\": TrackEvent;\n}\n\ninterface TextTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null;\n item(index: number): TextTrack;\n addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: TextTrack;\n}\n\ndeclare var TextTrackList: {\n prototype: TextTrackList;\n new(): TextTrackList;\n};\n\ninterface TimeRanges {\n readonly length: number;\n end(index: number): number;\n start(index: number): number;\n}\n\ndeclare var TimeRanges: {\n prototype: TimeRanges;\n new(): TimeRanges;\n};\n\ninterface Touch {\n readonly clientX: number;\n readonly clientY: number;\n readonly identifier: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly target: EventTarget;\n}\n\ndeclare var Touch: {\n prototype: Touch;\n new(): Touch;\n};\n\ninterface TouchEvent extends UIEvent {\n readonly altKey: boolean;\n readonly changedTouches: TouchList;\n readonly charCode: number;\n readonly ctrlKey: boolean;\n readonly keyCode: number;\n readonly metaKey: boolean;\n readonly shiftKey: boolean;\n readonly targetTouches: TouchList;\n readonly touches: TouchList;\n /** @deprecated */\n readonly which: number;\n}\n\ndeclare var TouchEvent: {\n prototype: TouchEvent;\n new(type: string, touchEventInit?: TouchEventInit): TouchEvent;\n};\n\ninterface TouchEventInit extends EventModifierInit {\n changedTouches?: Touch[];\n targetTouches?: Touch[];\n touches?: Touch[];\n}\n\ninterface TouchList {\n readonly length: number;\n item(index: number): Touch | null;\n [index: number]: Touch;\n}\n\ndeclare var TouchList: {\n prototype: TouchList;\n new(): TouchList;\n};\n\ninterface TrackEvent extends Event {\n readonly track: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ndeclare var TrackEvent: {\n prototype: TrackEvent;\n new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent;\n};\n\ninterface TransitionEvent extends Event {\n readonly elapsedTime: number;\n readonly propertyName: string;\n initTransitionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, propertyNameArg: string, elapsedTimeArg: number): void;\n}\n\ndeclare var TransitionEvent: {\n prototype: TransitionEvent;\n new(typeArg: string, eventInitDict?: TransitionEventInit): TransitionEvent;\n};\n\ninterface TreeWalker {\n currentNode: Node;\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n firstChild(): Node | null;\n lastChild(): Node | null;\n nextNode(): Node | null;\n nextSibling(): Node | null;\n parentNode(): Node | null;\n previousNode(): Node | null;\n previousSibling(): Node | null;\n}\n\ndeclare var TreeWalker: {\n prototype: TreeWalker;\n new(): TreeWalker;\n};\n\ninterface UIEvent extends Event {\n readonly detail: number;\n readonly view: Window;\n initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void;\n}\n\ndeclare var UIEvent: {\n prototype: UIEvent;\n new(typeArg: string, eventInitDict?: UIEventInit): UIEvent;\n};\n\ninterface URL {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n readonly searchParams: URLSearchParams;\n username: string;\n toString(): string;\n}\n\ndeclare var URL: {\n prototype: URL;\n new(url: string, base?: string | URL): URL;\n createObjectURL(object: any, options?: ObjectURLOptions): string;\n revokeObjectURL(url: string): void;\n};\n\ninterface URLSearchParams {\n /**\n * Appends a specified key/value pair as a new search parameter.\n */\n append(name: string, value: string): void;\n /**\n * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n */\n delete(name: string): void;\n /**\n * Returns the first value associated to the given search parameter.\n */\n get(name: string): string | null;\n /**\n * Returns all the values association with a given search parameter.\n */\n getAll(name: string): string[];\n /**\n * Returns a Boolean indicating if such a search parameter exists.\n */\n has(name: string): boolean;\n /**\n * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n */\n set(name: string, value: string): void;\n}\n\ndeclare var URLSearchParams: {\n prototype: URLSearchParams;\n new (init?: string | URLSearchParams): URLSearchParams;\n};\n\ninterface VRDisplay extends EventTarget {\n readonly capabilities: VRDisplayCapabilities;\n depthFar: number;\n depthNear: number;\n readonly displayId: number;\n readonly displayName: string;\n readonly isConnected: boolean;\n readonly isPresenting: boolean;\n readonly stageParameters: VRStageParameters | null;\n cancelAnimationFrame(handle: number): void;\n exitPresent(): Promise;\n getEyeParameters(whichEye: string): VREyeParameters;\n getFrameData(frameData: VRFrameData): boolean;\n getLayers(): VRLayer[];\n /** @deprecated */\n getPose(): VRPose;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n requestPresent(layers: VRLayer[]): Promise;\n resetPose(): void;\n submitFrame(pose?: VRPose): void;\n}\n\ndeclare var VRDisplay: {\n prototype: VRDisplay;\n new(): VRDisplay;\n};\n\ninterface VRDisplayCapabilities {\n readonly canPresent: boolean;\n readonly hasExternalDisplay: boolean;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly maxLayers: number;\n}\n\ndeclare var VRDisplayCapabilities: {\n prototype: VRDisplayCapabilities;\n new(): VRDisplayCapabilities;\n};\n\ninterface VRDisplayEvent extends Event {\n readonly display: VRDisplay;\n readonly reason: VRDisplayEventReason | null;\n}\n\ndeclare var VRDisplayEvent: {\n prototype: VRDisplayEvent;\n new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent;\n};\n\ninterface VREyeParameters {\n /** @deprecated */\n readonly fieldOfView: VRFieldOfView;\n readonly offset: Float32Array;\n readonly renderHeight: number;\n readonly renderWidth: number;\n}\n\ndeclare var VREyeParameters: {\n prototype: VREyeParameters;\n new(): VREyeParameters;\n};\n\ninterface VRFieldOfView {\n readonly downDegrees: number;\n readonly leftDegrees: number;\n readonly rightDegrees: number;\n readonly upDegrees: number;\n}\n\ndeclare var VRFieldOfView: {\n prototype: VRFieldOfView;\n new(): VRFieldOfView;\n};\n\ninterface VRFrameData {\n readonly leftProjectionMatrix: Float32Array;\n readonly leftViewMatrix: Float32Array;\n readonly pose: VRPose;\n readonly rightProjectionMatrix: Float32Array;\n readonly rightViewMatrix: Float32Array;\n readonly timestamp: number;\n}\n\ndeclare var VRFrameData: {\n prototype: VRFrameData;\n new(): VRFrameData;\n};\n\ninterface VRPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n readonly timestamp: number;\n}\n\ndeclare var VRPose: {\n prototype: VRPose;\n new(): VRPose;\n};\n\ninterface ValidityState {\n readonly badInput: boolean;\n readonly customError: boolean;\n readonly patternMismatch: boolean;\n readonly rangeOverflow: boolean;\n readonly rangeUnderflow: boolean;\n readonly stepMismatch: boolean;\n readonly tooLong: boolean;\n readonly tooShort: boolean;\n readonly typeMismatch: boolean;\n readonly valid: boolean;\n readonly valueMissing: boolean;\n}\n\ndeclare var ValidityState: {\n prototype: ValidityState;\n new(): ValidityState;\n};\n\ninterface VideoPlaybackQuality {\n readonly corruptedVideoFrames: number;\n readonly creationTime: number;\n readonly droppedVideoFrames: number;\n readonly totalFrameDelay: number;\n readonly totalVideoFrames: number;\n}\n\ndeclare var VideoPlaybackQuality: {\n prototype: VideoPlaybackQuality;\n new(): VideoPlaybackQuality;\n};\n\ninterface VideoTrack {\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n selected: boolean;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var VideoTrack: {\n prototype: VideoTrack;\n new(): VideoTrack;\n};\n\ninterface VideoTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface VideoTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: VideoTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n readonly selectedIndex: number;\n getTrackById(id: string): VideoTrack | null;\n item(index: number): VideoTrack;\n addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: VideoTrack;\n}\n\ndeclare var VideoTrackList: {\n prototype: VideoTrackList;\n new(): VideoTrackList;\n};\n\ninterface WEBGL_color_buffer_float {\n readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;\n readonly RGB32F_EXT: number;\n readonly RGBA32F_EXT: number;\n readonly UNSIGNED_NORMALIZED_EXT: number;\n}\n\ninterface WEBGL_compressed_texture_astc {\n readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number;\n getSupportedProfiles(): string[];\n}\n\ninterface WEBGL_compressed_texture_s3tc {\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n}\n\ndeclare var WEBGL_compressed_texture_s3tc: {\n prototype: WEBGL_compressed_texture_s3tc;\n new(): WEBGL_compressed_texture_s3tc;\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n};\n\ninterface WEBGL_compressed_texture_s3tc_srgb {\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number;\n}\n\ninterface WEBGL_debug_renderer_info {\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n}\n\ndeclare var WEBGL_debug_renderer_info: {\n prototype: WEBGL_debug_renderer_info;\n new(): WEBGL_debug_renderer_info;\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n};\n\ninterface WEBGL_debug_shaders {\n getTranslatedShaderSource(shader: WebGLShader): string;\n}\n\ninterface WEBGL_depth_texture {\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n}\n\ndeclare var WEBGL_depth_texture: {\n prototype: WEBGL_depth_texture;\n new(): WEBGL_depth_texture;\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n};\n\ninterface WEBGL_draw_buffers {\n readonly COLOR_ATTACHMENT0_WEBGL: number;\n readonly COLOR_ATTACHMENT10_WEBGL: number;\n readonly COLOR_ATTACHMENT11_WEBGL: number;\n readonly COLOR_ATTACHMENT12_WEBGL: number;\n readonly COLOR_ATTACHMENT13_WEBGL: number;\n readonly COLOR_ATTACHMENT14_WEBGL: number;\n readonly COLOR_ATTACHMENT15_WEBGL: number;\n readonly COLOR_ATTACHMENT1_WEBGL: number;\n readonly COLOR_ATTACHMENT2_WEBGL: number;\n readonly COLOR_ATTACHMENT3_WEBGL: number;\n readonly COLOR_ATTACHMENT4_WEBGL: number;\n readonly COLOR_ATTACHMENT5_WEBGL: number;\n readonly COLOR_ATTACHMENT6_WEBGL: number;\n readonly COLOR_ATTACHMENT7_WEBGL: number;\n readonly COLOR_ATTACHMENT8_WEBGL: number;\n readonly COLOR_ATTACHMENT9_WEBGL: number;\n readonly DRAW_BUFFER0_WEBGL: number;\n readonly DRAW_BUFFER10_WEBGL: number;\n readonly DRAW_BUFFER11_WEBGL: number;\n readonly DRAW_BUFFER12_WEBGL: number;\n readonly DRAW_BUFFER13_WEBGL: number;\n readonly DRAW_BUFFER14_WEBGL: number;\n readonly DRAW_BUFFER15_WEBGL: number;\n readonly DRAW_BUFFER1_WEBGL: number;\n readonly DRAW_BUFFER2_WEBGL: number;\n readonly DRAW_BUFFER3_WEBGL: number;\n readonly DRAW_BUFFER4_WEBGL: number;\n readonly DRAW_BUFFER5_WEBGL: number;\n readonly DRAW_BUFFER6_WEBGL: number;\n readonly DRAW_BUFFER7_WEBGL: number;\n readonly DRAW_BUFFER8_WEBGL: number;\n readonly DRAW_BUFFER9_WEBGL: number;\n readonly MAX_COLOR_ATTACHMENTS_WEBGL: number;\n readonly MAX_DRAW_BUFFERS_WEBGL: number;\n drawBuffersWEBGL(buffers: number[]): void;\n}\n\ninterface WEBGL_lose_context {\n loseContext(): void;\n restoreContext(): void;\n}\n\ninterface WaveShaperNode extends AudioNode {\n curve: Float32Array | null;\n oversample: OverSampleType;\n}\n\ndeclare var WaveShaperNode: {\n prototype: WaveShaperNode;\n new(): WaveShaperNode;\n};\n\ninterface WebAuthentication {\n getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise;\n makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise;\n}\n\ndeclare var WebAuthentication: {\n prototype: WebAuthentication;\n new(): WebAuthentication;\n};\n\ninterface WebAuthnAssertion {\n readonly authenticatorData: ArrayBuffer;\n readonly clientData: ArrayBuffer;\n readonly credential: ScopedCredential;\n readonly signature: ArrayBuffer;\n}\n\ndeclare var WebAuthnAssertion: {\n prototype: WebAuthnAssertion;\n new(): WebAuthnAssertion;\n};\n\ninterface WebGLActiveInfo {\n readonly name: string;\n readonly size: number;\n readonly type: number;\n}\n\ndeclare var WebGLActiveInfo: {\n prototype: WebGLActiveInfo;\n new(): WebGLActiveInfo;\n};\n\ninterface WebGLBuffer extends WebGLObject {\n}\n\ndeclare var WebGLBuffer: {\n prototype: WebGLBuffer;\n new(): WebGLBuffer;\n};\n\ninterface WebGLContextEvent extends Event {\n readonly statusMessage: string;\n}\n\ndeclare var WebGLContextEvent: {\n prototype: WebGLContextEvent;\n new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent;\n};\n\ninterface WebGLFramebuffer extends WebGLObject {\n}\n\ndeclare var WebGLFramebuffer: {\n prototype: WebGLFramebuffer;\n new(): WebGLFramebuffer;\n};\n\ninterface WebGLObject {\n}\n\ndeclare var WebGLObject: {\n prototype: WebGLObject;\n new(): WebGLObject;\n};\n\ninterface WebGLProgram extends WebGLObject {\n}\n\ndeclare var WebGLProgram: {\n prototype: WebGLProgram;\n new(): WebGLProgram;\n};\n\ninterface WebGLRenderbuffer extends WebGLObject {\n}\n\ndeclare var WebGLRenderbuffer: {\n prototype: WebGLRenderbuffer;\n new(): WebGLRenderbuffer;\n};\n\ninterface WebGLRenderingContext {\n readonly canvas: HTMLCanvasElement;\n readonly drawingBufferHeight: number;\n readonly drawingBufferWidth: number;\n activeTexture(texture: number): void;\n attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void;\n bindBuffer(target: number, buffer: WebGLBuffer | null): void;\n bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void;\n bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void;\n bindTexture(target: number, texture: WebGLTexture | null): void;\n blendColor(red: number, green: number, blue: number, alpha: number): void;\n blendEquation(mode: number): void;\n blendEquationSeparate(modeRGB: number, modeAlpha: number): void;\n blendFunc(sfactor: number, dfactor: number): void;\n blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;\n bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void;\n bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void;\n checkFramebufferStatus(target: number): number;\n clear(mask: number): void;\n clearColor(red: number, green: number, blue: number, alpha: number): void;\n clearDepth(depth: number): void;\n clearStencil(s: number): void;\n colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void;\n compileShader(shader: WebGLShader | null): void;\n compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void;\n copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void;\n createBuffer(): WebGLBuffer | null;\n createFramebuffer(): WebGLFramebuffer | null;\n createProgram(): WebGLProgram | null;\n createRenderbuffer(): WebGLRenderbuffer | null;\n createShader(type: number): WebGLShader | null;\n createTexture(): WebGLTexture | null;\n cullFace(mode: number): void;\n deleteBuffer(buffer: WebGLBuffer | null): void;\n deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void;\n deleteProgram(program: WebGLProgram | null): void;\n deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void;\n deleteShader(shader: WebGLShader | null): void;\n deleteTexture(texture: WebGLTexture | null): void;\n depthFunc(func: number): void;\n depthMask(flag: boolean): void;\n depthRange(zNear: number, zFar: number): void;\n detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n disable(cap: number): void;\n disableVertexAttribArray(index: number): void;\n drawArrays(mode: number, first: number, count: number): void;\n drawElements(mode: number, count: number, type: number, offset: number): void;\n enable(cap: number): void;\n enableVertexAttribArray(index: number): void;\n finish(): void;\n flush(): void;\n framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void;\n framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void;\n frontFace(mode: number): void;\n generateMipmap(target: number): void;\n getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null;\n getAttribLocation(program: WebGLProgram | null, name: string): number;\n getBufferParameter(target: number, pname: number): any;\n getContextAttributes(): WebGLContextAttributes;\n getError(): number;\n getExtension(extensionName: \"EXT_blend_minmax\"): EXT_blend_minmax | null;\n getExtension(extensionName: \"EXT_texture_filter_anisotropic\"): EXT_texture_filter_anisotropic | null;\n getExtension(extensionName: \"EXT_frag_depth\"): EXT_frag_depth | null;\n getExtension(extensionName: \"EXT_shader_texture_lod\"): EXT_shader_texture_lod | null;\n getExtension(extensionName: \"EXT_sRGB\"): EXT_sRGB | null;\n getExtension(extensionName: \"OES_vertex_array_object\"): OES_vertex_array_object | null;\n getExtension(extensionName: \"WEBGL_color_buffer_float\"): WEBGL_color_buffer_float | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_astc\"): WEBGL_compressed_texture_astc | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc_srgb\"): WEBGL_compressed_texture_s3tc_srgb | null;\n getExtension(extensionName: \"WEBGL_debug_shaders\"): WEBGL_debug_shaders | null;\n getExtension(extensionName: \"WEBGL_draw_buffers\"): WEBGL_draw_buffers | null;\n getExtension(extensionName: \"WEBGL_lose_context\"): WEBGL_lose_context | null;\n getExtension(extensionName: \"WEBGL_depth_texture\"): WEBGL_depth_texture | null;\n getExtension(extensionName: \"WEBGL_debug_renderer_info\"): WEBGL_debug_renderer_info | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc\"): WEBGL_compressed_texture_s3tc | null;\n getExtension(extensionName: \"OES_texture_half_float_linear\"): OES_texture_half_float_linear | null;\n getExtension(extensionName: \"OES_texture_half_float\"): OES_texture_half_float | null;\n getExtension(extensionName: \"OES_texture_float_linear\"): OES_texture_float_linear | null;\n getExtension(extensionName: \"OES_texture_float\"): OES_texture_float | null;\n getExtension(extensionName: \"OES_standard_derivatives\"): OES_standard_derivatives | null;\n getExtension(extensionName: \"OES_element_index_uint\"): OES_element_index_uint | null;\n getExtension(extensionName: \"ANGLE_instanced_arrays\"): ANGLE_instanced_arrays | null;\n getExtension(extensionName: string): any;\n getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any;\n getParameter(pname: number): any;\n getProgramInfoLog(program: WebGLProgram | null): string | null;\n getProgramParameter(program: WebGLProgram | null, pname: number): any;\n getRenderbufferParameter(target: number, pname: number): any;\n getShaderInfoLog(shader: WebGLShader | null): string | null;\n getShaderParameter(shader: WebGLShader | null, pname: number): any;\n getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null;\n getShaderSource(shader: WebGLShader | null): string | null;\n getSupportedExtensions(): string[] | null;\n getTexParameter(target: number, pname: number): any;\n getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any;\n getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null;\n getVertexAttrib(index: number, pname: number): any;\n getVertexAttribOffset(index: number, pname: number): number;\n hint(target: number, mode: number): void;\n isBuffer(buffer: WebGLBuffer | null): boolean;\n isContextLost(): boolean;\n isEnabled(cap: number): boolean;\n isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean;\n isProgram(program: WebGLProgram | null): boolean;\n isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean;\n isShader(shader: WebGLShader | null): boolean;\n isTexture(texture: WebGLTexture | null): boolean;\n lineWidth(width: number): void;\n linkProgram(program: WebGLProgram | null): void;\n pixelStorei(pname: number, param: number | boolean): void;\n polygonOffset(factor: number, units: number): void;\n readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n renderbufferStorage(target: number, internalformat: number, width: number, height: number): void;\n sampleCoverage(value: number, invert: boolean): void;\n scissor(x: number, y: number, width: number, height: number): void;\n shaderSource(shader: WebGLShader | null, source: string): void;\n stencilFunc(func: number, ref: number, mask: number): void;\n stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void;\n stencilMask(mask: number): void;\n stencilMaskSeparate(face: number, mask: number): void;\n stencilOp(fail: number, zfail: number, zpass: number): void;\n stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void;\n texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n texParameterf(target: number, pname: number, param: number): void;\n texParameteri(target: number, pname: number, param: number): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n uniform1f(location: WebGLUniformLocation | null, x: number): void;\n uniform1fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform1i(location: WebGLUniformLocation | null, x: number): void;\n uniform1iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4fv(location: WebGLUniformLocation, v: Float32Array | ArrayLike): void;\n uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4iv(location: WebGLUniformLocation, v: Int32Array | ArrayLike): void;\n uniformMatrix2fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix3fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix4fv(location: WebGLUniformLocation, transpose: boolean, value: Float32Array | ArrayLike): void;\n useProgram(program: WebGLProgram | null): void;\n validateProgram(program: WebGLProgram | null): void;\n vertexAttrib1f(indx: number, x: number): void;\n vertexAttrib1fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib2f(indx: number, x: number, y: number): void;\n vertexAttrib2fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib3f(indx: number, x: number, y: number, z: number): void;\n vertexAttrib3fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void;\n vertexAttrib4fv(indx: number, values: Float32Array | number[]): void;\n vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void;\n viewport(x: number, y: number, width: number, height: number): void;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n}\n\ndeclare var WebGLRenderingContext: {\n prototype: WebGLRenderingContext;\n new(): WebGLRenderingContext;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n};\n\ninterface WebGLShader extends WebGLObject {\n}\n\ndeclare var WebGLShader: {\n prototype: WebGLShader;\n new(): WebGLShader;\n};\n\ninterface WebGLShaderPrecisionFormat {\n readonly precision: number;\n readonly rangeMax: number;\n readonly rangeMin: number;\n}\n\ndeclare var WebGLShaderPrecisionFormat: {\n prototype: WebGLShaderPrecisionFormat;\n new(): WebGLShaderPrecisionFormat;\n};\n\ninterface WebGLTexture extends WebGLObject {\n}\n\ndeclare var WebGLTexture: {\n prototype: WebGLTexture;\n new(): WebGLTexture;\n};\n\ninterface WebGLUniformLocation {\n}\n\ndeclare var WebGLUniformLocation: {\n prototype: WebGLUniformLocation;\n new(): WebGLUniformLocation;\n};\n\ninterface WebGLVertexArrayObjectOES {\n}\n\ninterface WebKitCSSMatrix {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n m11: number;\n m12: number;\n m13: number;\n m14: number;\n m21: number;\n m22: number;\n m23: number;\n m24: number;\n m31: number;\n m32: number;\n m33: number;\n m34: number;\n m41: number;\n m42: number;\n m43: number;\n m44: number;\n inverse(): WebKitCSSMatrix;\n multiply(secondMatrix: WebKitCSSMatrix): WebKitCSSMatrix;\n rotate(angleX: number, angleY?: number, angleZ?: number): WebKitCSSMatrix;\n rotateAxisAngle(x: number, y: number, z: number, angle: number): WebKitCSSMatrix;\n scale(scaleX: number, scaleY?: number, scaleZ?: number): WebKitCSSMatrix;\n setMatrixValue(value: string): void;\n skewX(angle: number): WebKitCSSMatrix;\n skewY(angle: number): WebKitCSSMatrix;\n toString(): string;\n translate(x: number, y: number, z?: number): WebKitCSSMatrix;\n}\n\ndeclare var WebKitCSSMatrix: {\n prototype: WebKitCSSMatrix;\n new(text?: string): WebKitCSSMatrix;\n};\n\ninterface WebKitDirectoryEntry extends WebKitEntry {\n createReader(): WebKitDirectoryReader;\n}\n\ndeclare var WebKitDirectoryEntry: {\n prototype: WebKitDirectoryEntry;\n new(): WebKitDirectoryEntry;\n};\n\ninterface WebKitDirectoryReader {\n readEntries(successCallback: WebKitEntriesCallback, errorCallback?: WebKitErrorCallback): void;\n}\n\ndeclare var WebKitDirectoryReader: {\n prototype: WebKitDirectoryReader;\n new(): WebKitDirectoryReader;\n};\n\ninterface WebKitEntry {\n readonly filesystem: WebKitFileSystem;\n readonly fullPath: string;\n readonly isDirectory: boolean;\n readonly isFile: boolean;\n readonly name: string;\n}\n\ndeclare var WebKitEntry: {\n prototype: WebKitEntry;\n new(): WebKitEntry;\n};\n\ninterface WebKitFileEntry extends WebKitEntry {\n file(successCallback: WebKitFileCallback, errorCallback?: WebKitErrorCallback): void;\n}\n\ndeclare var WebKitFileEntry: {\n prototype: WebKitFileEntry;\n new(): WebKitFileEntry;\n};\n\ninterface WebKitFileSystem {\n readonly name: string;\n readonly root: WebKitDirectoryEntry;\n}\n\ndeclare var WebKitFileSystem: {\n prototype: WebKitFileSystem;\n new(): WebKitFileSystem;\n};\n\ninterface WebKitPoint {\n x: number;\n y: number;\n}\n\ndeclare var WebKitPoint: {\n prototype: WebKitPoint;\n new(x?: number, y?: number): WebKitPoint;\n};\n\ninterface WebSocketEventMap {\n \"close\": CloseEvent;\n \"error\": Event;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface WebSocket extends EventTarget {\n binaryType: BinaryType;\n readonly bufferedAmount: number;\n readonly extensions: string;\n onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;\n onerror: ((this: WebSocket, ev: Event) => any) | null;\n onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;\n onopen: ((this: WebSocket, ev: Event) => any) | null;\n readonly protocol: string;\n readonly readyState: number;\n readonly url: string;\n close(code?: number, reason?: string): void;\n send(data: string | ArrayBuffer | Blob | ArrayBufferView): void;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var WebSocket: {\n prototype: WebSocket;\n new(url: string, protocols?: string | string[]): WebSocket;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n};\n\ninterface WheelEvent extends MouseEvent {\n readonly deltaMode: number;\n readonly deltaX: number;\n readonly deltaY: number;\n readonly deltaZ: number;\n readonly wheelDelta: number;\n readonly wheelDeltaX: number;\n readonly wheelDeltaY: number;\n getCurrentPoint(element: Element): void;\n initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n}\n\ndeclare var WheelEvent: {\n prototype: WheelEvent;\n new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n};\n\ninterface WindowEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"beforeunload\": BeforeUnloadEvent;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"compassneedscalibration\": Event;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"devicelight\": DeviceLightEvent;\n \"devicemotion\": DeviceMotionEvent;\n \"deviceorientation\": DeviceOrientationEvent;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"hashchange\": HashChangeEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"message\": MessageEvent;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"offline\": Event;\n \"online\": Event;\n \"orientationchange\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"popstate\": PopStateEvent;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": ProgressEvent;\n \"reset\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"stalled\": Event;\n \"storage\": StorageEvent;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": Event;\n \"touchend\": Event;\n \"touchmove\": Event;\n \"touchstart\": Event;\n \"unload\": Event;\n \"volumechange\": Event;\n \"vrdisplayactivate\": Event;\n \"vrdisplayblur\": Event;\n \"vrdisplayconnect\": Event;\n \"vrdisplaydeactivate\": Event;\n \"vrdisplaydisconnect\": Event;\n \"vrdisplayfocus\": Event;\n \"vrdisplaypointerrestricted\": Event;\n \"vrdisplaypointerunrestricted\": Event;\n \"vrdisplaypresentchange\": Event;\n \"waiting\": Event;\n}\n\ninterface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {\n Blob: typeof Blob;\n URL: typeof URL;\n URLSearchParams: typeof URLSearchParams;\n readonly applicationCache: ApplicationCache;\n readonly caches: CacheStorage;\n readonly clientInformation: Navigator;\n readonly closed: boolean;\n readonly crypto: Crypto;\n customElements: CustomElementRegistry;\n defaultStatus: string;\n readonly devicePixelRatio: number;\n readonly doNotTrack: string;\n readonly document: Document;\n event: Event | undefined;\n readonly external: External;\n readonly frameElement: Element;\n readonly frames: Window;\n readonly history: History;\n readonly innerHeight: number;\n readonly innerWidth: number;\n readonly isSecureContext: boolean;\n readonly length: number;\n location: Location;\n readonly locationbar: BarProp;\n readonly menubar: BarProp;\n readonly msContentScript: ExtensionScriptApis;\n readonly msCredentials: MSCredentials;\n name: string;\n readonly navigator: Navigator;\n offscreenBuffering: string | boolean;\n onabort: ((this: Window, ev: UIEvent) => any) | null;\n onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\n onblur: ((this: Window, ev: FocusEvent) => any) | null;\n oncanplay: ((this: Window, ev: Event) => any) | null;\n oncanplaythrough: ((this: Window, ev: Event) => any) | null;\n onchange: ((this: Window, ev: Event) => any) | null;\n onclick: ((this: Window, ev: MouseEvent) => any) | null;\n oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\n oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\n ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\n ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\n ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\n ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\n ondrag: ((this: Window, ev: DragEvent) => any) | null;\n ondragend: ((this: Window, ev: DragEvent) => any) | null;\n ondragenter: ((this: Window, ev: DragEvent) => any) | null;\n ondragleave: ((this: Window, ev: DragEvent) => any) | null;\n ondragover: ((this: Window, ev: DragEvent) => any) | null;\n ondragstart: ((this: Window, ev: DragEvent) => any) | null;\n ondrop: ((this: Window, ev: DragEvent) => any) | null;\n ondurationchange: ((this: Window, ev: Event) => any) | null;\n onemptied: ((this: Window, ev: Event) => any) | null;\n onended: ((this: Window, ev: Event) => any) | null;\n onerror: ErrorEventHandler;\n onfocus: ((this: Window, ev: FocusEvent) => any) | null;\n onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\n oninput: ((this: Window, ev: Event) => any) | null;\n oninvalid: ((this: Window, ev: Event) => any) | null;\n onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\n onload: ((this: Window, ev: Event) => any) | null;\n onloadeddata: ((this: Window, ev: Event) => any) | null;\n onloadedmetadata: ((this: Window, ev: Event) => any) | null;\n onloadstart: ((this: Window, ev: Event) => any) | null;\n onmessage: ((this: Window, ev: MessageEvent) => any) | null;\n onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\n onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\n onmsgesturechange: ((this: Window, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\n onmsgestureend: ((this: Window, ev: Event) => any) | null;\n onmsgesturehold: ((this: Window, ev: Event) => any) | null;\n onmsgesturestart: ((this: Window, ev: Event) => any) | null;\n onmsgesturetap: ((this: Window, ev: Event) => any) | null;\n onmsinertiastart: ((this: Window, ev: Event) => any) | null;\n onmspointercancel: ((this: Window, ev: Event) => any) | null;\n onmspointerdown: ((this: Window, ev: Event) => any) | null;\n onmspointerenter: ((this: Window, ev: Event) => any) | null;\n onmspointerleave: ((this: Window, ev: Event) => any) | null;\n onmspointermove: ((this: Window, ev: Event) => any) | null;\n onmspointerout: ((this: Window, ev: Event) => any) | null;\n onmspointerover: ((this: Window, ev: Event) => any) | null;\n onmspointerup: ((this: Window, ev: Event) => any) | null;\n onoffline: ((this: Window, ev: Event) => any) | null;\n ononline: ((this: Window, ev: Event) => any) | null;\n onorientationchange: ((this: Window, ev: Event) => any) | null;\n onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpause: ((this: Window, ev: Event) => any) | null;\n onplay: ((this: Window, ev: Event) => any) | null;\n onplaying: ((this: Window, ev: Event) => any) | null;\n onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\n onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\n onratechange: ((this: Window, ev: Event) => any) | null;\n onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\n onreset: ((this: Window, ev: Event) => any) | null;\n onresize: ((this: Window, ev: UIEvent) => any) | null;\n onscroll: ((this: Window, ev: UIEvent) => any) | null;\n onseeked: ((this: Window, ev: Event) => any) | null;\n onseeking: ((this: Window, ev: Event) => any) | null;\n onselect: ((this: Window, ev: UIEvent) => any) | null;\n onstalled: ((this: Window, ev: Event) => any) | null;\n onstorage: ((this: Window, ev: StorageEvent) => any) | null;\n onsubmit: ((this: Window, ev: Event) => any) | null;\n onsuspend: ((this: Window, ev: Event) => any) | null;\n ontimeupdate: ((this: Window, ev: Event) => any) | null;\n ontouchcancel: (ev: TouchEvent) => any;\n ontouchend: (ev: TouchEvent) => any;\n ontouchmove: (ev: TouchEvent) => any;\n ontouchstart: (ev: TouchEvent) => any;\n onunload: ((this: Window, ev: Event) => any) | null;\n onvolumechange: ((this: Window, ev: Event) => any) | null;\n onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\n onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\n onwaiting: ((this: Window, ev: Event) => any) | null;\n readonly opener: any;\n readonly orientation: string | number;\n readonly outerHeight: number;\n readonly outerWidth: number;\n readonly pageXOffset: number;\n readonly pageYOffset: number;\n readonly parent: Window;\n readonly performance: Performance;\n readonly personalbar: BarProp;\n readonly screen: Screen;\n readonly screenLeft: number;\n readonly screenTop: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly scrollX: number;\n readonly scrollY: number;\n readonly scrollbars: BarProp;\n readonly self: Window;\n readonly speechSynthesis: SpeechSynthesis;\n status: string;\n readonly statusbar: BarProp;\n readonly styleMedia: StyleMedia;\n readonly toolbar: BarProp;\n readonly top: Window;\n readonly window: Window;\n alert(message?: any): void;\n blur(): void;\n cancelAnimationFrame(handle: number): void;\n captureEvents(): void;\n close(): void;\n confirm(message?: string): boolean;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\n departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\n focus(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\n getSelection(): Selection;\n matchMedia(mediaQuery: string): MediaQueryList;\n moveBy(x?: number, y?: number): void;\n moveTo(x?: number, y?: number): void;\n msWriteProfilerMark(profilerMarkName: string): void;\n open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\n postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\n prompt(message?: string, _default?: string): string | null;\n releaseEvents(): void;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n resizeBy(x?: number, y?: number): void;\n resizeTo(x?: number, y?: number): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x?: number, y?: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x?: number, y?: number): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x?: number, y?: number): void;\n stop(): void;\n webkitCancelAnimationFrame(handle: number): void;\n webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\n addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Window: {\n prototype: Window;\n new(): Window;\n};\n\ninterface WindowBase64 {\n atob(encodedString: string): string;\n btoa(rawString: string): string;\n}\n\ninterface WindowConsole {\n readonly console: Console;\n}\n\ninterface WindowEventHandlersEventMap {\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"hashchange\": HashChangeEvent;\n \"message\": MessageEvent;\n \"offline\": Event;\n \"online\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"popstate\": PopStateEvent;\n \"storage\": StorageEvent;\n \"unload\": Event;\n}\n\ninterface WindowEventHandlers {\n onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null;\n onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null;\n onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null;\n onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n ononline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null;\n onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null;\n onunload: ((this: WindowEventHandlers, ev: Event) => any) | null;\n addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface WindowLocalStorage {\n readonly localStorage: Storage;\n}\n\ninterface WindowSessionStorage {\n readonly sessionStorage: Storage;\n}\n\ninterface WindowTimers extends WindowTimersExtension {\n clearInterval(handle?: number): void;\n clearTimeout(handle?: number): void;\n setInterval(handler: (...args: any[]) => void, timeout: number): number;\n setInterval(handler: any, timeout?: any, ...args: any[]): number;\n setTimeout(handler: (...args: any[]) => void, timeout: number): number;\n setTimeout(handler: any, timeout?: any, ...args: any[]): number;\n}\n\ninterface WindowTimersExtension {\n clearImmediate(handle: number): void;\n setImmediate(handler: (...args: any[]) => void): number;\n setImmediate(handler: any, ...args: any[]): number;\n}\n\ninterface WorkerEventMap extends AbstractWorkerEventMap {\n \"message\": MessageEvent;\n}\n\ninterface Worker extends EventTarget, AbstractWorker {\n onmessage: ((this: Worker, ev: MessageEvent) => any) | null;\n /** @deprecated */\n postMessage(message: any, transfer?: any[]): void;\n terminate(): void;\n addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Worker: {\n prototype: Worker;\n new(stringUrl: string): Worker;\n};\n\ninterface WritableStream {\n readonly locked: boolean;\n abort(reason?: any): Promise;\n getWriter(): WritableStreamDefaultWriter;\n}\n\ndeclare var WritableStream: {\n prototype: WritableStream;\n new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream;\n};\n\ninterface WritableStreamDefaultController {\n error(error?: any): void;\n}\n\ndeclare var WritableStreamDefaultController: {\n prototype: WritableStreamDefaultController;\n new(): WritableStreamDefaultController;\n};\n\ninterface WritableStreamDefaultWriter {\n readonly closed: Promise;\n readonly desiredSize: number;\n readonly ready: Promise;\n abort(reason?: any): Promise;\n close(): Promise;\n releaseLock(): void;\n write(chunk?: any): Promise;\n}\n\ndeclare var WritableStreamDefaultWriter: {\n prototype: WritableStreamDefaultWriter;\n new(): WritableStreamDefaultWriter;\n};\n\ninterface XMLDocument extends Document {\n addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLDocument: {\n prototype: XMLDocument;\n new(): XMLDocument;\n};\n\ninterface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {\n \"readystatechange\": Event;\n}\n\ninterface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {\n msCaching: string;\n onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;\n readonly readyState: number;\n readonly response: any;\n readonly responseText: string;\n responseType: XMLHttpRequestResponseType;\n readonly responseURL: string;\n readonly responseXML: Document | null;\n readonly status: number;\n readonly statusText: string;\n timeout: number;\n readonly upload: XMLHttpRequestUpload;\n withCredentials: boolean;\n abort(): void;\n getAllResponseHeaders(): string;\n getResponseHeader(header: string): string | null;\n msCachingEnabled(): boolean;\n open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): void;\n overrideMimeType(mime: string): void;\n send(data?: any): void;\n setRequestHeader(header: string, value: string): void;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequest: {\n prototype: XMLHttpRequest;\n new(): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\n\ninterface XMLHttpRequestEventTargetEventMap {\n \"abort\": Event;\n \"error\": ErrorEvent;\n \"load\": Event;\n \"loadend\": ProgressEvent;\n \"loadstart\": Event;\n \"progress\": ProgressEvent;\n \"timeout\": ProgressEvent;\n}\n\ninterface XMLHttpRequestEventTarget {\n onabort: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onerror: ((this: XMLHttpRequest, ev: ErrorEvent) => any) | null;\n onload: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null;\n onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {\n addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestUpload: {\n prototype: XMLHttpRequestUpload;\n new(): XMLHttpRequestUpload;\n};\n\ninterface XMLSerializer {\n serializeToString(target: Node): string;\n}\n\ndeclare var XMLSerializer: {\n prototype: XMLSerializer;\n new(): XMLSerializer;\n};\n\ninterface XPathEvaluator {\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver?: Node): XPathNSResolver;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathEvaluator: {\n prototype: XPathEvaluator;\n new(): XPathEvaluator;\n};\n\ninterface XPathExpression {\n evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathExpression: {\n prototype: XPathExpression;\n new(): XPathExpression;\n};\n\ninterface XPathNSResolver {\n lookupNamespaceURI(prefix: string): string;\n}\n\ndeclare var XPathNSResolver: {\n prototype: XPathNSResolver;\n new(): XPathNSResolver;\n};\n\ninterface XPathResult {\n readonly booleanValue: boolean;\n readonly invalidIteratorState: boolean;\n readonly numberValue: number;\n readonly resultType: number;\n readonly singleNodeValue: Node;\n readonly snapshotLength: number;\n readonly stringValue: string;\n iterateNext(): Node;\n snapshotItem(index: number): Node;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n}\n\ndeclare var XPathResult: {\n prototype: XPathResult;\n new(): XPathResult;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n};\n\ninterface XSLTProcessor {\n clearParameters(): void;\n getParameter(namespaceURI: string, localName: string): any;\n importStylesheet(style: Node): void;\n removeParameter(namespaceURI: string, localName: string): void;\n reset(): void;\n setParameter(namespaceURI: string, localName: string, value: any): void;\n transformToDocument(source: Node): Document;\n transformToFragment(source: Node, document: Document): DocumentFragment;\n}\n\ndeclare var XSLTProcessor: {\n prototype: XSLTProcessor;\n new(): XSLTProcessor;\n};\n\ninterface webkitRTCPeerConnection extends RTCPeerConnection {\n addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var webkitRTCPeerConnection: {\n prototype: webkitRTCPeerConnection;\n new(configuration: RTCConfiguration): webkitRTCPeerConnection;\n};\n\ndeclare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;\n\ninterface DecodeErrorCallback {\n (error: DOMException): void;\n}\n\ninterface DecodeSuccessCallback {\n (decodedData: AudioBuffer): void;\n}\n\ninterface ErrorEventHandler {\n (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void;\n}\n\ninterface EventHandlerNonNull {\n (event: Event): any;\n}\n\ninterface ForEachCallback {\n (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void;\n}\n\ninterface FrameRequestCallback {\n (time: number): void;\n}\n\ninterface FunctionStringCallback {\n (data: string): void;\n}\n\ninterface IntersectionObserverCallback {\n (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;\n}\n\ninterface MSLaunchUriCallback {\n (): void;\n}\n\ninterface MediaQueryListListener {\n (mql: MediaQueryList): void;\n}\n\ninterface MutationCallback {\n (mutations: MutationRecord[], observer: MutationObserver): void;\n}\n\ninterface NavigatorUserMediaErrorCallback {\n (error: MediaStreamError): void;\n}\n\ninterface NavigatorUserMediaSuccessCallback {\n (stream: MediaStream): void;\n}\n\ninterface NotificationPermissionCallback {\n (permission: NotificationPermission): void;\n}\n\ninterface PositionCallback {\n (position: Position): void;\n}\n\ninterface PositionErrorCallback {\n (error: PositionError): void;\n}\n\ninterface RTCPeerConnectionErrorCallback {\n (error: DOMError): void;\n}\n\ninterface RTCSessionDescriptionCallback {\n (sdp: RTCSessionDescription): void;\n}\n\ninterface RTCStatsCallback {\n (report: RTCStatsReport): void;\n}\n\ninterface VoidFunction {\n (): void;\n}\n\ninterface WritableStreamChunkCallback {\n (chunk: any, controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamDefaultControllerCallback {\n (controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamErrorCallback {\n (reason: string): void;\n}\n\ninterface HTMLElementTagNameMap {\n \"a\": HTMLAnchorElement;\n \"abbr\": HTMLElement;\n \"acronym\": HTMLElement;\n \"address\": HTMLElement;\n \"applet\": HTMLAppletElement;\n \"area\": HTMLAreaElement;\n \"article\": HTMLElement;\n \"aside\": HTMLElement;\n \"audio\": HTMLAudioElement;\n \"b\": HTMLElement;\n \"base\": HTMLBaseElement;\n \"basefont\": HTMLBaseFontElement;\n \"bdo\": HTMLElement;\n \"big\": HTMLElement;\n \"blockquote\": HTMLQuoteElement;\n \"body\": HTMLBodyElement;\n \"br\": HTMLBRElement;\n \"button\": HTMLButtonElement;\n \"canvas\": HTMLCanvasElement;\n \"caption\": HTMLTableCaptionElement;\n \"center\": HTMLElement;\n \"cite\": HTMLElement;\n \"code\": HTMLElement;\n \"col\": HTMLTableColElement;\n \"colgroup\": HTMLTableColElement;\n \"data\": HTMLDataElement;\n \"datalist\": HTMLDataListElement;\n \"dd\": HTMLElement;\n \"del\": HTMLModElement;\n \"dfn\": HTMLElement;\n \"dir\": HTMLDirectoryElement;\n \"div\": HTMLDivElement;\n \"dl\": HTMLDListElement;\n \"dt\": HTMLElement;\n \"em\": HTMLElement;\n \"embed\": HTMLEmbedElement;\n \"fieldset\": HTMLFieldSetElement;\n \"figcaption\": HTMLElement;\n \"figure\": HTMLElement;\n \"font\": HTMLFontElement;\n \"footer\": HTMLElement;\n \"form\": HTMLFormElement;\n \"frame\": HTMLFrameElement;\n \"frameset\": HTMLFrameSetElement;\n \"h1\": HTMLHeadingElement;\n \"h2\": HTMLHeadingElement;\n \"h3\": HTMLHeadingElement;\n \"h4\": HTMLHeadingElement;\n \"h5\": HTMLHeadingElement;\n \"h6\": HTMLHeadingElement;\n \"head\": HTMLHeadElement;\n \"header\": HTMLElement;\n \"hgroup\": HTMLElement;\n \"hr\": HTMLHRElement;\n \"html\": HTMLHtmlElement;\n \"i\": HTMLElement;\n \"iframe\": HTMLIFrameElement;\n \"img\": HTMLImageElement;\n \"input\": HTMLInputElement;\n \"ins\": HTMLModElement;\n \"isindex\": HTMLUnknownElement;\n \"kbd\": HTMLElement;\n \"keygen\": HTMLElement;\n \"label\": HTMLLabelElement;\n \"legend\": HTMLLegendElement;\n \"li\": HTMLLIElement;\n \"link\": HTMLLinkElement;\n \"listing\": HTMLPreElement;\n \"map\": HTMLMapElement;\n \"mark\": HTMLElement;\n \"marquee\": HTMLMarqueeElement;\n \"menu\": HTMLMenuElement;\n \"meta\": HTMLMetaElement;\n \"meter\": HTMLMeterElement;\n \"nav\": HTMLElement;\n \"nextid\": HTMLUnknownElement;\n \"nobr\": HTMLElement;\n \"noframes\": HTMLElement;\n \"noscript\": HTMLElement;\n \"object\": HTMLObjectElement;\n \"ol\": HTMLOListElement;\n \"optgroup\": HTMLOptGroupElement;\n \"option\": HTMLOptionElement;\n \"output\": HTMLOutputElement;\n \"p\": HTMLParagraphElement;\n \"param\": HTMLParamElement;\n \"picture\": HTMLPictureElement;\n \"plaintext\": HTMLElement;\n \"pre\": HTMLPreElement;\n \"progress\": HTMLProgressElement;\n \"q\": HTMLQuoteElement;\n \"rt\": HTMLElement;\n \"ruby\": HTMLElement;\n \"s\": HTMLElement;\n \"samp\": HTMLElement;\n \"script\": HTMLScriptElement;\n \"section\": HTMLElement;\n \"select\": HTMLSelectElement;\n \"slot\": HTMLSlotElement;\n \"small\": HTMLElement;\n \"source\": HTMLSourceElement;\n \"span\": HTMLSpanElement;\n \"strike\": HTMLElement;\n \"strong\": HTMLElement;\n \"style\": HTMLStyleElement;\n \"sub\": HTMLElement;\n \"sup\": HTMLElement;\n \"table\": HTMLTableElement;\n \"tbody\": HTMLTableSectionElement;\n \"td\": HTMLTableDataCellElement;\n \"template\": HTMLTemplateElement;\n \"textarea\": HTMLTextAreaElement;\n \"tfoot\": HTMLTableSectionElement;\n \"th\": HTMLTableHeaderCellElement;\n \"thead\": HTMLTableSectionElement;\n \"time\": HTMLTimeElement;\n \"title\": HTMLTitleElement;\n \"tr\": HTMLTableRowElement;\n \"track\": HTMLTrackElement;\n \"tt\": HTMLElement;\n \"u\": HTMLElement;\n \"ul\": HTMLUListElement;\n \"var\": HTMLElement;\n \"video\": HTMLVideoElement;\n \"wbr\": HTMLElement;\n \"xmp\": HTMLPreElement;\n}\n\ninterface SVGElementTagNameMap {\n \"circle\": SVGCircleElement;\n \"clippath\": SVGClipPathElement;\n \"defs\": SVGDefsElement;\n \"desc\": SVGDescElement;\n \"ellipse\": SVGEllipseElement;\n \"feblend\": SVGFEBlendElement;\n \"fecolormatrix\": SVGFEColorMatrixElement;\n \"fecomponenttransfer\": SVGFEComponentTransferElement;\n \"fecomposite\": SVGFECompositeElement;\n \"feconvolvematrix\": SVGFEConvolveMatrixElement;\n \"fediffuselighting\": SVGFEDiffuseLightingElement;\n \"fedisplacementmap\": SVGFEDisplacementMapElement;\n \"fedistantlight\": SVGFEDistantLightElement;\n \"feflood\": SVGFEFloodElement;\n \"fefunca\": SVGFEFuncAElement;\n \"fefuncb\": SVGFEFuncBElement;\n \"fefuncg\": SVGFEFuncGElement;\n \"fefuncr\": SVGFEFuncRElement;\n \"fegaussianblur\": SVGFEGaussianBlurElement;\n \"feimage\": SVGFEImageElement;\n \"femerge\": SVGFEMergeElement;\n \"femergenode\": SVGFEMergeNodeElement;\n \"femorphology\": SVGFEMorphologyElement;\n \"feoffset\": SVGFEOffsetElement;\n \"fepointlight\": SVGFEPointLightElement;\n \"fespecularlighting\": SVGFESpecularLightingElement;\n \"fespotlight\": SVGFESpotLightElement;\n \"fetile\": SVGFETileElement;\n \"feturbulence\": SVGFETurbulenceElement;\n \"filter\": SVGFilterElement;\n \"foreignobject\": SVGForeignObjectElement;\n \"g\": SVGGElement;\n \"image\": SVGImageElement;\n \"line\": SVGLineElement;\n \"lineargradient\": SVGLinearGradientElement;\n \"marker\": SVGMarkerElement;\n \"mask\": SVGMaskElement;\n \"metadata\": SVGMetadataElement;\n \"path\": SVGPathElement;\n \"pattern\": SVGPatternElement;\n \"polygon\": SVGPolygonElement;\n \"polyline\": SVGPolylineElement;\n \"radialgradient\": SVGRadialGradientElement;\n \"rect\": SVGRectElement;\n \"stop\": SVGStopElement;\n \"svg\": SVGSVGElement;\n \"switch\": SVGSwitchElement;\n \"symbol\": SVGSymbolElement;\n \"text\": SVGTextElement;\n \"textpath\": SVGTextPathElement;\n \"tspan\": SVGTSpanElement;\n \"use\": SVGUseElement;\n \"view\": SVGViewElement;\n}\n\n/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */\ninterface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { }\n\ndeclare var Audio: {\n new(src?: string): HTMLAudioElement;\n};\ndeclare var Image: {\n new(width?: number, height?: number): HTMLImageElement;\n};\ndeclare var Option: {\n new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement;\n};\ndeclare var Blob: typeof Blob;\ndeclare var URL: typeof URL;\ndeclare var URLSearchParams: typeof URLSearchParams;\ndeclare var applicationCache: ApplicationCache;\ndeclare var caches: CacheStorage;\ndeclare var clientInformation: Navigator;\ndeclare var closed: boolean;\ndeclare var crypto: Crypto;\ndeclare var customElements: CustomElementRegistry;\ndeclare var defaultStatus: string;\ndeclare var devicePixelRatio: number;\ndeclare var doNotTrack: string;\ndeclare var document: Document;\ndeclare var event: Event | undefined;\ndeclare var external: External;\ndeclare var frameElement: Element;\ndeclare var frames: Window;\ndeclare var history: History;\ndeclare var innerHeight: number;\ndeclare var innerWidth: number;\ndeclare var isSecureContext: boolean;\ndeclare var length: number;\ndeclare var location: Location;\ndeclare var locationbar: BarProp;\ndeclare var menubar: BarProp;\ndeclare var msContentScript: ExtensionScriptApis;\ndeclare var msCredentials: MSCredentials;\ndeclare const name: never;\ndeclare var navigator: Navigator;\ndeclare var offscreenBuffering: string | boolean;\ndeclare var onabort: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\ndeclare var onblur: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var oncanplay: ((this: Window, ev: Event) => any) | null;\ndeclare var oncanplaythrough: ((this: Window, ev: Event) => any) | null;\ndeclare var onchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\ndeclare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\ndeclare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\ndeclare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\ndeclare var ondrag: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragend: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragenter: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragleave: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragover: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragstart: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondrop: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondurationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onemptied: ((this: Window, ev: Event) => any) | null;\ndeclare var onended: ((this: Window, ev: Event) => any) | null;\ndeclare var onerror: ErrorEventHandler;\ndeclare var onfocus: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\ndeclare var oninput: ((this: Window, ev: Event) => any) | null;\ndeclare var oninvalid: ((this: Window, ev: Event) => any) | null;\ndeclare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onload: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadeddata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadedmetadata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadstart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;\ndeclare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var onmsgesturechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgestureend: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturehold: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturestart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturetap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsinertiastart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointercancel: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerdown: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerenter: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerleave: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointermove: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerout: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerover: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerup: ((this: Window, ev: Event) => any) | null;\ndeclare var onoffline: ((this: Window, ev: Event) => any) | null;\ndeclare var ononline: ((this: Window, ev: Event) => any) | null;\ndeclare var onorientationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpause: ((this: Window, ev: Event) => any) | null;\ndeclare var onplay: ((this: Window, ev: Event) => any) | null;\ndeclare var onplaying: ((this: Window, ev: Event) => any) | null;\ndeclare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\ndeclare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onratechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onreset: ((this: Window, ev: Event) => any) | null;\ndeclare var onresize: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onscroll: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onseeked: ((this: Window, ev: Event) => any) | null;\ndeclare var onseeking: ((this: Window, ev: Event) => any) | null;\ndeclare var onselect: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onstalled: ((this: Window, ev: Event) => any) | null;\ndeclare var onstorage: ((this: Window, ev: StorageEvent) => any) | null;\ndeclare var onsubmit: ((this: Window, ev: Event) => any) | null;\ndeclare var onsuspend: ((this: Window, ev: Event) => any) | null;\ndeclare var ontimeupdate: ((this: Window, ev: Event) => any) | null;\ndeclare var ontouchcancel: (ev: TouchEvent) => any;\ndeclare var ontouchend: (ev: TouchEvent) => any;\ndeclare var ontouchmove: (ev: TouchEvent) => any;\ndeclare var ontouchstart: (ev: TouchEvent) => any;\ndeclare var onunload: ((this: Window, ev: Event) => any) | null;\ndeclare var onvolumechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onwaiting: ((this: Window, ev: Event) => any) | null;\ndeclare var opener: any;\ndeclare var orientation: string | number;\ndeclare var outerHeight: number;\ndeclare var outerWidth: number;\ndeclare var pageXOffset: number;\ndeclare var pageYOffset: number;\ndeclare var parent: Window;\ndeclare var performance: Performance;\ndeclare var personalbar: BarProp;\ndeclare var screen: Screen;\ndeclare var screenLeft: number;\ndeclare var screenTop: number;\ndeclare var screenX: number;\ndeclare var screenY: number;\ndeclare var scrollX: number;\ndeclare var scrollY: number;\ndeclare var scrollbars: BarProp;\ndeclare var self: Window;\ndeclare var speechSynthesis: SpeechSynthesis;\ndeclare var status: string;\ndeclare var statusbar: BarProp;\ndeclare var styleMedia: StyleMedia;\ndeclare var toolbar: BarProp;\ndeclare var top: Window;\ndeclare var window: Window;\ndeclare function alert(message?: any): void;\ndeclare function blur(): void;\ndeclare function cancelAnimationFrame(handle: number): void;\ndeclare function captureEvents(): void;\ndeclare function close(): void;\ndeclare function confirm(message?: string): boolean;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\ndeclare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\ndeclare function focus(): void;\ndeclare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\ndeclare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\ndeclare function getSelection(): Selection;\ndeclare function matchMedia(mediaQuery: string): MediaQueryList;\ndeclare function moveBy(x?: number, y?: number): void;\ndeclare function moveTo(x?: number, y?: number): void;\ndeclare function msWriteProfilerMark(profilerMarkName: string): void;\ndeclare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\ndeclare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\ndeclare function prompt(message?: string, _default?: string): string | null;\ndeclare function releaseEvents(): void;\ndeclare function requestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function resizeBy(x?: number, y?: number): void;\ndeclare function resizeTo(x?: number, y?: number): void;\ndeclare function scroll(options?: ScrollToOptions): void;\ndeclare function scroll(x?: number, y?: number): void;\ndeclare function scrollBy(options?: ScrollToOptions): void;\ndeclare function scrollBy(x?: number, y?: number): void;\ndeclare function scrollTo(options?: ScrollToOptions): void;\ndeclare function scrollTo(x?: number, y?: number): void;\ndeclare function stop(): void;\ndeclare function webkitCancelAnimationFrame(handle: number): void;\ndeclare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function toString(): string;\ndeclare function dispatchEvent(evt: Event): boolean;\ndeclare function clearInterval(handle?: number): void;\ndeclare function clearTimeout(handle?: number): void;\ndeclare function setInterval(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setInterval(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function clearImmediate(handle: number): void;\ndeclare function setImmediate(handler: (...args: any[]) => void): number;\ndeclare function setImmediate(handler: any, ...args: any[]): number;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare var console: Console;\ndeclare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onwheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var indexedDB: IDBFactory;\ndeclare function atob(encodedString: string): string;\ndeclare function btoa(rawString: string): string;\ndeclare function fetch(input?: Request | string, init?: RequestInit): Promise;\ndeclare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\ndeclare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\ndeclare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\ndeclare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\ntype ScrollBehavior = \"auto\" | \"instant\" | \"smooth\";\ntype ScrollLogicalPosition = \"start\" | \"center\" | \"end\" | \"nearest\";\ntype MouseWheelEvent = WheelEvent;\ntype ScrollRestoration = \"auto\" | \"manual\";\ntype FormDataEntryValue = string | File;\ntype InsertPosition = \"beforebegin\" | \"afterbegin\" | \"beforeend\" | \"afterend\";\ntype HeadersInit = Headers | string[][] | { [key: string]: string };\ntype OrientationLockType = \"any\" | \"natural\" | \"portrait\" | \"landscape\" | \"portrait-primary\" | \"portrait-secondary\" | \"landscape-primary\"| \"landscape-secondary\";\ntype IDBValidKey = number | string | Date | IDBArrayKey;\ntype AlgorithmIdentifier = string | Algorithm;\ntype MutationRecordType = \"attributes\" | \"characterData\" | \"childList\";\ntype AAGUID = string;\ntype BodyInit = any;\ntype ByteString = string;\ntype ConstrainBoolean = boolean | ConstrainBooleanParameters;\ntype ConstrainDOMString = string | string[] | ConstrainDOMStringParameters;\ntype ConstrainDouble = number | ConstrainDoubleRange;\ntype ConstrainLong = number | ConstrainLongRange;\ntype CryptoOperationData = ArrayBufferView;\ntype GLbitfield = number;\ntype GLboolean = boolean;\ntype GLbyte = number;\ntype GLclampf = number;\ntype GLenum = number;\ntype GLfloat = number;\ntype GLint = number;\ntype GLintptr = number;\ntype GLshort = number;\ntype GLsizei = number;\ntype GLsizeiptr = number;\ntype GLubyte = number;\ntype GLuint = number;\ntype GLushort = number;\ntype IDBKeyPath = string;\ntype MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload;\ntype MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent;\ntype MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload;\ntype RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete;\ntype RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport;\ntype RequestInfo = Request | string;\ntype USVString = string;\ntype payloadtype = number;\ntype BufferSource = ArrayBuffer | ArrayBufferView;\ntype ClientTypes = \"window\" | \"worker\" | \"sharedworker\" | \"all\";\ntype AppendMode = \"segments\" | \"sequence\";\ntype AudioContextLatencyCategory = \"balanced\" | \"interactive\" | \"playback\";\ntype AudioContextState = \"suspended\" | \"running\" | \"closed\";\ntype BinaryType = \"blob\" | \"arraybuffer\";\ntype BiquadFilterType = \"lowpass\" | \"highpass\" | \"bandpass\" | \"lowshelf\" | \"highshelf\" | \"peaking\" | \"notch\" | \"allpass\";\ntype CanPlayTypeResult = \"\" | \"maybe\" | \"probably\";\ntype CanvasFillRule = \"nonzero\" | \"evenodd\";\ntype ChannelCountMode = \"max\" | \"clamped-max\" | \"explicit\";\ntype ChannelInterpretation = \"speakers\" | \"discrete\";\ntype DisplayCaptureSurfaceType = \"monitor\" | \"window\" | \"application\" | \"browser\";\ntype DistanceModelType = \"linear\" | \"inverse\" | \"exponential\";\ntype EndOfStreamError = \"network\" | \"decode\";\ntype ExpandGranularity = \"character\" | \"word\" | \"sentence\" | \"textedit\";\ntype GamepadHand = \"\" | \"left\" | \"right\";\ntype GamepadHapticActuatorType = \"vibration\";\ntype GamepadInputEmulationType = \"mouse\" | \"keyboard\" | \"gamepad\";\ntype GamepadMappingType = \"\" | \"standard\";\ntype IDBCursorDirection = \"next\" | \"nextunique\" | \"prev\" | \"prevunique\";\ntype IDBRequestReadyState = \"pending\" | \"done\";\ntype IDBTransactionMode = \"readonly\" | \"readwrite\" | \"versionchange\";\ntype KeyFormat = \"raw\" | \"spki\" | \"pkcs8\" | \"jwk\";\ntype KeyType = \"public\" | \"private\" | \"secret\";\ntype KeyUsage = \"encrypt\" | \"decrypt\" | \"sign\" | \"verify\" | \"deriveKey\" | \"deriveBits\" | \"wrapKey\" | \"unwrapKey\";\ntype ListeningState = \"inactive\" | \"active\" | \"disambiguation\";\ntype MSCredentialType = \"FIDO_2_0\";\ntype MSIceAddrType = \"os\" | \"stun\" | \"turn\" | \"peer-derived\";\ntype MSIceType = \"failed\" | \"direct\" | \"relay\";\ntype MSStatsType = \"description\" | \"localclientevent\" | \"inbound-network\" | \"outbound-network\" | \"inbound-payload\" | \"outbound-payload\" | \"transportdiagnostics\";\ntype MSTransportType = \"Embedded\" | \"USB\" | \"NFC\" | \"BT\";\ntype MSWebViewPermissionState = \"unknown\" | \"defer\" | \"allow\" | \"deny\";\ntype MSWebViewPermissionType = \"geolocation\" | \"unlimitedIndexedDBQuota\" | \"media\" | \"pointerlock\" | \"webnotifications\";\ntype MediaDeviceKind = \"audioinput\" | \"audiooutput\" | \"videoinput\";\ntype MediaKeyMessageType = \"license-request\" | \"license-renewal\" | \"license-release\" | \"individualization-request\";\ntype MediaKeySessionType = \"temporary\" | \"persistent-license\" | \"persistent-release-message\";\ntype MediaKeyStatus = \"usable\" | \"expired\" | \"output-downscaled\" | \"output-not-allowed\" | \"status-pending\" | \"internal-error\";\ntype MediaKeysRequirement = \"required\" | \"optional\" | \"not-allowed\";\ntype MediaStreamTrackState = \"live\" | \"ended\";\ntype NavigationReason = \"up\" | \"down\" | \"left\" | \"right\";\ntype NavigationType = \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\";\ntype NotificationDirection = \"auto\" | \"ltr\" | \"rtl\";\ntype NotificationPermission = \"default\" | \"denied\" | \"granted\";\ntype OscillatorType = \"sine\" | \"square\" | \"sawtooth\" | \"triangle\" | \"custom\";\ntype OverSampleType = \"none\" | \"2x\" | \"4x\";\ntype PanningModelType = \"equalpower\" | \"HRTF\";\ntype PaymentComplete = \"success\" | \"fail\" | \"unknown\";\ntype PaymentShippingType = \"shipping\" | \"delivery\" | \"pickup\";\ntype PushEncryptionKeyName = \"p256dh\" | \"auth\";\ntype PushPermissionState = \"granted\" | \"denied\" | \"prompt\";\ntype RTCBundlePolicy = \"balanced\" | \"max-compat\" | \"max-bundle\";\ntype RTCDegradationPreference = \"maintain-framerate\" | \"maintain-resolution\" | \"balanced\";\ntype RTCDtlsRole = \"auto\" | \"client\" | \"server\";\ntype RTCDtlsTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\";\ntype RTCIceCandidateType = \"host\" | \"srflx\" | \"prflx\" | \"relay\";\ntype RTCIceComponent = \"RTP\" | \"RTCP\";\ntype RTCIceConnectionState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"failed\" | \"disconnected\" | \"closed\";\ntype RTCIceGatherPolicy = \"all\" | \"nohost\" | \"relay\";\ntype RTCIceGathererState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceGatheringState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceProtocol = \"udp\" | \"tcp\";\ntype RTCIceRole = \"controlling\" | \"controlled\";\ntype RTCIceTcpCandidateType = \"active\" | \"passive\" | \"so\";\ntype RTCIceTransportPolicy = \"none\" | \"relay\" | \"all\";\ntype RTCIceTransportState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"closed\";\ntype RTCSdpType = \"offer\" | \"pranswer\" | \"answer\";\ntype RTCSignalingState = \"stable\" | \"have-local-offer\" | \"have-remote-offer\" | \"have-local-pranswer\" | \"have-remote-pranswer\" | \"closed\";\ntype RTCStatsIceCandidatePairState = \"frozen\" | \"waiting\" | \"inprogress\" | \"failed\" | \"succeeded\" | \"cancelled\";\ntype RTCStatsIceCandidateType = \"host\" | \"serverreflexive\" | \"peerreflexive\" | \"relayed\";\ntype RTCStatsType = \"inboundrtp\" | \"outboundrtp\" | \"session\" | \"datachannel\" | \"track\" | \"transport\" | \"candidatepair\" | \"localcandidate\" | \"remotecandidate\";\ntype ReadyState = \"closed\" | \"open\" | \"ended\";\ntype ReferrerPolicy = \"\" | \"no-referrer\" | \"no-referrer-when-downgrade\" | \"origin-only\" | \"origin-when-cross-origin\" | \"unsafe-url\";\ntype RequestCache = \"default\" | \"no-store\" | \"reload\" | \"no-cache\" | \"force-cache\";\ntype RequestCredentials = \"omit\" | \"same-origin\" | \"include\";\ntype RequestDestination = \"\" | \"document\" | \"sharedworker\" | \"subresource\" | \"unknown\" | \"worker\";\ntype RequestMode = \"navigate\" | \"same-origin\" | \"no-cors\" | \"cors\";\ntype RequestRedirect = \"follow\" | \"error\" | \"manual\";\ntype RequestType = \"\" | \"audio\" | \"font\" | \"image\" | \"script\" | \"style\" | \"track\" | \"video\";\ntype ResponseType = \"basic\" | \"cors\" | \"default\" | \"error\" | \"opaque\" | \"opaqueredirect\";\ntype ScopedCredentialType = \"ScopedCred\";\ntype ServiceWorkerState = \"installing\" | \"installed\" | \"activating\" | \"activated\" | \"redundant\";\ntype TextTrackKind = \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\ntype TextTrackMode = \"disabled\" | \"hidden\" | \"showing\";\ntype Transport = \"usb\" | \"nfc\" | \"ble\";\ntype VRDisplayEventReason = \"mounted\" | \"navigation\" | \"requested\" | \"unmounted\";\ntype VREye = \"left\" | \"right\";\ntype VideoFacingModeEnum = \"user\" | \"environment\" | \"left\" | \"right\";\ntype VisibilityState = \"hidden\" | \"visible\" | \"prerender\" | \"unloaded\";\ntype XMLHttpRequestResponseType = \"\" | \"arraybuffer\" | \"blob\" | \"document\" | \"json\" | \"text\";\n\n\n/////////////////////////////\n/// WorkerGlobalScope APIs\n/////////////////////////////\n// These are only available in a Web Worker\ndeclare function importScripts(...urls: string[]): void;\n\n\n\n\n/////////////////////////////\n/// Windows Script Host APIS\n/////////////////////////////\n\n\ninterface ActiveXObject {\n new (s: string): any;\n}\ndeclare var ActiveXObject: ActiveXObject;\n\ninterface ITextWriter {\n Write(s: string): void;\n WriteLine(s: string): void;\n Close(): void;\n}\n\ninterface TextStreamBase {\n /**\n * The column number of the current character position in an input stream.\n */\n Column: number;\n\n /**\n * The current line number in an input stream.\n */\n Line: number;\n\n /**\n * Closes a text stream.\n * It is not necessary to close standard streams; they close automatically when the process ends. If\n * you close a standard stream, be aware that any other pointers to that standard stream become invalid.\n */\n Close(): void;\n}\n\ninterface TextStreamWriter extends TextStreamBase {\n /**\n * Sends a string to an output stream.\n */\n Write(s: string): void;\n\n /**\n * Sends a specified number of blank lines (newline characters) to an output stream.\n */\n WriteBlankLines(intLines: number): void;\n\n /**\n * Sends a string followed by a newline character to an output stream.\n */\n WriteLine(s: string): void;\n}\n\ninterface TextStreamReader extends TextStreamBase {\n /**\n * Returns a specified number of characters from an input stream, starting at the current pointer position.\n * Does not return until the ENTER key is pressed.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n Read(characters: number): string;\n\n /**\n * Returns all characters from an input stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadAll(): string;\n\n /**\n * Returns an entire line from an input stream.\n * Although this method extracts the newline character, it does not add it to the returned string.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadLine(): string;\n\n /**\n * Skips a specified number of characters when reading from an input text stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)\n */\n Skip(characters: number): void;\n\n /**\n * Skips the next line when reading from an input text stream.\n * Can only be used on a stream in reading mode, not writing or appending mode.\n */\n SkipLine(): void;\n\n /**\n * Indicates whether the stream pointer position is at the end of a line.\n */\n AtEndOfLine: boolean;\n\n /**\n * Indicates whether the stream pointer position is at the end of a stream.\n */\n AtEndOfStream: boolean;\n}\n\ndeclare var WScript: {\n /**\n * Outputs text to either a message box (under WScript.exe) or the command console window followed by\n * a newline (under CScript.exe).\n */\n Echo(s: any): void;\n\n /**\n * Exposes the write-only error output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdErr: TextStreamWriter;\n\n /**\n * Exposes the write-only output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdOut: TextStreamWriter;\n Arguments: { length: number; Item(n: number): string; };\n\n /**\n * The full path of the currently running script.\n */\n ScriptFullName: string;\n\n /**\n * Forces the script to stop immediately, with an optional exit code.\n */\n Quit(exitCode?: number): number;\n\n /**\n * The Windows Script Host build version number.\n */\n BuildVersion: number;\n\n /**\n * Fully qualified path of the host executable.\n */\n FullName: string;\n\n /**\n * Gets/sets the script mode - interactive(true) or batch(false).\n */\n Interactive: boolean;\n\n /**\n * The name of the host executable (WScript.exe or CScript.exe).\n */\n Name: string;\n\n /**\n * Path of the directory containing the host executable.\n */\n Path: string;\n\n /**\n * The filename of the currently running script.\n */\n ScriptName: string;\n\n /**\n * Exposes the read-only input stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdIn: TextStreamReader;\n\n /**\n * Windows Script Host version\n */\n Version: string;\n\n /**\n * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.\n */\n ConnectObject(objEventSource: any, strPrefix: string): void;\n\n /**\n * Creates a COM object.\n * @param strProgiID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n CreateObject(strProgID: string, strPrefix?: string): any;\n\n /**\n * Disconnects a COM object from its event sources.\n */\n DisconnectObject(obj: any): void;\n\n /**\n * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.\n * @param strPathname Fully qualified path to the file containing the object persisted to disk.\n * For objects in memory, pass a zero-length string.\n * @param strProgID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;\n\n /**\n * Suspends script execution for a specified length of time, then continues execution.\n * @param intTime Interval (in milliseconds) to suspend script execution.\n */\n Sleep(intTime: number): void;\n};\n\n/**\n * Represents an Automation SAFEARRAY\n */\ndeclare class SafeArray {\n private constructor();\n private SafeArray_typekey: SafeArray;\n}\n\n/**\n * Allows enumerating over a COM collection, which may not have indexed item access.\n */\ninterface Enumerator {\n /**\n * Returns true if the current item is the last one in the collection, or the collection is empty,\n * or the current item is undefined.\n */\n atEnd(): boolean;\n\n /**\n * Returns the current item in the collection\n */\n item(): T;\n\n /**\n * Resets the current item in the collection to the first item. If there are no items in the collection,\n * the current item is set to undefined.\n */\n moveFirst(): void;\n\n /**\n * Moves the current item to the next item in the collection. If the enumerator is at the end of\n * the collection or the collection is empty, the current item is set to undefined.\n */\n moveNext(): void;\n}\n\ninterface EnumeratorConstructor {\n new (safearray: SafeArray): Enumerator;\n new (collection: { Item(index: any): T }): Enumerator;\n new (collection: any): Enumerator;\n}\n\ndeclare var Enumerator: EnumeratorConstructor;\n\n/**\n * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.\n */\ninterface VBArray {\n /**\n * Returns the number of dimensions (1-based).\n */\n dimensions(): number;\n\n /**\n * Takes an index for each dimension in the array, and returns the item at the corresponding location.\n */\n getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;\n\n /**\n * Returns the smallest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n lbound(dimension?: number): number;\n\n /**\n * Returns the largest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n ubound(dimension?: number): number;\n\n /**\n * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,\n * each successive dimension is appended to the end of the array.\n * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]\n */\n toArray(): T[];\n}\n\ninterface VBArrayConstructor {\n new (safeArray: SafeArray): VBArray;\n}\n\ndeclare var VBArray: VBArrayConstructor;\n\n/**\n * Automation date (VT_DATE)\n */\ndeclare class VarDate {\n private constructor();\n private VarDate_typekey: VarDate;\n}\n\ninterface DateConstructor {\n new (vd: VarDate): Date;\n}\n\ninterface Date {\n getVarDate: () => VarDate;\n}\n"; +export const contents = "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// ECMAScript APIs\n/////////////////////////////\n\ndeclare const NaN: number;\ndeclare const Infinity: number;\n\n/**\n * Evaluates JavaScript code and executes it.\n * @param x A String value that contains valid JavaScript code.\n */\ndeclare function eval(x: string): any;\n\n/**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n * All other strings are considered decimal.\n */\ndeclare function parseInt(s: string, radix?: number): number;\n\n/**\n * Converts a string to a floating-point number.\n * @param string A string that contains a floating-point number.\n */\ndeclare function parseFloat(string: string): number;\n\n/**\n * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).\n * @param number A numeric value.\n */\ndeclare function isNaN(number: number): boolean;\n\n/**\n * Determines whether a supplied number is finite.\n * @param number Any numeric value.\n */\ndeclare function isFinite(number: number): boolean;\n\n/**\n * Gets the unencoded version of an encoded Uniform Resource Identifier (URI).\n * @param encodedURI A value representing an encoded URI.\n */\ndeclare function decodeURI(encodedURI: string): string;\n\n/**\n * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI).\n * @param encodedURIComponent A value representing an encoded URI component.\n */\ndeclare function decodeURIComponent(encodedURIComponent: string): string;\n\n/**\n * Encodes a text string as a valid Uniform Resource Identifier (URI)\n * @param uri A value representing an encoded URI.\n */\ndeclare function encodeURI(uri: string): string;\n\n/**\n * Encodes a text string as a valid component of a Uniform Resource Identifier (URI).\n * @param uriComponent A value representing an encoded URI component.\n */\ndeclare function encodeURIComponent(uriComponent: string): string;\n\n/**\n * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\n * @param string A string value\n */\ndeclare function escape(string: string): string;\n\n/**\n * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.\n * @param string A string value\n */\ndeclare function unescape(string: string): string;\n\ninterface Symbol {\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): symbol;\n}\n\ndeclare type PropertyKey = string | number | symbol;\n\ninterface PropertyDescriptor {\n configurable?: boolean;\n enumerable?: boolean;\n value?: any;\n writable?: boolean;\n get?(): any;\n set?(v: any): void;\n}\n\ninterface PropertyDescriptorMap {\n [s: string]: PropertyDescriptor;\n}\n\ninterface Object {\n /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */\n constructor: Function;\n\n /** Returns a string representation of an object. */\n toString(): string;\n\n /** Returns a date converted to a string using the current locale. */\n toLocaleString(): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): Object;\n\n /**\n * Determines whether an object has a property with the specified name.\n * @param v A property name.\n */\n hasOwnProperty(v: PropertyKey): boolean;\n\n /**\n * Determines whether an object exists in another object's prototype chain.\n * @param v Another object whose prototype chain is to be checked.\n */\n isPrototypeOf(v: Object): boolean;\n\n /**\n * Determines whether a specified property is enumerable.\n * @param v A property name.\n */\n propertyIsEnumerable(v: PropertyKey): boolean;\n}\n\ninterface ObjectConstructor {\n new(value?: any): Object;\n (): any;\n (value: any): any;\n\n /** A reference to the prototype for a class of objects. */\n readonly prototype: Object;\n\n /**\n * Returns the prototype of an object.\n * @param o The object that references the prototype.\n */\n getPrototypeOf(o: any): any;\n\n /**\n * Gets the own property descriptor of the specified object.\n * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.\n * @param o Object that contains the property.\n * @param p Name of the property.\n */\n getOwnPropertyDescriptor(o: any, p: PropertyKey): PropertyDescriptor | undefined;\n\n /**\n * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly\n * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions.\n * @param o Object that contains the own properties.\n */\n getOwnPropertyNames(o: any): string[];\n\n /**\n * Creates an object that has the specified prototype or that has null prototype.\n * @param o Object to use as a prototype. May be null.\n */\n create(o: object | null): any;\n\n /**\n * Creates an object that has the specified prototype, and that optionally contains specified properties.\n * @param o Object to use as a prototype. May be null\n * @param properties JavaScript object that contains one or more property descriptors.\n */\n create(o: object | null, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Adds a property to an object, or modifies attributes of an existing property.\n * @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.\n * @param p The property name.\n * @param attributes Descriptor for the property. It can be for a data property or an accessor property.\n */\n defineProperty(o: any, p: PropertyKey, attributes: PropertyDescriptor & ThisType): any;\n\n /**\n * Adds one or more properties to an object, and/or modifies attributes of existing properties.\n * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object.\n * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property.\n */\n defineProperties(o: any, properties: PropertyDescriptorMap & ThisType): any;\n\n /**\n * Prevents the modification of attributes of existing properties, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n seal(o: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(a: T[]): ReadonlyArray;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(f: T): T;\n\n /**\n * Prevents the modification of existing property attributes and values, and prevents the addition of new properties.\n * @param o Object on which to lock the attributes.\n */\n freeze(o: T): Readonly;\n\n /**\n * Prevents the addition of new properties to an object.\n * @param o Object to make non-extensible.\n */\n preventExtensions(o: T): T;\n\n /**\n * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isSealed(o: any): boolean;\n\n /**\n * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object.\n * @param o Object to test.\n */\n isFrozen(o: any): boolean;\n\n /**\n * Returns a value that indicates whether new properties can be added to an object.\n * @param o Object to test.\n */\n isExtensible(o: any): boolean;\n\n /**\n * Returns the names of the enumerable properties and methods of an object.\n * @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.\n */\n keys(o: {}): string[];\n}\n\n/**\n * Provides functionality common to all JavaScript objects.\n */\ndeclare const Object: ObjectConstructor;\n\n/**\n * Creates a new function.\n */\ninterface Function {\n /**\n * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function.\n * @param thisArg The object to be used as the this object.\n * @param argArray A set of arguments to be passed to the function.\n */\n apply(this: Function, thisArg: any, argArray?: any): any;\n\n /**\n * Calls a method of an object, substituting another object for the current object.\n * @param thisArg The object to be used as the current object.\n * @param argArray A list of arguments to be passed to the method.\n */\n call(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /**\n * For a given function, creates a bound function that has the same body as the original function.\n * The this object of the bound function is associated with the specified object, and has the specified initial parameters.\n * @param thisArg An object to which the this keyword can refer inside the new function.\n * @param argArray A list of arguments to be passed to the new function.\n */\n bind(this: Function, thisArg: any, ...argArray: any[]): any;\n\n /** Returns a string representation of a function. */\n toString(): string;\n\n prototype: any;\n readonly length: number;\n\n // Non-standard extensions\n arguments: any;\n caller: Function;\n}\n\ninterface FunctionConstructor {\n /**\n * Creates a new function.\n * @param args A list of arguments the function accepts.\n */\n new(...args: string[]): Function;\n (...args: string[]): Function;\n readonly prototype: Function;\n}\n\ndeclare const Function: FunctionConstructor;\n\ninterface IArguments {\n [index: number]: any;\n length: number;\n callee: Function;\n}\n\ninterface String {\n /** Returns a string representation of a string. */\n toString(): string;\n\n /**\n * Returns the character at the specified index.\n * @param pos The zero-based index of the desired character.\n */\n charAt(pos: number): string;\n\n /**\n * Returns the Unicode value of the character at the specified location.\n * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.\n */\n charCodeAt(index: number): number;\n\n /**\n * Returns a string that contains the concatenation of two or more strings.\n * @param strings The strings to append to the end of the string.\n */\n concat(...strings: string[]): string;\n\n /**\n * Returns the position of the first occurrence of a substring.\n * @param searchString The substring to search for in the string\n * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string.\n */\n indexOf(searchString: string, position?: number): number;\n\n /**\n * Returns the last occurrence of a substring in the string.\n * @param searchString The substring to search for.\n * @param position The index at which to begin searching. If omitted, the search begins at the end of the string.\n */\n lastIndexOf(searchString: string, position?: number): number;\n\n /**\n * Determines whether two strings are equivalent in the current locale.\n * @param that String to compare to target string\n */\n localeCompare(that: string): number;\n\n /**\n * Matches a string with a regular expression, and returns an array containing the results of that search.\n * @param regexp A variable name or string literal containing the regular expression pattern and flags.\n */\n match(regexp: string | RegExp): RegExpMatchArray | null;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.\n */\n replace(searchValue: string | RegExp, replaceValue: string): string;\n\n /**\n * Replaces text in a string, using a regular expression or search string.\n * @param searchValue A string to search for.\n * @param replacer A function that returns the replacement text.\n */\n replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;\n\n /**\n * Finds the first substring match in a regular expression search.\n * @param regexp The regular expression pattern and applicable flags.\n */\n search(regexp: string | RegExp): number;\n\n /**\n * Returns a section of a string.\n * @param start The index to the beginning of the specified portion of stringObj.\n * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end.\n * If this value is not specified, the substring continues to the end of stringObj.\n */\n slice(start?: number, end?: number): string;\n\n /**\n * Split a string into substrings using the specified separator and return them as an array.\n * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.\n * @param limit A value used to limit the number of elements returned in the array.\n */\n split(separator: string | RegExp, limit?: number): string[];\n\n /**\n * Returns the substring at the specified location within a String object.\n * @param start The zero-based index number indicating the beginning of the substring.\n * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end.\n * If end is omitted, the characters from start through the end of the original string are returned.\n */\n substring(start: number, end?: number): string;\n\n /** Converts all the alphabetic characters in a string to lowercase. */\n toLowerCase(): string;\n\n /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */\n toLocaleLowerCase(): string;\n\n /** Converts all the alphabetic characters in a string to uppercase. */\n toUpperCase(): string;\n\n /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */\n toLocaleUpperCase(): string;\n\n /** Removes the leading and trailing white space and line terminator characters from a string. */\n trim(): string;\n\n /** Returns the length of a String object. */\n readonly length: number;\n\n // IE extensions\n /**\n * Gets a substring beginning at the specified location and having the specified length.\n * @param from The starting position of the desired substring. The index of the first character in the string is zero.\n * @param length The number of characters to include in the returned substring.\n */\n substr(from: number, length?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): string;\n\n readonly [index: number]: string;\n}\n\ninterface StringConstructor {\n new(value?: any): String;\n (value?: any): string;\n readonly prototype: String;\n fromCharCode(...codes: number[]): string;\n}\n\n/**\n * Allows manipulation and formatting of text strings and determination and location of substrings within strings.\n */\ndeclare const String: StringConstructor;\n\ninterface Boolean {\n /** Returns the primitive value of the specified object. */\n valueOf(): boolean;\n}\n\ninterface BooleanConstructor {\n new(value?: any): Boolean;\n (value?: any): boolean;\n readonly prototype: Boolean;\n}\n\ndeclare const Boolean: BooleanConstructor;\n\ninterface Number {\n /**\n * Returns a string representation of an object.\n * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.\n */\n toString(radix?: number): string;\n\n /**\n * Returns a string representing a number in fixed-point notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toFixed(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented in exponential notation.\n * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.\n */\n toExponential(fractionDigits?: number): string;\n\n /**\n * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.\n * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.\n */\n toPrecision(precision?: number): string;\n\n /** Returns the primitive value of the specified object. */\n valueOf(): number;\n}\n\ninterface NumberConstructor {\n new(value?: any): Number;\n (value?: any): number;\n readonly prototype: Number;\n\n /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */\n readonly MAX_VALUE: number;\n\n /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */\n readonly MIN_VALUE: number;\n\n /**\n * A value that is not a number.\n * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function.\n */\n readonly NaN: number;\n\n /**\n * A value that is less than the largest negative number that can be represented in JavaScript.\n * JavaScript displays NEGATIVE_INFINITY values as -infinity.\n */\n readonly NEGATIVE_INFINITY: number;\n\n /**\n * A value greater than the largest number that can be represented in JavaScript.\n * JavaScript displays POSITIVE_INFINITY values as infinity.\n */\n readonly POSITIVE_INFINITY: number;\n}\n\n/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */\ndeclare const Number: NumberConstructor;\n\ninterface TemplateStringsArray extends ReadonlyArray {\n readonly raw: ReadonlyArray;\n}\n\n/**\n * The type of `import.meta`.\n * \n * If you need to declare that a given property exists on `import.meta`,\n * this type may be augmented via interface merging.\n */\ninterface ImportMeta {\n}\n\ninterface Math {\n /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */\n readonly E: number;\n /** The natural logarithm of 10. */\n readonly LN10: number;\n /** The natural logarithm of 2. */\n readonly LN2: number;\n /** The base-2 logarithm of e. */\n readonly LOG2E: number;\n /** The base-10 logarithm of e. */\n readonly LOG10E: number;\n /** Pi. This is the ratio of the circumference of a circle to its diameter. */\n readonly PI: number;\n /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */\n readonly SQRT1_2: number;\n /** The square root of 2. */\n readonly SQRT2: number;\n /**\n * Returns the absolute value of a number (the value without regard to whether it is positive or negative).\n * For example, the absolute value of -5 is the same as the absolute value of 5.\n * @param x A numeric expression for which the absolute value is needed.\n */\n abs(x: number): number;\n /**\n * Returns the arc cosine (or inverse cosine) of a number.\n * @param x A numeric expression.\n */\n acos(x: number): number;\n /**\n * Returns the arcsine of a number.\n * @param x A numeric expression.\n */\n asin(x: number): number;\n /**\n * Returns the arctangent of a number.\n * @param x A numeric expression for which the arctangent is needed.\n */\n atan(x: number): number;\n /**\n * Returns the angle (in radians) from the X axis to a point.\n * @param y A numeric expression representing the cartesian y-coordinate.\n * @param x A numeric expression representing the cartesian x-coordinate.\n */\n atan2(y: number, x: number): number;\n /**\n * Returns the smallest integer greater than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n ceil(x: number): number;\n /**\n * Returns the cosine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n cos(x: number): number;\n /**\n * Returns e (the base of natural logarithms) raised to a power.\n * @param x A numeric expression representing the power of e.\n */\n exp(x: number): number;\n /**\n * Returns the greatest integer less than or equal to its numeric argument.\n * @param x A numeric expression.\n */\n floor(x: number): number;\n /**\n * Returns the natural logarithm (base e) of a number.\n * @param x A numeric expression.\n */\n log(x: number): number;\n /**\n * Returns the larger of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n max(...values: number[]): number;\n /**\n * Returns the smaller of a set of supplied numeric expressions.\n * @param values Numeric expressions to be evaluated.\n */\n min(...values: number[]): number;\n /**\n * Returns the value of a base expression taken to a specified power.\n * @param x The base value of the expression.\n * @param y The exponent value of the expression.\n */\n pow(x: number, y: number): number;\n /** Returns a pseudorandom number between 0 and 1. */\n random(): number;\n /**\n * Returns a supplied numeric expression rounded to the nearest number.\n * @param x The value to be rounded to the nearest number.\n */\n round(x: number): number;\n /**\n * Returns the sine of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n sin(x: number): number;\n /**\n * Returns the square root of a number.\n * @param x A numeric expression.\n */\n sqrt(x: number): number;\n /**\n * Returns the tangent of a number.\n * @param x A numeric expression that contains an angle measured in radians.\n */\n tan(x: number): number;\n}\n/** An intrinsic object that provides basic mathematics functionality and constants. */\ndeclare const Math: Math;\n\n/** Enables basic storage and retrieval of dates and times. */\ninterface Date {\n /** Returns a string representation of a date. The format of the string depends on the locale. */\n toString(): string;\n /** Returns a date as a string value. */\n toDateString(): string;\n /** Returns a time as a string value. */\n toTimeString(): string;\n /** Returns a value as a string value appropriate to the host environment's current locale. */\n toLocaleString(): string;\n /** Returns a date as a string value appropriate to the host environment's current locale. */\n toLocaleDateString(): string;\n /** Returns a time as a string value appropriate to the host environment's current locale. */\n toLocaleTimeString(): string;\n /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */\n valueOf(): number;\n /** Gets the time value in milliseconds. */\n getTime(): number;\n /** Gets the year, using local time. */\n getFullYear(): number;\n /** Gets the year using Universal Coordinated Time (UTC). */\n getUTCFullYear(): number;\n /** Gets the month, using local time. */\n getMonth(): number;\n /** Gets the month of a Date object using Universal Coordinated Time (UTC). */\n getUTCMonth(): number;\n /** Gets the day-of-the-month, using local time. */\n getDate(): number;\n /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */\n getUTCDate(): number;\n /** Gets the day of the week, using local time. */\n getDay(): number;\n /** Gets the day of the week using Universal Coordinated Time (UTC). */\n getUTCDay(): number;\n /** Gets the hours in a date, using local time. */\n getHours(): number;\n /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */\n getUTCHours(): number;\n /** Gets the minutes of a Date object, using local time. */\n getMinutes(): number;\n /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */\n getUTCMinutes(): number;\n /** Gets the seconds of a Date object, using local time. */\n getSeconds(): number;\n /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCSeconds(): number;\n /** Gets the milliseconds of a Date, using local time. */\n getMilliseconds(): number;\n /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */\n getUTCMilliseconds(): number;\n /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */\n getTimezoneOffset(): number;\n /**\n * Sets the date and time value in the Date object.\n * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.\n */\n setTime(time: number): number;\n /**\n * Sets the milliseconds value in the Date object using local time.\n * @param ms A numeric value equal to the millisecond value.\n */\n setMilliseconds(ms: number): number;\n /**\n * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).\n * @param ms A numeric value equal to the millisecond value.\n */\n setUTCMilliseconds(ms: number): number;\n\n /**\n * Sets the seconds value in the Date object using local time.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setSeconds(sec: number, ms?: number): number;\n /**\n * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCSeconds(sec: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using local time.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCMinutes(min: number, sec?: number, ms?: number): number;\n /**\n * Sets the hour value in the Date object using local time.\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the hours value in the Date object using Universal Coordinated Time (UTC).\n * @param hours A numeric value equal to the hours value.\n * @param min A numeric value equal to the minutes value.\n * @param sec A numeric value equal to the seconds value.\n * @param ms A numeric value equal to the milliseconds value.\n */\n setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;\n /**\n * Sets the numeric day-of-the-month value of the Date object using local time.\n * @param date A numeric value equal to the day of the month.\n */\n setDate(date: number): number;\n /**\n * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).\n * @param date A numeric value equal to the day of the month.\n */\n setUTCDate(date: number): number;\n /**\n * Sets the month value in the Date object using local time.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.\n */\n setMonth(month: number, date?: number): number;\n /**\n * Sets the month value in the Date object using Universal Coordinated Time (UTC).\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.\n * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.\n */\n setUTCMonth(month: number, date?: number): number;\n /**\n * Sets the year of the Date object using local time.\n * @param year A numeric value for the year.\n * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.\n * @param date A numeric value equal for the day of the month.\n */\n setFullYear(year: number, month?: number, date?: number): number;\n /**\n * Sets the year value in the Date object using Universal Coordinated Time (UTC).\n * @param year A numeric value equal to the year.\n * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.\n * @param date A numeric value equal to the day of the month.\n */\n setUTCFullYear(year: number, month?: number, date?: number): number;\n /** Returns a date converted to a string using Universal Coordinated Time (UTC). */\n toUTCString(): string;\n /** Returns a date as a string value in ISO format. */\n toISOString(): string;\n /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */\n toJSON(key?: any): string;\n}\n\ninterface DateConstructor {\n new(): Date;\n new(value: number | string): Date;\n new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;\n (): string;\n readonly prototype: Date;\n /**\n * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.\n * @param s A date string\n */\n parse(s: string): number;\n /**\n * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.\n * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.\n * @param month The month as an number between 0 and 11 (January to December).\n * @param date The date as an number between 1 and 31.\n * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.\n * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.\n * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.\n * @param ms An number from 0 to 999 that specifies the milliseconds.\n */\n UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;\n now(): number;\n}\n\ndeclare const Date: DateConstructor;\n\ninterface RegExpMatchArray extends Array {\n index?: number;\n input?: string;\n}\n\ninterface RegExpExecArray extends Array {\n index: number;\n input: string;\n}\n\ninterface RegExp {\n /**\n * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.\n * @param string The String object or string literal on which to perform the search.\n */\n exec(string: string): RegExpExecArray | null;\n\n /**\n * Returns a Boolean value that indicates whether or not a pattern exists in a searched string.\n * @param string String on which to perform the search.\n */\n test(string: string): boolean;\n\n /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */\n readonly source: string;\n\n /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */\n readonly global: boolean;\n\n /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */\n readonly ignoreCase: boolean;\n\n /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */\n readonly multiline: boolean;\n\n lastIndex: number;\n\n // Non-standard extensions\n compile(): this;\n}\n\ninterface RegExpConstructor {\n new(pattern: RegExp | string): RegExp;\n new(pattern: string, flags?: string): RegExp;\n (pattern: RegExp | string): RegExp;\n (pattern: string, flags?: string): RegExp;\n readonly prototype: RegExp;\n\n // Non-standard extensions\n $1: string;\n $2: string;\n $3: string;\n $4: string;\n $5: string;\n $6: string;\n $7: string;\n $8: string;\n $9: string;\n lastMatch: string;\n}\n\ndeclare const RegExp: RegExpConstructor;\n\ninterface Error {\n name: string;\n message: string;\n stack?: string;\n}\n\ninterface ErrorConstructor {\n new(message?: string): Error;\n (message?: string): Error;\n readonly prototype: Error;\n}\n\ndeclare const Error: ErrorConstructor;\n\ninterface EvalError extends Error {\n}\n\ninterface EvalErrorConstructor {\n new(message?: string): EvalError;\n (message?: string): EvalError;\n readonly prototype: EvalError;\n}\n\ndeclare const EvalError: EvalErrorConstructor;\n\ninterface RangeError extends Error {\n}\n\ninterface RangeErrorConstructor {\n new(message?: string): RangeError;\n (message?: string): RangeError;\n readonly prototype: RangeError;\n}\n\ndeclare const RangeError: RangeErrorConstructor;\n\ninterface ReferenceError extends Error {\n}\n\ninterface ReferenceErrorConstructor {\n new(message?: string): ReferenceError;\n (message?: string): ReferenceError;\n readonly prototype: ReferenceError;\n}\n\ndeclare const ReferenceError: ReferenceErrorConstructor;\n\ninterface SyntaxError extends Error {\n}\n\ninterface SyntaxErrorConstructor {\n new(message?: string): SyntaxError;\n (message?: string): SyntaxError;\n readonly prototype: SyntaxError;\n}\n\ndeclare const SyntaxError: SyntaxErrorConstructor;\n\ninterface TypeError extends Error {\n}\n\ninterface TypeErrorConstructor {\n new(message?: string): TypeError;\n (message?: string): TypeError;\n readonly prototype: TypeError;\n}\n\ndeclare const TypeError: TypeErrorConstructor;\n\ninterface URIError extends Error {\n}\n\ninterface URIErrorConstructor {\n new(message?: string): URIError;\n (message?: string): URIError;\n readonly prototype: URIError;\n}\n\ndeclare const URIError: URIErrorConstructor;\n\ninterface JSON {\n /**\n * Converts a JavaScript Object Notation (JSON) string into an object.\n * @param text A valid JSON string.\n * @param reviver A function that transforms the results. This function is called for each member of the object.\n * If a member contains nested objects, the nested objects are transformed before the parent object is.\n */\n parse(text: string, reviver?: (key: any, value: any) => any): any;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer A function that transforms the results.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string;\n /**\n * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.\n * @param value A JavaScript value, usually an object or array, to be converted.\n * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.\n * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.\n */\n stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;\n}\n\n/**\n * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.\n */\ndeclare const JSON: JSON;\n\n\n/////////////////////////////\n/// ECMAScript Array API (specially handled by compiler)\n/////////////////////////////\n\ninterface ReadonlyArray {\n /**\n * Gets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n readonly length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: ReadonlyArray) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: ReadonlyArray) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: ReadonlyArray) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray) => U, initialValue: U): U;\n\n readonly [n: number]: T;\n}\n\ninterface ConcatArray {\n readonly length: number;\n readonly [n: number]: T;\n join(separator?: string): string;\n slice(start?: number, end?: number): T[];\n}\n\ninterface Array {\n /**\n * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.\n */\n length: number;\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n /**\n * Returns a string representation of an array. The elements are converted to string using their toLocalString methods.\n */\n toLocaleString(): string;\n /**\n * Removes the last element from an array and returns it.\n */\n pop(): T | undefined;\n /**\n * Appends new elements to an array, and returns the new length of the array.\n * @param items New elements of the Array.\n */\n push(...items: T[]): number;\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: ConcatArray[]): T[];\n /**\n * Combines two or more arrays.\n * @param items Additional items to add to the end of array1.\n */\n concat(...items: (T | ConcatArray)[]): T[];\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @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.\n */\n join(separator?: string): string;\n /**\n * Reverses the elements in an Array.\n */\n reverse(): T[];\n /**\n * Removes the first element from an array and returns it.\n */\n shift(): T | undefined;\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): T[];\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: T, b: T) => number): this;\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n */\n splice(start: number, deleteCount?: number): T[];\n /**\n * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the array in place of the deleted elements.\n */\n splice(start: number, deleteCount: number, ...items: T[]): T[];\n /**\n * Inserts new elements at the start of an array.\n * @param items Elements to insert at the start of the Array.\n */\n unshift(...items: T[]): number;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.\n */\n indexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Returns the index of the last occurrence of a specified value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.\n */\n lastIndexOf(searchElement: T, fromIndex?: number): number;\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;\n /**\n * Calls a defined callback function on each element of an array, and returns an array that contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;\n reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;\n /**\n * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;\n\n [n: number]: T;\n}\n\ninterface ArrayConstructor {\n new(arrayLength?: number): any[];\n new (arrayLength: number): T[];\n new (...items: T[]): T[];\n (arrayLength?: number): any[];\n (arrayLength: number): T[];\n (...items: T[]): T[];\n isArray(arg: any): arg is Array;\n readonly prototype: Array;\n}\n\ndeclare const Array: ArrayConstructor;\n\ninterface TypedPropertyDescriptor {\n enumerable?: boolean;\n configurable?: boolean;\n writable?: boolean;\n value?: T;\n get?: () => T;\n set?: (value: T) => void;\n}\n\ndeclare type ClassDecorator = (target: TFunction) => TFunction | void;\ndeclare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;\ndeclare type MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void;\ndeclare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;\n\ndeclare type PromiseConstructorLike = new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void) => PromiseLike;\n\ninterface PromiseLike {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike;\n}\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface Promise {\n /**\n * Attaches callbacks for the resolution and/or rejection of the Promise.\n * @param onfulfilled The callback to execute when the Promise is resolved.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of which ever callback is executed.\n */\n then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise;\n\n /**\n * Attaches a callback for only the rejection of the Promise.\n * @param onrejected The callback to execute when the Promise is rejected.\n * @returns A Promise for the completion of the callback.\n */\n catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise;\n}\n\ninterface ArrayLike {\n readonly length: number;\n readonly [n: number]: T;\n}\n\n/**\n * Make all properties in T optional\n */\ntype Partial = {\n [P in keyof T]?: T[P];\n};\n\n/**\n * Make all properties in T required\n */\ntype Required = {\n [P in keyof T]-?: T[P];\n};\n\n/**\n * Make all properties in T readonly\n */\ntype Readonly = {\n readonly [P in keyof T]: T[P];\n};\n\n/**\n * From T pick a set of properties K\n */\ntype Pick = {\n [P in K]: T[P];\n};\n\n/**\n * Construct a type with a set of properties K of type T\n */\ntype Record = {\n [P in K]: T;\n};\n\n/**\n * Exclude from T those types that are assignable to U\n */\ntype Exclude = T extends U ? never : T;\n\n/**\n * Extract from T those types that are assignable to U\n */\ntype Extract = T extends U ? T : never;\n\n/**\n * Exclude null and undefined from T\n */\ntype NonNullable = T extends null | undefined ? never : T;\n\n/**\n * Obtain the return type of a function type\n */\ntype ReturnType any> = T extends (...args: any[]) => infer R ? R : any;\n\n/**\n * Obtain the return type of a constructor function type\n */\ntype InstanceType any> = T extends new (...args: any[]) => infer R ? R : any;\n\n/**\n * Marker for contextual 'this' type\n */\ninterface ThisType { }\n\n/**\n * Represents a raw buffer of binary data, which is used to store data for the\n * different typed arrays. ArrayBuffers cannot be read from or written to directly,\n * but can be passed to a typed array or DataView Object to interpret the raw\n * buffer as needed.\n */\ninterface ArrayBuffer {\n /**\n * Read-only. The length of the ArrayBuffer (in bytes).\n */\n readonly byteLength: number;\n\n /**\n * Returns a section of an ArrayBuffer.\n */\n slice(begin: number, end?: number): ArrayBuffer;\n}\n\n/**\n * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays.\n */\ninterface ArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];\n\ninterface ArrayBufferConstructor {\n readonly prototype: ArrayBuffer;\n new(byteLength: number): ArrayBuffer;\n isView(arg: any): arg is ArrayBufferView;\n}\ndeclare const ArrayBuffer: ArrayBufferConstructor;\n\ninterface ArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\ninterface DataView {\n readonly buffer: ArrayBuffer;\n readonly byteLength: number;\n readonly byteOffset: number;\n /**\n * Gets the Float32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Float64 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getFloat64(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Int8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt8(byteOffset: number): number;\n\n /**\n * Gets the Int16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt16(byteOffset: number, littleEndian?: boolean): number;\n /**\n * Gets the Int32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getInt32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint8 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint8(byteOffset: number): number;\n\n /**\n * Gets the Uint16 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint16(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Gets the Uint32 value at the specified byte offset from the start of the view. There is\n * no alignment constraint; multi-byte values may be fetched from any offset.\n * @param byteOffset The place in the buffer at which the value should be retrieved.\n */\n getUint32(byteOffset: number, littleEndian?: boolean): number;\n\n /**\n * Stores an Float32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Float64 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setInt8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Int16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Int32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setInt32(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint8 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n */\n setUint8(byteOffset: number, value: number): void;\n\n /**\n * Stores an Uint16 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint16(byteOffset: number, value: number, littleEndian?: boolean): void;\n\n /**\n * Stores an Uint32 value at the specified byte offset from the start of the view.\n * @param byteOffset The place in the buffer at which the value should be set.\n * @param value The value to set.\n * @param littleEndian If false or undefined, a big-endian value should be written,\n * otherwise a little-endian value should be written.\n */\n setUint32(byteOffset: number, value: number, littleEndian?: boolean): void;\n}\n\ninterface DataViewConstructor {\n new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView;\n}\ndeclare const DataView: DataViewConstructor;\n\n/**\n * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Int8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\ninterface Int8ArrayConstructor {\n readonly prototype: Int8Array;\n new(length: number): Int8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;\n\n\n}\ndeclare const Int8Array: Int8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ArrayConstructor {\n readonly prototype: Uint8Array;\n new(length: number): Uint8Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;\n\n}\ndeclare const Uint8Array: Uint8ArrayConstructor;\n\n/**\n * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.\n * If the requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint8ClampedArray {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint8ClampedArray;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint8ClampedArray;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint8ClampedArray;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint8ClampedArrayConstructor {\n readonly prototype: Uint8ClampedArray;\n new(length: number): Uint8ClampedArray;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint8ClampedArray;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint8ClampedArray;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;\n}\ndeclare const Uint8ClampedArray: Uint8ClampedArrayConstructor;\n\n/**\n * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int16ArrayConstructor {\n readonly prototype: Int16Array;\n new(length: number): Int16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;\n\n\n}\ndeclare const Int16Array: Int16ArrayConstructor;\n\n/**\n * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint16Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint16Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint16Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint16Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint16ArrayConstructor {\n readonly prototype: Uint16Array;\n new(length: number): Uint16Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint16Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint16Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;\n\n\n}\ndeclare const Uint16Array: Uint16ArrayConstructor;\n/**\n * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Int32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Int32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Int32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Int32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Int32ArrayConstructor {\n readonly prototype: Int32Array;\n new(length: number): Int32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Int32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Int32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;\n\n}\ndeclare const Int32Array: Int32ArrayConstructor;\n\n/**\n * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the\n * requested number of bytes could not be allocated an exception is raised.\n */\ninterface Uint32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void;\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Uint32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Uint32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Uint32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Uint32ArrayConstructor {\n readonly prototype: Uint32Array;\n new(length: number): Uint32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Uint32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Uint32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;\n\n}\ndeclare const Uint32Array: Uint32ArrayConstructor;\n\n/**\n * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number\n * of bytes could not be allocated an exception is raised.\n */\ninterface Float32Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float32Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float32Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float32Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float32ArrayConstructor {\n readonly prototype: Float32Array;\n new(length: number): Float32Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float32Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float32Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;\n\n\n}\ndeclare const Float32Array: Float32ArrayConstructor;\n\n/**\n * A typed array of 64-bit float values. The contents are initialized to 0. If the requested\n * number of bytes could not be allocated an exception is raised.\n */\ninterface Float64Array {\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n readonly buffer: ArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n readonly byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n readonly byteOffset: number;\n\n /**\n * Returns the this object after copying a section of the array identified by start and end\n * to the same array starting at position target\n * @param target If target is negative, it is treated as length+target where length is the\n * length of the array.\n * @param start If start is negative, it is treated as length+start. If end is negative, it\n * is treated as length+end.\n * @param end If not specified, length of the this object is used as its default value.\n */\n copyWithin(target: number, start: number, end?: number): this;\n\n /**\n * Determines whether all the members of an array satisfy the specified test.\n * @param callbackfn A function that accepts up to three arguments. The every method calls\n * the callbackfn function for each element in array1 until the callbackfn returns false,\n * or until the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Returns the this object after filling the section identified by start and end with value\n * @param value value to fill array section with\n * @param start index to start filling the array at. If start is negative, it is treated as\n * length+start where length is the length of the array.\n * @param end index to stop filling the array at. If end is negative, it is treated as\n * length+end.\n */\n fill(value: number, start?: number, end?: number): this;\n\n /**\n * Returns the elements of an array that meet the condition specified in a callback function.\n * @param callbackfn A function that accepts up to three arguments. The filter method calls\n * the callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;\n\n /**\n * Returns the value of the first element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found, find\n * immediately returns that element value. Otherwise, find returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined;\n\n /**\n * Returns the index of the first element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate find calls predicate once for each element of the array, in ascending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findIndex immediately returns that element index. Otherwise, findIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number;\n\n /**\n * Performs the specified action for each element in an array.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void;\n\n /**\n * Returns the index of the first occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n indexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * Adds all the elements of an array separated by the specified separator string.\n * @param separator A string used to separate one element of an array from the next in the\n * resulting String. If omitted, the array elements are separated with a comma.\n */\n join(separator?: string): string;\n\n /**\n * Returns the index of the last occurrence of a value in an array.\n * @param searchElement The value to locate in the array.\n * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n * search starts at index 0.\n */\n lastIndexOf(searchElement: number, fromIndex?: number): number;\n\n /**\n * The length of the array.\n */\n readonly length: number;\n\n /**\n * Calls a defined callback function on each element of an array, and returns an array that\n * contains the results.\n * @param callbackfn A function that accepts up to three arguments. The map method calls the\n * callbackfn function one time for each element in the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array. The return value of\n * the callback function is the accumulated result, and is provided as an argument in the next\n * call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduce method calls the\n * callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an\n * argument instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number;\n reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number;\n\n /**\n * Calls the specified callback function for all the elements in an array, in descending order.\n * The return value of the callback function is the accumulated result, and is provided as an\n * argument in the next call to the callback function.\n * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n * the callbackfn function one time for each element in the array.\n * @param initialValue If initialValue is specified, it is used as the initial value to start\n * the accumulation. The first call to the callbackfn function provides this value as an argument\n * instead of an array value.\n */\n reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U;\n\n /**\n * Reverses the elements in an Array.\n */\n reverse(): Float64Array;\n\n /**\n * Sets a value or an array of values.\n * @param array A typed or untyped array of values to set.\n * @param offset The index in the current array at which the values are to be written.\n */\n set(array: ArrayLike, offset?: number): void;\n\n /**\n * Returns a section of an array.\n * @param start The beginning of the specified portion of the array.\n * @param end The end of the specified portion of the array.\n */\n slice(start?: number, end?: number): Float64Array;\n\n /**\n * Determines whether the specified callback function returns true for any element of an array.\n * @param callbackfn A function that accepts up to three arguments. The some method calls the\n * callbackfn function for each element in array1 until the callbackfn returns true, or until\n * the end of the array.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n * If thisArg is omitted, undefined is used as the this value.\n */\n some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean;\n\n /**\n * Sorts an array.\n * @param compareFn The name of the function used to determine the order of the elements. If\n * omitted, the elements are sorted in ascending, ASCII character order.\n */\n sort(compareFn?: (a: number, b: number) => number): this;\n\n /**\n * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n * at begin, inclusive, up to end, exclusive.\n * @param begin The index of the beginning of the array.\n * @param end The index of the end of the array.\n */\n subarray(begin: number, end?: number): Float64Array;\n\n /**\n * Converts a number to a string by using the current locale.\n */\n toLocaleString(): string;\n\n /**\n * Returns a string representation of an array.\n */\n toString(): string;\n\n [index: number]: number;\n}\n\ninterface Float64ArrayConstructor {\n readonly prototype: Float64Array;\n new(length: number): Float64Array;\n new(arrayOrArrayBuffer: ArrayLike | ArrayBufferLike): Float64Array;\n new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array;\n\n /**\n * The size in bytes of each element in the array.\n */\n readonly BYTES_PER_ELEMENT: number;\n\n /**\n * Returns a new array from a set of elements.\n * @param items A set of elements to include in the new array object.\n */\n of(...items: number[]): Float64Array;\n\n /**\n * Creates an array from an array-like or iterable object.\n * @param arrayLike An array-like or iterable object to convert to an array.\n * @param mapfn A mapping function to call on every element of the array.\n * @param thisArg Value of 'this' used to invoke the mapfn.\n */\n from(arrayLike: ArrayLike, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;\n\n}\ndeclare const Float64Array: Float64ArrayConstructor;\n\n/////////////////////////////\n/// ECMAScript Internationalization API\n/////////////////////////////\n\ndeclare namespace Intl {\n interface CollatorOptions {\n usage?: string;\n localeMatcher?: string;\n numeric?: boolean;\n caseFirst?: string;\n sensitivity?: string;\n ignorePunctuation?: boolean;\n }\n\n interface ResolvedCollatorOptions {\n locale: string;\n usage: string;\n sensitivity: string;\n ignorePunctuation: boolean;\n collation: string;\n caseFirst: string;\n numeric: boolean;\n }\n\n interface Collator {\n compare(x: string, y: string): number;\n resolvedOptions(): ResolvedCollatorOptions;\n }\n var Collator: {\n new(locales?: string | string[], options?: CollatorOptions): Collator;\n (locales?: string | string[], options?: CollatorOptions): Collator;\n supportedLocalesOf(locales: string | string[], options?: CollatorOptions): string[];\n };\n\n interface NumberFormatOptions {\n localeMatcher?: string;\n style?: string;\n currency?: string;\n currencyDisplay?: string;\n useGrouping?: boolean;\n minimumIntegerDigits?: number;\n minimumFractionDigits?: number;\n maximumFractionDigits?: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n }\n\n interface ResolvedNumberFormatOptions {\n locale: string;\n numberingSystem: string;\n style: string;\n currency?: string;\n currencyDisplay?: string;\n minimumIntegerDigits: number;\n minimumFractionDigits: number;\n maximumFractionDigits: number;\n minimumSignificantDigits?: number;\n maximumSignificantDigits?: number;\n useGrouping: boolean;\n }\n\n interface NumberFormat {\n format(value: number): string;\n resolvedOptions(): ResolvedNumberFormatOptions;\n }\n var NumberFormat: {\n new(locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n (locales?: string | string[], options?: NumberFormatOptions): NumberFormat;\n supportedLocalesOf(locales: string | string[], options?: NumberFormatOptions): string[];\n };\n\n interface DateTimeFormatOptions {\n localeMatcher?: string;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n formatMatcher?: string;\n hour12?: boolean;\n timeZone?: string;\n }\n\n interface ResolvedDateTimeFormatOptions {\n locale: string;\n calendar: string;\n numberingSystem: string;\n timeZone: string;\n hour12?: boolean;\n weekday?: string;\n era?: string;\n year?: string;\n month?: string;\n day?: string;\n hour?: string;\n minute?: string;\n second?: string;\n timeZoneName?: string;\n }\n\n interface DateTimeFormat {\n format(date?: Date | number): string;\n resolvedOptions(): ResolvedDateTimeFormatOptions;\n }\n var DateTimeFormat: {\n new(locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n (locales?: string | string[], options?: DateTimeFormatOptions): DateTimeFormat;\n supportedLocalesOf(locales: string | string[], options?: DateTimeFormatOptions): string[];\n };\n}\n\ninterface String {\n /**\n * Determines whether two strings are equivalent in the current or specified locale.\n * @param that String to compare to target string\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.\n * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.\n */\n localeCompare(that: string, locales?: string | string[], options?: Intl.CollatorOptions): number;\n}\n\ninterface Number {\n /**\n * Converts a number to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;\n}\n\ninterface Date {\n /**\n * Converts a date and time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n /**\n * Converts a date to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n\n /**\n * Converts a time to a string by using the current or specified locale.\n * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.\n * @param options An object that contains one or more properties that specify comparison options.\n */\n toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;\n}\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n/////////////////////////////\n/// DOM APIs\n/////////////////////////////\n\ninterface Account {\n displayName: string;\n id: string;\n imageURL?: string;\n name?: string;\n rpDisplayName: string;\n}\n\ninterface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\ninterface AesCbcParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCtrParams extends Algorithm {\n counter: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n length: number;\n}\n\ninterface AesDerivedKeyParams extends Algorithm {\n length: number;\n}\n\ninterface AesGcmParams extends Algorithm {\n additionalData?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n tagLength?: number;\n}\n\ninterface AesKeyAlgorithm extends KeyAlgorithm {\n length: number;\n}\n\ninterface AesKeyGenParams extends Algorithm {\n length: number;\n}\n\ninterface Algorithm {\n name: string;\n}\n\ninterface AnalyserOptions extends AudioNodeOptions {\n fftSize?: number;\n maxDecibels?: number;\n minDecibels?: number;\n smoothingTimeConstant?: number;\n}\n\ninterface AnimationEventInit extends EventInit {\n animationName?: string;\n elapsedTime?: number;\n pseudoElement?: string;\n}\n\ninterface AnimationPlaybackEventInit extends EventInit {\n currentTime?: number | null;\n timelineTime?: number | null;\n}\n\ninterface AssertionOptions {\n allowList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface AudioBufferOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface AudioBufferSourceOptions {\n buffer?: AudioBuffer | null;\n detune?: number;\n loop?: boolean;\n loopEnd?: number;\n loopStart?: number;\n playbackRate?: number;\n}\n\ninterface AudioContextInfo {\n currentTime?: number;\n sampleRate?: number;\n}\n\ninterface AudioContextOptions {\n latencyHint?: AudioContextLatencyCategory | number;\n sampleRate?: number;\n}\n\ninterface AudioNodeOptions {\n channelCount?: number;\n channelCountMode?: ChannelCountMode;\n channelInterpretation?: ChannelInterpretation;\n}\n\ninterface AudioParamDescriptor {\n automationRate?: AutomationRate;\n defaultValue?: number;\n maxValue?: number;\n minValue?: number;\n name: string;\n}\n\ninterface AudioProcessingEventInit extends EventInit {\n inputBuffer: AudioBuffer;\n outputBuffer: AudioBuffer;\n playbackTime: number;\n}\n\ninterface AudioTimestamp {\n contextTime?: number;\n performanceTime?: number;\n}\n\ninterface AudioWorkletNodeOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n numberOfOutputs?: number;\n outputChannelCount?: number[];\n parameterData?: Record;\n processorOptions?: any;\n}\n\ninterface BiquadFilterOptions extends AudioNodeOptions {\n Q?: number;\n detune?: number;\n frequency?: number;\n gain?: number;\n type?: BiquadFilterType;\n}\n\ninterface BlobPropertyBag {\n type?: string;\n}\n\ninterface ByteLengthChunk {\n byteLength?: number;\n}\n\ninterface CacheQueryOptions {\n cacheName?: string;\n ignoreMethod?: boolean;\n ignoreSearch?: boolean;\n ignoreVary?: boolean;\n}\n\ninterface ChannelMergerOptions extends AudioNodeOptions {\n numberOfInputs?: number;\n}\n\ninterface ChannelSplitterOptions extends AudioNodeOptions {\n numberOfOutputs?: number;\n}\n\ninterface ClientData {\n challenge: string;\n extensions?: WebAuthnExtensions;\n hashAlg: string | Algorithm;\n origin: string;\n rpId: string;\n tokenBinding?: string;\n}\n\ninterface ClientQueryOptions {\n includeUncontrolled?: boolean;\n type?: ClientTypes;\n}\n\ninterface CloseEventInit extends EventInit {\n code?: number;\n reason?: string;\n wasClean?: boolean;\n}\n\ninterface CompositionEventInit extends UIEventInit {\n data?: string;\n}\n\ninterface ComputedEffectTiming extends EffectTiming {\n activeDuration?: number;\n currentIteration?: number | null;\n endTime?: number;\n localTime?: number | null;\n progress?: number | null;\n}\n\ninterface ComputedKeyframe extends Record {\n composite?: CompositeOperation | null;\n computedOffset?: number;\n easing?: string;\n offset?: number | null;\n}\n\ninterface ConfirmSiteSpecificExceptionsInformation extends ExceptionInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface ConstantSourceOptions {\n offset?: number;\n}\n\ninterface ConstrainBooleanParameters {\n exact?: boolean;\n ideal?: boolean;\n}\n\ninterface ConstrainDOMStringParameters {\n exact?: string | string[];\n ideal?: string | string[];\n}\n\ninterface ConstrainDoubleRange extends DoubleRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainLongRange extends LongRange {\n exact?: number;\n ideal?: number;\n}\n\ninterface ConstrainVideoFacingModeParameters {\n exact?: VideoFacingModeEnum | VideoFacingModeEnum[];\n ideal?: VideoFacingModeEnum | VideoFacingModeEnum[];\n}\n\ninterface ConvolverOptions extends AudioNodeOptions {\n buffer?: AudioBuffer | null;\n disableNormalization?: boolean;\n}\n\ninterface CustomEventInit extends EventInit {\n detail?: T;\n}\n\ninterface DOMMatrix2DInit {\n a?: number;\n b?: number;\n c?: number;\n d?: number;\n e?: number;\n f?: number;\n m11?: number;\n m12?: number;\n m21?: number;\n m22?: number;\n m41?: number;\n m42?: number;\n}\n\ninterface DOMMatrixInit extends DOMMatrix2DInit {\n is2D?: boolean;\n m13?: number;\n m14?: number;\n m23?: number;\n m24?: number;\n m31?: number;\n m32?: number;\n m33?: number;\n m34?: number;\n m43?: number;\n m44?: number;\n}\n\ninterface DOMPointInit {\n w?: number;\n x?: number;\n y?: number;\n z?: number;\n}\n\ninterface DOMQuadInit {\n p1?: DOMPointInit;\n p2?: DOMPointInit;\n p3?: DOMPointInit;\n p4?: DOMPointInit;\n}\n\ninterface DOMRectInit {\n height?: number;\n width?: number;\n x?: number;\n y?: number;\n}\n\ninterface DelayOptions extends AudioNodeOptions {\n delayTime?: number;\n maxDelayTime?: number;\n}\n\ninterface DeviceAccelerationDict {\n x?: number | null;\n y?: number | null;\n z?: number | null;\n}\n\ninterface DeviceLightEventInit extends EventInit {\n value?: number;\n}\n\ninterface DeviceMotionEventInit extends EventInit {\n acceleration?: DeviceAccelerationDict | null;\n accelerationIncludingGravity?: DeviceAccelerationDict | null;\n interval?: number | null;\n rotationRate?: DeviceRotationRateDict | null;\n}\n\ninterface DeviceOrientationEventInit extends EventInit {\n absolute?: boolean;\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DeviceRotationRateDict {\n alpha?: number | null;\n beta?: number | null;\n gamma?: number | null;\n}\n\ninterface DocumentTimelineOptions {\n originTime?: number;\n}\n\ninterface DoubleRange {\n max?: number;\n min?: number;\n}\n\ninterface DynamicsCompressorOptions extends AudioNodeOptions {\n attack?: number;\n knee?: number;\n ratio?: number;\n release?: number;\n threshold?: number;\n}\n\ninterface EcKeyAlgorithm extends KeyAlgorithm {\n namedCurve: string;\n}\n\ninterface EcKeyGenParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcKeyImportParams extends Algorithm {\n namedCurve: string;\n}\n\ninterface EcdhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface EcdsaParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface EffectTiming {\n delay?: number;\n direction?: PlaybackDirection;\n duration?: number | string;\n easing?: string;\n endDelay?: number;\n fill?: FillMode;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface ErrorEventInit extends EventInit {\n colno?: number;\n error?: any;\n filename?: string;\n lineno?: number;\n message?: string;\n}\n\ninterface EventInit {\n bubbles?: boolean;\n cancelable?: boolean;\n composed?: boolean;\n}\n\ninterface EventListenerOptions {\n capture?: boolean;\n}\n\ninterface EventModifierInit extends UIEventInit {\n altKey?: boolean;\n ctrlKey?: boolean;\n metaKey?: boolean;\n modifierAltGraph?: boolean;\n modifierCapsLock?: boolean;\n modifierFn?: boolean;\n modifierFnLock?: boolean;\n modifierHyper?: boolean;\n modifierNumLock?: boolean;\n modifierOS?: boolean;\n modifierScrollLock?: boolean;\n modifierSuper?: boolean;\n modifierSymbol?: boolean;\n modifierSymbolLock?: boolean;\n shiftKey?: boolean;\n}\n\ninterface ExceptionInformation {\n domain?: string | null;\n}\n\ninterface ExtendableEventInit extends EventInit {\n}\n\ninterface ExtendableMessageEventInit extends ExtendableEventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: object | ServiceWorker | MessagePort;\n}\n\ninterface FetchEventInit extends ExtendableEventInit {\n clientId?: string;\n preloadResponse: Promise;\n request: Request;\n resultingClientId?: string;\n targetClientId?: string;\n}\n\ninterface FilePropertyBag extends BlobPropertyBag {\n lastModified?: number;\n}\n\ninterface FocusEventInit extends UIEventInit {\n relatedTarget?: EventTarget | null;\n}\n\ninterface FocusNavigationEventInit extends EventInit {\n navigationReason?: string | null;\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface FocusNavigationOrigin {\n originHeight?: number;\n originLeft?: number;\n originTop?: number;\n originWidth?: number;\n}\n\ninterface GainOptions extends AudioNodeOptions {\n gain?: number;\n}\n\ninterface GamepadEventInit extends EventInit {\n gamepad?: Gamepad;\n}\n\ninterface GetNotificationOptions {\n tag?: string;\n}\n\ninterface HashChangeEventInit extends EventInit {\n newURL?: string;\n oldURL?: string;\n}\n\ninterface HkdfParams extends Algorithm {\n hash: string | Algorithm;\n info: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface HmacImportParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface HmacKeyAlgorithm extends KeyAlgorithm {\n hash: KeyAlgorithm;\n length: number;\n}\n\ninterface HmacKeyGenParams extends Algorithm {\n hash: string | Algorithm;\n length?: number;\n}\n\ninterface IDBIndexParameters {\n multiEntry?: boolean;\n unique?: boolean;\n}\n\ninterface IDBObjectStoreParameters {\n autoIncrement?: boolean;\n keyPath?: string | string[];\n}\n\ninterface IDBVersionChangeEventInit extends EventInit {\n newVersion?: number | null;\n oldVersion?: number;\n}\n\ninterface IIRFilterOptions extends AudioNodeOptions {\n feedback: number[];\n feedforward: number[];\n}\n\ninterface IntersectionObserverEntryInit {\n boundingClientRect: DOMRectInit;\n intersectionRect: DOMRectInit;\n isIntersecting: boolean;\n rootBounds: DOMRectInit;\n target: Element;\n time: number;\n}\n\ninterface IntersectionObserverInit {\n root?: Element | null;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\ninterface JsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\ninterface KeyAlgorithm {\n name: string;\n}\n\ninterface KeyboardEventInit extends EventModifierInit {\n code?: string;\n key?: string;\n location?: number;\n repeat?: boolean;\n}\n\ninterface Keyframe extends Record {\n composite?: CompositeOperation | null;\n easing?: string;\n offset?: number | null;\n}\n\ninterface KeyframeAnimationOptions extends KeyframeEffectOptions {\n id?: string;\n}\n\ninterface KeyframeEffectOptions extends EffectTiming {\n composite?: CompositeOperation;\n iterationComposite?: IterationCompositeOperation;\n}\n\ninterface LongRange {\n max?: number;\n min?: number;\n}\n\ninterface MSAccountInfo {\n accountImageUri?: string;\n accountName?: string;\n rpDisplayName: string;\n userDisplayName: string;\n userId?: string;\n}\n\ninterface MSAudioLocalClientEvent extends MSLocalClientEventBase {\n cpuInsufficientEventRatio?: number;\n deviceCaptureNotFunctioningEventRatio?: number;\n deviceClippingEventRatio?: number;\n deviceEchoEventRatio?: number;\n deviceGlitchesEventRatio?: number;\n deviceHalfDuplexAECEventRatio?: number;\n deviceHowlingEventCount?: number;\n deviceLowSNREventRatio?: number;\n deviceLowSpeechLevelEventRatio?: number;\n deviceMultipleEndpointsEventCount?: number;\n deviceNearEndToEchoRatioEventRatio?: number;\n deviceRenderMuteEventRatio?: number;\n deviceRenderNotFunctioningEventRatio?: number;\n deviceRenderZeroVolumeEventRatio?: number;\n networkDelayEventRatio?: number;\n networkSendQualityEventRatio?: number;\n}\n\ninterface MSAudioRecvPayload extends MSPayloadBase {\n burstLossLength1?: number;\n burstLossLength2?: number;\n burstLossLength3?: number;\n burstLossLength4?: number;\n burstLossLength5?: number;\n burstLossLength6?: number;\n burstLossLength7?: number;\n burstLossLength8OrHigher?: number;\n fecRecvDistance1?: number;\n fecRecvDistance2?: number;\n fecRecvDistance3?: number;\n packetReorderDepthAvg?: number;\n packetReorderDepthMax?: number;\n packetReorderRatio?: number;\n ratioCompressedSamplesAvg?: number;\n ratioConcealedSamplesAvg?: number;\n ratioStretchedSamplesAvg?: number;\n samplingRate?: number;\n signal?: MSAudioRecvSignal;\n}\n\ninterface MSAudioRecvSignal {\n initialSignalLevelRMS?: number;\n recvNoiseLevelCh1?: number;\n recvSignalLevelCh1?: number;\n renderLoopbackSignalLevel?: number;\n renderNoiseLevel?: number;\n renderSignalLevel?: number;\n}\n\ninterface MSAudioSendPayload extends MSPayloadBase {\n audioFECUsed?: boolean;\n samplingRate?: number;\n sendMutePercent?: number;\n signal?: MSAudioSendSignal;\n}\n\ninterface MSAudioSendSignal {\n noiseLevel?: number;\n sendNoiseLevelCh1?: number;\n sendSignalLevelCh1?: number;\n}\n\ninterface MSConnectivity {\n iceType?: MSIceType;\n iceWarningFlags?: MSIceWarningFlags;\n relayAddress?: MSRelayAddress;\n}\n\ninterface MSCredentialFilter {\n accept?: MSCredentialSpec[];\n}\n\ninterface MSCredentialParameters {\n type?: MSCredentialType;\n}\n\ninterface MSCredentialSpec {\n id?: string;\n type: MSCredentialType;\n}\n\ninterface MSDCCEventInit extends EventInit {\n maxFr?: number;\n maxFs?: number;\n}\n\ninterface MSDSHEventInit extends EventInit {\n sources?: number[];\n timestamp?: number;\n}\n\ninterface MSDelay {\n roundTrip?: number;\n roundTripMax?: number;\n}\n\ninterface MSDescription extends RTCStats {\n connectivity?: MSConnectivity;\n deviceDevName?: string;\n localAddr?: MSIPAddressInfo;\n networkconnectivity?: MSNetworkConnectivityInfo;\n reflexiveLocalIPAddr?: MSIPAddressInfo;\n remoteAddr?: MSIPAddressInfo;\n transport?: RTCIceProtocol;\n}\n\ninterface MSFIDOCredentialParameters extends MSCredentialParameters {\n algorithm?: string | Algorithm;\n authenticators?: string[];\n}\n\ninterface MSIPAddressInfo {\n ipAddr?: string;\n manufacturerMacAddrMask?: string;\n port?: number;\n}\n\ninterface MSIceWarningFlags {\n allocationMessageIntegrityFailed?: boolean;\n alternateServerReceived?: boolean;\n connCheckMessageIntegrityFailed?: boolean;\n connCheckOtherError?: boolean;\n fipsAllocationFailure?: boolean;\n multipleRelayServersAttempted?: boolean;\n noRelayServersConfigured?: boolean;\n portRangeExhausted?: boolean;\n pseudoTLSFailure?: boolean;\n tcpNatConnectivityFailed?: boolean;\n tcpRelayConnectivityFailed?: boolean;\n turnAuthUnknownUsernameError?: boolean;\n turnTcpAllocateFailed?: boolean;\n turnTcpSendFailed?: boolean;\n turnTcpTimedOut?: boolean;\n turnTurnTcpConnectivityFailed?: boolean;\n turnUdpAllocateFailed?: boolean;\n turnUdpSendFailed?: boolean;\n udpLocalConnectivityFailed?: boolean;\n udpNatConnectivityFailed?: boolean;\n udpRelayConnectivityFailed?: boolean;\n useCandidateChecksFailed?: boolean;\n}\n\ninterface MSJitter {\n interArrival?: number;\n interArrivalMax?: number;\n interArrivalSD?: number;\n}\n\ninterface MSLocalClientEventBase extends RTCStats {\n networkBandwidthLowEventRatio?: number;\n networkReceiveQualityEventRatio?: number;\n}\n\ninterface MSNetwork extends RTCStats {\n delay?: MSDelay;\n jitter?: MSJitter;\n packetLoss?: MSPacketLoss;\n utilization?: MSUtilization;\n}\n\ninterface MSNetworkConnectivityInfo {\n linkspeed?: number;\n networkConnectionDetails?: string;\n vpn?: boolean;\n}\n\ninterface MSNetworkInterfaceType {\n interfaceTypeEthernet?: boolean;\n interfaceTypePPP?: boolean;\n interfaceTypeTunnel?: boolean;\n interfaceTypeWWAN?: boolean;\n interfaceTypeWireless?: boolean;\n}\n\ninterface MSOutboundNetwork extends MSNetwork {\n appliedBandwidthLimit?: number;\n}\n\ninterface MSPacketLoss {\n lossRate?: number;\n lossRateMax?: number;\n}\n\ninterface MSPayloadBase extends RTCStats {\n payloadDescription?: string;\n}\n\ninterface MSPortRange {\n max?: number;\n min?: number;\n}\n\ninterface MSRelayAddress {\n port?: number;\n relayAddress?: string;\n}\n\ninterface MSSignatureParameters {\n userPrompt?: string;\n}\n\ninterface MSTransportDiagnosticsStats extends RTCStats {\n allocationTimeInMs?: number;\n baseAddress?: string;\n baseInterface?: MSNetworkInterfaceType;\n iceRole?: RTCIceRole;\n iceWarningFlags?: MSIceWarningFlags;\n interfaces?: MSNetworkInterfaceType;\n localAddrType?: MSIceAddrType;\n localAddress?: string;\n localInterface?: MSNetworkInterfaceType;\n localMR?: string;\n localMRTCPPort?: number;\n localSite?: string;\n msRtcEngineVersion?: string;\n networkName?: string;\n numConsentReqReceived?: number;\n numConsentReqSent?: number;\n numConsentRespReceived?: number;\n numConsentRespSent?: number;\n portRangeMax?: number;\n portRangeMin?: number;\n protocol?: RTCIceProtocol;\n remoteAddrType?: MSIceAddrType;\n remoteAddress?: string;\n remoteMR?: string;\n remoteMRTCPPort?: number;\n remoteSite?: string;\n rtpRtcpMux?: boolean;\n stunVer?: number;\n}\n\ninterface MSUtilization {\n bandwidthEstimation?: number;\n bandwidthEstimationAvg?: number;\n bandwidthEstimationMax?: number;\n bandwidthEstimationMin?: number;\n bandwidthEstimationStdDev?: number;\n packets?: number;\n}\n\ninterface MSVideoPayload extends MSPayloadBase {\n durationSeconds?: number;\n resolution?: string;\n videoBitRateAvg?: number;\n videoBitRateMax?: number;\n videoFrameRateAvg?: number;\n videoPacketLossRate?: number;\n}\n\ninterface MSVideoRecvPayload extends MSVideoPayload {\n lowBitRateCallPercent?: number;\n lowFrameRateCallPercent?: number;\n recvBitRateAverage?: number;\n recvBitRateMaximum?: number;\n recvCodecType?: string;\n recvFpsHarmonicAverage?: number;\n recvFrameRateAverage?: number;\n recvNumResSwitches?: number;\n recvReorderBufferMaxSuccessfullyOrderedExtent?: number;\n recvReorderBufferMaxSuccessfullyOrderedLateTime?: number;\n recvReorderBufferPacketsDroppedDueToBufferExhaustion?: number;\n recvReorderBufferPacketsDroppedDueToTimeout?: number;\n recvReorderBufferReorderedPackets?: number;\n recvResolutionHeight?: number;\n recvResolutionWidth?: number;\n recvVideoStreamsMax?: number;\n recvVideoStreamsMin?: number;\n recvVideoStreamsMode?: number;\n reorderBufferTotalPackets?: number;\n videoFrameLossRate?: number;\n videoPostFECPLR?: number;\n videoResolutions?: MSVideoResolutionDistribution;\n}\n\ninterface MSVideoResolutionDistribution {\n cifQuality?: number;\n h1080Quality?: number;\n h1440Quality?: number;\n h2160Quality?: number;\n h720Quality?: number;\n vgaQuality?: number;\n}\n\ninterface MSVideoSendPayload extends MSVideoPayload {\n sendBitRateAverage?: number;\n sendBitRateMaximum?: number;\n sendFrameRateAverage?: number;\n sendResolutionHeight?: number;\n sendResolutionWidth?: number;\n sendVideoStreamsMax?: number;\n}\n\ninterface MediaElementAudioSourceOptions {\n mediaElement: HTMLMediaElement;\n}\n\ninterface MediaEncryptedEventInit extends EventInit {\n initData?: ArrayBuffer | null;\n initDataType?: string;\n}\n\ninterface MediaKeyMessageEventInit extends EventInit {\n message?: ArrayBuffer | null;\n messageType?: MediaKeyMessageType;\n}\n\ninterface MediaKeySystemConfiguration {\n audioCapabilities?: MediaKeySystemMediaCapability[];\n distinctiveIdentifier?: MediaKeysRequirement;\n initDataTypes?: string[];\n persistentState?: MediaKeysRequirement;\n videoCapabilities?: MediaKeySystemMediaCapability[];\n}\n\ninterface MediaKeySystemMediaCapability {\n contentType?: string;\n robustness?: string;\n}\n\ninterface MediaStreamAudioSourceOptions {\n mediaStream: MediaStream;\n}\n\ninterface MediaStreamConstraints {\n audio?: boolean | MediaTrackConstraints;\n peerIdentity?: string;\n video?: boolean | MediaTrackConstraints;\n}\n\ninterface MediaStreamErrorEventInit extends EventInit {\n error?: MediaStreamError | null;\n}\n\ninterface MediaStreamEventInit extends EventInit {\n stream?: MediaStream;\n}\n\ninterface MediaStreamTrackAudioSourceOptions {\n mediaStreamTrack: MediaStreamTrack;\n}\n\ninterface MediaStreamTrackEventInit extends EventInit {\n track?: MediaStreamTrack | null;\n}\n\ninterface MediaTrackCapabilities {\n aspectRatio?: number | DoubleRange;\n deviceId?: string;\n echoCancellation?: boolean[];\n facingMode?: string;\n frameRate?: number | DoubleRange;\n groupId?: string;\n height?: number | LongRange;\n sampleRate?: number | LongRange;\n sampleSize?: number | LongRange;\n volume?: number | DoubleRange;\n width?: number | LongRange;\n}\n\ninterface MediaTrackConstraintSet {\n aspectRatio?: number | ConstrainDoubleRange;\n channelCount?: number | ConstrainLongRange;\n deviceId?: string | string[] | ConstrainDOMStringParameters;\n displaySurface?: string | string[] | ConstrainDOMStringParameters;\n echoCancellation?: boolean | ConstrainBooleanParameters;\n facingMode?: string | string[] | ConstrainDOMStringParameters;\n frameRate?: number | ConstrainDoubleRange;\n groupId?: string | string[] | ConstrainDOMStringParameters;\n height?: number | ConstrainLongRange;\n latency?: number | ConstrainDoubleRange;\n logicalSurface?: boolean | ConstrainBooleanParameters;\n sampleRate?: number | ConstrainLongRange;\n sampleSize?: number | ConstrainLongRange;\n volume?: number | ConstrainDoubleRange;\n width?: number | ConstrainLongRange;\n}\n\ninterface MediaTrackConstraints extends MediaTrackConstraintSet {\n advanced?: MediaTrackConstraintSet[];\n}\n\ninterface MediaTrackSettings {\n aspectRatio?: number;\n deviceId?: string;\n echoCancellation?: boolean;\n facingMode?: string;\n frameRate?: number;\n groupId?: string;\n height?: number;\n sampleRate?: number;\n sampleSize?: number;\n volume?: number;\n width?: number;\n}\n\ninterface MediaTrackSupportedConstraints {\n aspectRatio?: boolean;\n deviceId?: boolean;\n echoCancellation?: boolean;\n facingMode?: boolean;\n frameRate?: boolean;\n groupId?: boolean;\n height?: boolean;\n sampleRate?: boolean;\n sampleSize?: boolean;\n volume?: boolean;\n width?: boolean;\n}\n\ninterface MessageEventInit extends EventInit {\n channel?: string;\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[];\n source?: Window | null;\n}\n\ninterface MouseEventInit extends EventModifierInit {\n button?: number;\n buttons?: number;\n clientX?: number;\n clientY?: number;\n relatedTarget?: EventTarget | null;\n screenX?: number;\n screenY?: number;\n}\n\ninterface MsZoomToOptions {\n animate?: string;\n contentX?: number;\n contentY?: number;\n scaleFactor?: number;\n viewportX?: string | null;\n viewportY?: string | null;\n}\n\ninterface MutationObserverInit {\n attributeFilter?: string[];\n attributeOldValue?: boolean;\n attributes?: boolean;\n characterData?: boolean;\n characterDataOldValue?: boolean;\n childList?: boolean;\n subtree?: boolean;\n}\n\ninterface NavigationPreloadState {\n enabled?: boolean;\n headerValue?: string;\n}\n\ninterface NotificationAction {\n action: string;\n icon?: string;\n title: string;\n}\n\ninterface NotificationEventInit extends ExtendableEventInit {\n action?: string;\n notification: Notification;\n}\n\ninterface NotificationOptions {\n actions?: NotificationAction[];\n badge?: string;\n body?: string;\n data?: any;\n dir?: NotificationDirection;\n icon?: string;\n image?: string;\n lang?: string;\n renotify?: boolean;\n requireInteraction?: boolean;\n silent?: boolean;\n tag?: string;\n timestamp?: number;\n vibrate?: VibratePattern;\n}\n\ninterface OfflineAudioCompletionEventInit extends EventInit {\n renderedBuffer: AudioBuffer;\n}\n\ninterface OfflineAudioContextOptions {\n length: number;\n numberOfChannels?: number;\n sampleRate: number;\n}\n\ninterface OptionalEffectTiming {\n delay?: number;\n direction?: PlaybackDirection;\n duration?: number | string;\n easing?: string;\n endDelay?: number;\n fill?: FillMode;\n iterationStart?: number;\n iterations?: number;\n}\n\ninterface OscillatorOptions extends AudioNodeOptions {\n detune?: number;\n frequency?: number;\n periodicWave?: PeriodicWave;\n type?: OscillatorType;\n}\n\ninterface PannerOptions extends AudioNodeOptions {\n coneInnerAngle?: number;\n coneOuterAngle?: number;\n coneOuterGain?: number;\n distanceModel?: DistanceModelType;\n maxDistance?: number;\n orientationX?: number;\n orientationY?: number;\n orientationZ?: number;\n panningModel?: PanningModelType;\n positionX?: number;\n positionY?: number;\n positionZ?: number;\n refDistance?: number;\n rolloffFactor?: number;\n}\n\ninterface PaymentCurrencyAmount {\n currency: string;\n currencySystem?: string;\n value: string;\n}\n\ninterface PaymentDetailsBase {\n displayItems?: PaymentItem[];\n modifiers?: PaymentDetailsModifier[];\n shippingOptions?: PaymentShippingOption[];\n}\n\ninterface PaymentDetailsInit extends PaymentDetailsBase {\n id?: string;\n total: PaymentItem;\n}\n\ninterface PaymentDetailsModifier {\n additionalDisplayItems?: PaymentItem[];\n data?: any;\n supportedMethods: string | string[];\n total?: PaymentItem;\n}\n\ninterface PaymentDetailsUpdate extends PaymentDetailsBase {\n error?: string;\n total?: PaymentItem;\n}\n\ninterface PaymentItem {\n amount: PaymentCurrencyAmount;\n label: string;\n pending?: boolean;\n}\n\ninterface PaymentMethodData {\n data?: any;\n supportedMethods: string | string[];\n}\n\ninterface PaymentOptions {\n requestPayerEmail?: boolean;\n requestPayerName?: boolean;\n requestPayerPhone?: boolean;\n requestShipping?: boolean;\n shippingType?: string;\n}\n\ninterface PaymentRequestUpdateEventInit extends EventInit {\n}\n\ninterface PaymentShippingOption {\n amount: PaymentCurrencyAmount;\n id: string;\n label: string;\n selected?: boolean;\n}\n\ninterface Pbkdf2Params extends Algorithm {\n hash: string | Algorithm;\n iterations: number;\n salt: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface PerformanceObserverInit {\n buffered?: boolean;\n entryTypes: string[];\n}\n\ninterface PeriodicWaveConstraints {\n disableNormalization?: boolean;\n}\n\ninterface PeriodicWaveOptions extends PeriodicWaveConstraints {\n imag?: number[] | Float32Array;\n real?: number[] | Float32Array;\n}\n\ninterface PointerEventInit extends MouseEventInit {\n height?: number;\n isPrimary?: boolean;\n pointerId?: number;\n pointerType?: string;\n pressure?: number;\n tangentialPressure?: number;\n tiltX?: number;\n tiltY?: number;\n twist?: number;\n width?: number;\n}\n\ninterface PopStateEventInit extends EventInit {\n state?: any;\n}\n\ninterface PositionOptions {\n enableHighAccuracy?: boolean;\n maximumAge?: number;\n timeout?: number;\n}\n\ninterface ProgressEventInit extends EventInit {\n lengthComputable?: boolean;\n loaded?: number;\n total?: number;\n}\n\ninterface PromiseRejectionEventInit extends EventInit {\n promise: Promise;\n reason?: any;\n}\n\ninterface PropertyIndexedKeyframes extends Record {\n composite?: CompositeOperation | (CompositeOperation | null)[];\n easing?: string | string[];\n offset?: number | (number | null)[];\n}\n\ninterface PushEventInit extends ExtendableEventInit {\n data?: PushMessageDataInit;\n}\n\ninterface PushSubscriptionChangeInit extends ExtendableEventInit {\n newSubscription?: PushSubscription;\n oldSubscription?: PushSubscription;\n}\n\ninterface PushSubscriptionJSON {\n endpoint?: string;\n expirationTime?: number | null;\n keys?: Record;\n}\n\ninterface PushSubscriptionOptionsInit {\n applicationServerKey?: BufferSource | string;\n userVisibleOnly?: boolean;\n}\n\ninterface QueuingStrategy {\n highWaterMark?: number;\n size?: WritableStreamChunkCallback;\n}\n\ninterface RTCAnswerOptions extends RTCOfferAnswerOptions {\n}\n\ninterface RTCCertificateExpiration {\n expires?: number;\n}\n\ninterface RTCConfiguration {\n bundlePolicy?: RTCBundlePolicy;\n certificates?: RTCCertificate[];\n iceCandidatePoolSize?: number;\n iceServers?: RTCIceServer[];\n iceTransportPolicy?: RTCIceTransportPolicy;\n peerIdentity?: string;\n rtcpMuxPolicy?: RTCRtcpMuxPolicy;\n}\n\ninterface RTCDTMFToneChangeEventInit extends EventInit {\n tone: string;\n}\n\ninterface RTCDataChannelEventInit extends EventInit {\n channel: RTCDataChannel;\n}\n\ninterface RTCDataChannelInit {\n id?: number;\n maxPacketLifeTime?: number;\n maxRetransmits?: number;\n negotiated?: boolean;\n ordered?: boolean;\n priority?: RTCPriorityType;\n protocol?: string;\n}\n\ninterface RTCDtlsFingerprint {\n algorithm?: string;\n value?: string;\n}\n\ninterface RTCDtlsParameters {\n fingerprints?: RTCDtlsFingerprint[];\n role?: RTCDtlsRole;\n}\n\ninterface RTCErrorEventInit extends EventInit {\n error?: RTCError | null;\n}\n\ninterface RTCIceCandidateAttributes extends RTCStats {\n addressSourceUrl?: string;\n candidateType?: RTCStatsIceCandidateType;\n ipAddress?: string;\n portNumber?: number;\n priority?: number;\n transport?: string;\n}\n\ninterface RTCIceCandidateComplete {\n}\n\ninterface RTCIceCandidateDictionary {\n foundation?: string;\n ip?: string;\n msMTurnSessionId?: string;\n port?: number;\n priority?: number;\n protocol?: RTCIceProtocol;\n relatedAddress?: string;\n relatedPort?: number;\n tcpType?: RTCIceTcpCandidateType;\n type?: RTCIceCandidateType;\n}\n\ninterface RTCIceCandidateInit {\n candidate?: string;\n sdpMLineIndex?: number | null;\n sdpMid?: string | null;\n usernameFragment?: string;\n}\n\ninterface RTCIceCandidatePair {\n local?: RTCIceCandidate;\n remote?: RTCIceCandidate;\n}\n\ninterface RTCIceCandidatePairStats extends RTCStats {\n availableIncomingBitrate?: number;\n availableOutgoingBitrate?: number;\n bytesReceived?: number;\n bytesSent?: number;\n localCandidateId?: string;\n nominated?: boolean;\n priority?: number;\n readable?: boolean;\n remoteCandidateId?: string;\n roundTripTime?: number;\n state?: RTCStatsIceCandidatePairState;\n transportId?: string;\n writable?: boolean;\n}\n\ninterface RTCIceGatherOptions {\n gatherPolicy?: RTCIceGatherPolicy;\n iceservers?: RTCIceServer[];\n portRange?: MSPortRange;\n}\n\ninterface RTCIceParameters {\n password?: string;\n usernameFragment?: string;\n}\n\ninterface RTCIceServer {\n credential?: string | RTCOAuthCredential;\n credentialType?: RTCIceCredentialType;\n urls: string | string[];\n username?: string;\n}\n\ninterface RTCIdentityAssertionResult {\n assertion: string;\n idp: RTCIdentityProviderDetails;\n}\n\ninterface RTCIdentityProvider {\n generateAssertion: GenerateAssertionCallback;\n validateAssertion: ValidateAssertionCallback;\n}\n\ninterface RTCIdentityProviderDetails {\n domain: string;\n protocol?: string;\n}\n\ninterface RTCIdentityProviderOptions {\n peerIdentity?: string;\n protocol?: string;\n usernameHint?: string;\n}\n\ninterface RTCIdentityValidationResult {\n contents: string;\n identity: string;\n}\n\ninterface RTCInboundRTPStreamStats extends RTCRTPStreamStats {\n bytesReceived?: number;\n fractionLost?: number;\n jitter?: number;\n packetsLost?: number;\n packetsReceived?: number;\n}\n\ninterface RTCMediaStreamTrackStats extends RTCStats {\n audioLevel?: number;\n echoReturnLoss?: number;\n echoReturnLossEnhancement?: number;\n frameHeight?: number;\n frameWidth?: number;\n framesCorrupted?: number;\n framesDecoded?: number;\n framesDropped?: number;\n framesPerSecond?: number;\n framesReceived?: number;\n framesSent?: number;\n remoteSource?: boolean;\n ssrcIds?: string[];\n trackIdentifier?: string;\n}\n\ninterface RTCOAuthCredential {\n accessToken: string;\n macKey: string;\n}\n\ninterface RTCOfferAnswerOptions {\n voiceActivityDetection?: boolean;\n}\n\ninterface RTCOfferOptions extends RTCOfferAnswerOptions {\n iceRestart?: boolean;\n offerToReceiveAudio?: boolean;\n offerToReceiveVideo?: boolean;\n}\n\ninterface RTCOutboundRTPStreamStats extends RTCRTPStreamStats {\n bytesSent?: number;\n packetsSent?: number;\n roundTripTime?: number;\n targetBitrate?: number;\n}\n\ninterface RTCPeerConnectionIceErrorEventInit extends EventInit {\n errorCode: number;\n hostCandidate?: string;\n statusText?: string;\n url?: string;\n}\n\ninterface RTCPeerConnectionIceEventInit extends EventInit {\n candidate?: RTCIceCandidate | null;\n url?: string | null;\n}\n\ninterface RTCRTPStreamStats extends RTCStats {\n associateStatsId?: string;\n codecId?: string;\n firCount?: number;\n isRemote?: boolean;\n mediaTrackId?: string;\n mediaType?: string;\n nackCount?: number;\n pliCount?: number;\n sliCount?: number;\n ssrc?: string;\n transportId?: string;\n}\n\ninterface RTCRtcpFeedback {\n parameter?: string;\n type?: string;\n}\n\ninterface RTCRtcpParameters {\n cname?: string;\n reducedSize?: boolean;\n}\n\ninterface RTCRtpCapabilities {\n codecs: RTCRtpCodecCapability[];\n headerExtensions: RTCRtpHeaderExtensionCapability[];\n}\n\ninterface RTCRtpCodecCapability {\n channels?: number;\n clockRate: number;\n mimeType: string;\n sdpFmtpLine?: string;\n}\n\ninterface RTCRtpCodecParameters {\n channels?: number;\n clockRate: number;\n mimeType: string;\n payloadType: number;\n sdpFmtpLine?: string;\n}\n\ninterface RTCRtpCodingParameters {\n rid?: string;\n}\n\ninterface RTCRtpContributingSource {\n audioLevel?: number;\n source: number;\n timestamp: number;\n}\n\ninterface RTCRtpDecodingParameters extends RTCRtpCodingParameters {\n}\n\ninterface RTCRtpEncodingParameters extends RTCRtpCodingParameters {\n active?: boolean;\n codecPayloadType?: number;\n dtx?: RTCDtxStatus;\n maxBitrate?: number;\n maxFramerate?: number;\n priority?: RTCPriorityType;\n ptime?: number;\n scaleResolutionDownBy?: number;\n}\n\ninterface RTCRtpFecParameters {\n mechanism?: string;\n ssrc?: number;\n}\n\ninterface RTCRtpHeaderExtension {\n kind?: string;\n preferredEncrypt?: boolean;\n preferredId?: number;\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionCapability {\n uri?: string;\n}\n\ninterface RTCRtpHeaderExtensionParameters {\n encrypted?: boolean;\n id: number;\n uri: string;\n}\n\ninterface RTCRtpParameters {\n codecs: RTCRtpCodecParameters[];\n headerExtensions: RTCRtpHeaderExtensionParameters[];\n rtcp: RTCRtcpParameters;\n}\n\ninterface RTCRtpReceiveParameters extends RTCRtpParameters {\n encodings: RTCRtpDecodingParameters[];\n}\n\ninterface RTCRtpRtxParameters {\n ssrc?: number;\n}\n\ninterface RTCRtpSendParameters extends RTCRtpParameters {\n degradationPreference?: RTCDegradationPreference;\n encodings: RTCRtpEncodingParameters[];\n transactionId: string;\n}\n\ninterface RTCRtpSynchronizationSource extends RTCRtpContributingSource {\n voiceActivityFlag?: boolean;\n}\n\ninterface RTCRtpTransceiverInit {\n direction?: RTCRtpTransceiverDirection;\n sendEncodings?: RTCRtpEncodingParameters[];\n streams?: MediaStream[];\n}\n\ninterface RTCRtpUnhandled {\n muxId?: string;\n payloadType?: number;\n ssrc?: number;\n}\n\ninterface RTCSessionDescriptionInit {\n sdp?: string;\n type: RTCSdpType;\n}\n\ninterface RTCSrtpKeyParam {\n keyMethod?: string;\n keySalt?: string;\n lifetime?: string;\n mkiLength?: number;\n mkiValue?: number;\n}\n\ninterface RTCSrtpSdesParameters {\n cryptoSuite?: string;\n keyParams?: RTCSrtpKeyParam[];\n sessionParams?: string[];\n tag?: number;\n}\n\ninterface RTCSsrcRange {\n max?: number;\n min?: number;\n}\n\ninterface RTCStats {\n id: string;\n timestamp: number;\n type: RTCStatsType;\n}\n\ninterface RTCStatsEventInit extends EventInit {\n report: RTCStatsReport;\n}\n\ninterface RTCStatsReport {\n}\n\ninterface RTCTrackEventInit extends EventInit {\n receiver: RTCRtpReceiver;\n streams?: MediaStream[];\n track: MediaStreamTrack;\n transceiver: RTCRtpTransceiver;\n}\n\ninterface RTCTransportStats extends RTCStats {\n activeConnection?: boolean;\n bytesReceived?: number;\n bytesSent?: number;\n localCertificateId?: string;\n remoteCertificateId?: string;\n rtcpTransportStatsId?: string;\n selectedCandidatePairId?: string;\n}\n\ninterface RegistrationOptions {\n scope?: string;\n type?: WorkerType;\n updateViaCache?: ServiceWorkerUpdateViaCache;\n}\n\ninterface RequestInit {\n body?: BodyInit | null;\n cache?: RequestCache;\n credentials?: RequestCredentials;\n headers?: HeadersInit;\n integrity?: string;\n keepalive?: boolean;\n method?: string;\n mode?: RequestMode;\n redirect?: RequestRedirect;\n referrer?: string;\n referrerPolicy?: ReferrerPolicy;\n signal?: AbortSignal | null;\n window?: any;\n}\n\ninterface ResponseInit {\n headers?: HeadersInit;\n status?: number;\n statusText?: string;\n}\n\ninterface RsaHashedImportParams extends Algorithm {\n hash: string | Algorithm;\n}\n\ninterface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {\n hash: KeyAlgorithm;\n}\n\ninterface RsaHashedKeyGenParams extends RsaKeyGenParams {\n hash: string | Algorithm;\n}\n\ninterface RsaKeyAlgorithm extends KeyAlgorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaKeyGenParams extends Algorithm {\n modulusLength: number;\n publicExponent: Uint8Array;\n}\n\ninterface RsaOaepParams extends Algorithm {\n label?: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface RsaOtherPrimesInfo {\n d?: string;\n r?: string;\n t?: string;\n}\n\ninterface RsaPssParams extends Algorithm {\n saltLength: number;\n}\n\ninterface ScopedCredentialDescriptor {\n id: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null;\n transports?: Transport[];\n type: ScopedCredentialType;\n}\n\ninterface ScopedCredentialOptions {\n excludeList?: ScopedCredentialDescriptor[];\n extensions?: WebAuthnExtensions;\n rpId?: string;\n timeoutSeconds?: number;\n}\n\ninterface ScopedCredentialParameters {\n algorithm: string | Algorithm;\n type: ScopedCredentialType;\n}\n\ninterface ScrollIntoViewOptions extends ScrollOptions {\n block?: ScrollLogicalPosition;\n inline?: ScrollLogicalPosition;\n}\n\ninterface ScrollOptions {\n behavior?: ScrollBehavior;\n}\n\ninterface ScrollToOptions extends ScrollOptions {\n left?: number;\n top?: number;\n}\n\ninterface SecurityPolicyViolationEventInit extends EventInit {\n blockedURI?: string;\n columnNumber?: number;\n documentURI?: string;\n effectiveDirective?: string;\n lineNumber?: number;\n originalPolicy?: string;\n referrer?: string;\n sourceFile?: string;\n statusCode?: number;\n violatedDirective?: string;\n}\n\ninterface ServiceWorkerMessageEventInit extends EventInit {\n data?: any;\n lastEventId?: string;\n origin?: string;\n ports?: MessagePort[] | null;\n source?: ServiceWorker | MessagePort | null;\n}\n\ninterface SpeechSynthesisEventInit extends EventInit {\n charIndex?: number;\n charLength?: number;\n elapsedTime?: number;\n name?: string;\n utterance?: SpeechSynthesisUtterance | null;\n}\n\ninterface StereoPannerOptions extends AudioNodeOptions {\n pan?: number;\n}\n\ninterface StorageEstimate {\n quota?: number;\n usage?: number;\n}\n\ninterface StorageEventInit extends EventInit {\n key?: string | null;\n newValue?: string | null;\n oldValue?: string | null;\n storageArea?: Storage | null;\n url?: string;\n}\n\ninterface StoreExceptionsInformation extends ExceptionInformation {\n detailURI?: string | null;\n explanationString?: string | null;\n siteName?: string | null;\n}\n\ninterface StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation {\n arrayOfDomainStrings?: string[];\n}\n\ninterface SyncEventInit extends ExtendableEventInit {\n lastChance?: boolean;\n tag: string;\n}\n\ninterface TextDecodeOptions {\n stream?: boolean;\n}\n\ninterface TextDecoderOptions {\n fatal?: boolean;\n ignoreBOM?: boolean;\n}\n\ninterface TouchEventInit extends EventModifierInit {\n changedTouches?: Touch[];\n targetTouches?: Touch[];\n touches?: Touch[];\n}\n\ninterface TouchInit {\n altitudeAngle?: number;\n azimuthAngle?: number;\n clientX?: number;\n clientY?: number;\n force?: number;\n identifier: number;\n pageX?: number;\n pageY?: number;\n radiusX?: number;\n radiusY?: number;\n rotationAngle?: number;\n screenX?: number;\n screenY?: number;\n target: EventTarget;\n touchType?: TouchType;\n}\n\ninterface TrackEventInit extends EventInit {\n track?: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ninterface TransitionEventInit extends EventInit {\n elapsedTime?: number;\n propertyName?: string;\n pseudoElement?: string;\n}\n\ninterface UIEventInit extends EventInit {\n detail?: number;\n view?: Window | null;\n}\n\ninterface UnderlyingSink {\n abort?: WritableStreamErrorCallback;\n close?: WritableStreamDefaultControllerCallback;\n start: WritableStreamDefaultControllerCallback;\n write?: WritableStreamChunkCallback;\n}\n\ninterface VRDisplayEventInit extends EventInit {\n display: VRDisplay;\n reason?: VRDisplayEventReason;\n}\n\ninterface VRLayer {\n leftBounds?: number[] | Float32Array | null;\n rightBounds?: number[] | Float32Array | null;\n source?: HTMLCanvasElement | null;\n}\n\ninterface VRStageParameters {\n sittingToStandingTransform?: Float32Array;\n sizeX?: number;\n sizeY?: number;\n}\n\ninterface WaveShaperOptions extends AudioNodeOptions {\n curve?: number[] | Float32Array;\n oversample?: OverSampleType;\n}\n\ninterface WebAuthnExtensions {\n}\n\ninterface WebGLContextAttributes {\n alpha?: boolean;\n antialias?: boolean;\n depth?: boolean;\n failIfMajorPerformanceCaveat?: boolean;\n premultipliedAlpha?: boolean;\n preserveDrawingBuffer?: boolean;\n stencil?: boolean;\n}\n\ninterface WebGLContextEventInit extends EventInit {\n statusMessage?: string;\n}\n\ninterface WheelEventInit extends MouseEventInit {\n deltaMode?: number;\n deltaX?: number;\n deltaY?: number;\n deltaZ?: number;\n}\n\ninterface WorkletOptions {\n credentials?: RequestCredentials;\n}\n\ninterface EventListener {\n (evt: Event): void;\n}\n\ninterface ANGLE_instanced_arrays {\n drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number): void;\n drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number): void;\n vertexAttribDivisorANGLE(index: number, divisor: number): void;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n}\n\ndeclare var ANGLE_instanced_arrays: {\n prototype: ANGLE_instanced_arrays;\n new(): ANGLE_instanced_arrays;\n readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;\n};\n\ninterface AbortController {\n readonly signal: AbortSignal;\n abort(): void;\n}\n\ndeclare var AbortController: {\n prototype: AbortController;\n new(): AbortController;\n};\n\ninterface AbortSignalEventMap {\n \"abort\": ProgressEvent;\n}\n\ninterface AbortSignal extends EventTarget {\n readonly aborted: boolean;\n onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AbortSignal: {\n prototype: AbortSignal;\n new(): AbortSignal;\n};\n\ninterface AbstractWorkerEventMap {\n \"error\": ErrorEvent;\n}\n\ninterface AbstractWorker {\n onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null;\n addEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface AesCfbParams extends Algorithm {\n iv: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface AesCmacParams extends Algorithm {\n length: number;\n}\n\ninterface AnalyserNode extends AudioNode {\n fftSize: number;\n readonly frequencyBinCount: number;\n maxDecibels: number;\n minDecibels: number;\n smoothingTimeConstant: number;\n getByteFrequencyData(array: Uint8Array): void;\n getByteTimeDomainData(array: Uint8Array): void;\n getFloatFrequencyData(array: Float32Array): void;\n getFloatTimeDomainData(array: Float32Array): void;\n}\n\ndeclare var AnalyserNode: {\n prototype: AnalyserNode;\n new(context: BaseAudioContext, options?: AnalyserOptions): AnalyserNode;\n};\n\ninterface Animatable {\n animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation;\n getAnimations(): Animation[];\n}\n\ninterface AnimationEventMap {\n \"cancel\": AnimationPlaybackEvent;\n \"finish\": AnimationPlaybackEvent;\n}\n\ninterface Animation extends EventTarget {\n currentTime: number | null;\n effect: AnimationEffect | null;\n readonly finished: Promise;\n id: string;\n oncancel: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\n onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null;\n readonly pending: boolean;\n readonly playState: AnimationPlayState;\n playbackRate: number;\n readonly ready: Promise;\n startTime: number | null;\n timeline: AnimationTimeline | null;\n cancel(): void;\n finish(): void;\n pause(): void;\n play(): void;\n reverse(): void;\n updatePlaybackRate(playbackRate: number): void;\n addEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Animation, ev: AnimationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Animation: {\n prototype: Animation;\n new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation;\n};\n\ninterface AnimationEffect {\n getComputedTiming(): ComputedEffectTiming;\n getTiming(): EffectTiming;\n updateTiming(timing?: OptionalEffectTiming): void;\n}\n\ndeclare var AnimationEffect: {\n prototype: AnimationEffect;\n new(): AnimationEffect;\n};\n\ninterface AnimationEvent extends Event {\n readonly animationName: string;\n readonly elapsedTime: number;\n readonly pseudoElement: string;\n}\n\ndeclare var AnimationEvent: {\n prototype: AnimationEvent;\n new(type: string, animationEventInitDict?: AnimationEventInit): AnimationEvent;\n};\n\ninterface AnimationPlaybackEvent extends Event {\n readonly currentTime: number | null;\n readonly timelineTime: number | null;\n}\n\ndeclare var AnimationPlaybackEvent: {\n prototype: AnimationPlaybackEvent;\n new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent;\n};\n\ninterface AnimationTimeline {\n readonly currentTime: number | null;\n}\n\ndeclare var AnimationTimeline: {\n prototype: AnimationTimeline;\n new(): AnimationTimeline;\n};\n\ninterface ApplicationCacheEventMap {\n \"cached\": Event;\n \"checking\": Event;\n \"downloading\": Event;\n \"error\": Event;\n \"noupdate\": Event;\n \"obsolete\": Event;\n \"progress\": ProgressEvent;\n \"updateready\": Event;\n}\n\ninterface ApplicationCache extends EventTarget {\n oncached: ((this: ApplicationCache, ev: Event) => any) | null;\n onchecking: ((this: ApplicationCache, ev: Event) => any) | null;\n ondownloading: ((this: ApplicationCache, ev: Event) => any) | null;\n onerror: ((this: ApplicationCache, ev: Event) => any) | null;\n onnoupdate: ((this: ApplicationCache, ev: Event) => any) | null;\n onobsolete: ((this: ApplicationCache, ev: Event) => any) | null;\n onprogress: ((this: ApplicationCache, ev: ProgressEvent) => any) | null;\n onupdateready: ((this: ApplicationCache, ev: Event) => any) | null;\n readonly status: number;\n abort(): void;\n swapCache(): void;\n update(): void;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n addEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ApplicationCache, ev: ApplicationCacheEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ApplicationCache: {\n prototype: ApplicationCache;\n new(): ApplicationCache;\n readonly CHECKING: number;\n readonly DOWNLOADING: number;\n readonly IDLE: number;\n readonly OBSOLETE: number;\n readonly UNCACHED: number;\n readonly UPDATEREADY: number;\n};\n\ninterface AssignedNodesOptions {\n flatten?: boolean;\n}\n\ninterface Attr extends Node {\n readonly name: string;\n readonly ownerElement: Element | null;\n readonly prefix: string | null;\n readonly specified: boolean;\n value: string;\n}\n\ndeclare var Attr: {\n prototype: Attr;\n new(): Attr;\n};\n\ninterface AudioBuffer {\n readonly duration: number;\n readonly length: number;\n readonly numberOfChannels: number;\n readonly sampleRate: number;\n copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;\n copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;\n getChannelData(channel: number): Float32Array;\n}\n\ndeclare var AudioBuffer: {\n prototype: AudioBuffer;\n new(options: AudioBufferOptions): AudioBuffer;\n};\n\ninterface AudioBufferSourceNode extends AudioScheduledSourceNode {\n buffer: AudioBuffer | null;\n readonly detune: AudioParam;\n loop: boolean;\n loopEnd: number;\n loopStart: number;\n readonly playbackRate: AudioParam;\n start(when?: number, offset?: number, duration?: number): void;\n addEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioBufferSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioBufferSourceNode: {\n prototype: AudioBufferSourceNode;\n new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode;\n};\n\ninterface AudioContext extends BaseAudioContext {\n readonly baseLatency: number;\n readonly outputLatency: number;\n close(): Promise;\n createMediaElementSource(mediaElement: HTMLMediaElement): MediaElementAudioSourceNode;\n createMediaStreamDestination(): MediaStreamAudioDestinationNode;\n createMediaStreamSource(mediaStream: MediaStream): MediaStreamAudioSourceNode;\n createMediaStreamTrackSource(mediaStreamTrack: MediaStreamTrack): MediaStreamTrackAudioSourceNode;\n getOutputTimestamp(): AudioTimestamp;\n suspend(): Promise;\n addEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioContext: {\n prototype: AudioContext;\n new(contextOptions?: AudioContextOptions): AudioContext;\n};\n\ninterface AudioDestinationNode extends AudioNode {\n readonly maxChannelCount: number;\n}\n\ndeclare var AudioDestinationNode: {\n prototype: AudioDestinationNode;\n new(): AudioDestinationNode;\n};\n\ninterface AudioListener {\n readonly forwardX: AudioParam;\n readonly forwardY: AudioParam;\n readonly forwardZ: AudioParam;\n readonly positionX: AudioParam;\n readonly positionY: AudioParam;\n readonly positionZ: AudioParam;\n readonly upX: AudioParam;\n readonly upY: AudioParam;\n readonly upZ: AudioParam;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number, xUp: number, yUp: number, zUp: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n}\n\ndeclare var AudioListener: {\n prototype: AudioListener;\n new(): AudioListener;\n};\n\ninterface AudioNode extends EventTarget {\n channelCount: number;\n channelCountMode: ChannelCountMode;\n channelInterpretation: ChannelInterpretation;\n readonly context: BaseAudioContext;\n readonly numberOfInputs: number;\n readonly numberOfOutputs: number;\n connect(destinationNode: AudioNode, output?: number, input?: number): AudioNode;\n connect(destinationParam: AudioParam, output?: number): void;\n disconnect(): void;\n disconnect(output: number): void;\n disconnect(destinationNode: AudioNode): void;\n disconnect(destinationNode: AudioNode, output: number): void;\n disconnect(destinationNode: AudioNode, output: number, input: number): void;\n disconnect(destinationParam: AudioParam): void;\n disconnect(destinationParam: AudioParam, output: number): void;\n}\n\ndeclare var AudioNode: {\n prototype: AudioNode;\n new(): AudioNode;\n};\n\ninterface AudioParam {\n automationRate: AutomationRate;\n readonly defaultValue: number;\n readonly maxValue: number;\n readonly minValue: number;\n value: number;\n cancelAndHoldAtTime(cancelTime: number): AudioParam;\n cancelScheduledValues(cancelTime: number): AudioParam;\n exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;\n linearRampToValueAtTime(value: number, endTime: number): AudioParam;\n setTargetAtTime(target: number, startTime: number, timeConstant: number): AudioParam;\n setValueAtTime(value: number, startTime: number): AudioParam;\n setValueCurveAtTime(values: number[] | Float32Array, startTime: number, duration: number): AudioParam;\n}\n\ndeclare var AudioParam: {\n prototype: AudioParam;\n new(): AudioParam;\n};\n\ninterface AudioParamMap {\n forEach(callbackfn: (value: AudioParam, key: string, parent: AudioParamMap) => void, thisArg?: any): void;\n}\n\ndeclare var AudioParamMap: {\n prototype: AudioParamMap;\n new(): AudioParamMap;\n};\n\ninterface AudioProcessingEvent extends Event {\n readonly inputBuffer: AudioBuffer;\n readonly outputBuffer: AudioBuffer;\n readonly playbackTime: number;\n}\n\ndeclare var AudioProcessingEvent: {\n prototype: AudioProcessingEvent;\n new(type: string, eventInitDict: AudioProcessingEventInit): AudioProcessingEvent;\n};\n\ninterface AudioScheduledSourceNodeEventMap {\n \"ended\": Event;\n}\n\ninterface AudioScheduledSourceNode extends AudioNode {\n onended: ((this: AudioScheduledSourceNode, ev: Event) => any) | null;\n start(when?: number): void;\n stop(when?: number): void;\n addEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioScheduledSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioScheduledSourceNode: {\n prototype: AudioScheduledSourceNode;\n new(): AudioScheduledSourceNode;\n};\n\ninterface AudioTrack {\n enabled: boolean;\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var AudioTrack: {\n prototype: AudioTrack;\n new(): AudioTrack;\n};\n\ninterface AudioTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface AudioTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: AudioTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: AudioTrackList, ev: TrackEvent) => any) | null;\n getTrackById(id: string): AudioTrack | null;\n item(index: number): AudioTrack;\n addEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioTrackList, ev: AudioTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: AudioTrack;\n}\n\ndeclare var AudioTrackList: {\n prototype: AudioTrackList;\n new(): AudioTrackList;\n};\n\ninterface AudioWorklet extends Worklet {\n}\n\ndeclare var AudioWorklet: {\n prototype: AudioWorklet;\n new(): AudioWorklet;\n};\n\ninterface AudioWorkletNodeEventMap {\n \"processorerror\": Event;\n}\n\ninterface AudioWorkletNode extends AudioNode {\n onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null;\n readonly parameters: AudioParamMap;\n readonly port: MessagePort;\n addEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: AudioWorkletNode, ev: AudioWorkletNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var AudioWorkletNode: {\n prototype: AudioWorkletNode;\n new(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions): AudioWorkletNode;\n};\n\ninterface BarProp {\n readonly visible: boolean;\n}\n\ndeclare var BarProp: {\n prototype: BarProp;\n new(): BarProp;\n};\n\ninterface BaseAudioContextEventMap {\n \"statechange\": Event;\n}\n\ninterface BaseAudioContext extends EventTarget {\n readonly audioWorklet: AudioWorklet;\n readonly currentTime: number;\n readonly destination: AudioDestinationNode;\n readonly listener: AudioListener;\n onstatechange: ((this: BaseAudioContext, ev: Event) => any) | null;\n readonly sampleRate: number;\n readonly state: AudioContextState;\n createAnalyser(): AnalyserNode;\n createBiquadFilter(): BiquadFilterNode;\n createBuffer(numberOfChannels: number, length: number, sampleRate: number): AudioBuffer;\n createBufferSource(): AudioBufferSourceNode;\n createChannelMerger(numberOfInputs?: number): ChannelMergerNode;\n createChannelSplitter(numberOfOutputs?: number): ChannelSplitterNode;\n createConstantSource(): ConstantSourceNode;\n createConvolver(): ConvolverNode;\n createDelay(maxDelayTime?: number): DelayNode;\n createDynamicsCompressor(): DynamicsCompressorNode;\n createGain(): GainNode;\n createIIRFilter(feedforward: number[], feedback: number[]): IIRFilterNode;\n createOscillator(): OscillatorNode;\n createPanner(): PannerNode;\n createPeriodicWave(real: number[] | Float32Array, imag: number[] | Float32Array, constraints?: PeriodicWaveConstraints): PeriodicWave;\n createScriptProcessor(bufferSize?: number, numberOfInputChannels?: number, numberOfOutputChannels?: number): ScriptProcessorNode;\n createStereoPanner(): StereoPannerNode;\n createWaveShaper(): WaveShaperNode;\n decodeAudioData(audioData: ArrayBuffer, successCallback?: DecodeSuccessCallback, errorCallback?: DecodeErrorCallback): Promise;\n resume(): Promise;\n addEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: BaseAudioContext, ev: BaseAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BaseAudioContext: {\n prototype: BaseAudioContext;\n new(): BaseAudioContext;\n};\n\ninterface BeforeUnloadEvent extends Event {\n returnValue: any;\n}\n\ndeclare var BeforeUnloadEvent: {\n prototype: BeforeUnloadEvent;\n new(): BeforeUnloadEvent;\n};\n\ninterface BhxBrowser {\n readonly lastError: DOMException;\n checkMatchesGlobExpression(pattern: string, value: string): boolean;\n checkMatchesUriExpression(pattern: string, value: string): boolean;\n clearLastError(): void;\n currentWindowId(): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(functionId: number, destination: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n getExtensionId(): string;\n getThisAddress(): any;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericListenerHandler(eventHandler: Function): void;\n setLastError(parameters: string): void;\n webPlatformGenericFunction(destination: any, parameters?: string, callbackId?: number): void;\n}\n\ndeclare var BhxBrowser: {\n prototype: BhxBrowser;\n new(): BhxBrowser;\n};\n\ninterface BiquadFilterNode extends AudioNode {\n readonly Q: AudioParam;\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n readonly gain: AudioParam;\n type: BiquadFilterType;\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var BiquadFilterNode: {\n prototype: BiquadFilterNode;\n new(context: BaseAudioContext, options?: BiquadFilterOptions): BiquadFilterNode;\n};\n\ninterface Blob {\n readonly size: number;\n readonly type: string;\n slice(start?: number, end?: number, contentType?: string): Blob;\n}\n\ndeclare var Blob: {\n prototype: Blob;\n new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;\n};\n\ninterface Body {\n readonly body: ReadableStream | null;\n readonly bodyUsed: boolean;\n arrayBuffer(): Promise;\n blob(): Promise;\n formData(): Promise;\n json(): Promise;\n text(): Promise;\n}\n\ninterface BroadcastChannelEventMap {\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface BroadcastChannel extends EventTarget {\n /**\n * Returns the channel name (as passed to the constructor).\n */\n readonly name: string;\n onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null;\n /**\n * Closes the BroadcastChannel object, opening it up to garbage collection.\n */\n close(): void;\n /**\n * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.\n */\n postMessage(message: any): void;\n addEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var BroadcastChannel: {\n prototype: BroadcastChannel;\n new(name: string): BroadcastChannel;\n};\n\ninterface BroadcastChannelEventMap {\n message: MessageEvent;\n messageerror: MessageEvent;\n}\n\ninterface ByteLengthQueuingStrategy {\n highWaterMark: number;\n size(chunk?: any): number;\n}\n\ndeclare var ByteLengthQueuingStrategy: {\n prototype: ByteLengthQueuingStrategy;\n new(strategy: QueuingStrategy): ByteLengthQueuingStrategy;\n};\n\ninterface CDATASection extends Text {\n}\n\ndeclare var CDATASection: {\n prototype: CDATASection;\n new(): CDATASection;\n};\n\ninterface CSS {\n escape(value: string): string;\n supports(property: string, value?: string): boolean;\n}\ndeclare var CSS: CSS;\n\ninterface CSSConditionRule extends CSSGroupingRule {\n conditionText: string;\n}\n\ndeclare var CSSConditionRule: {\n prototype: CSSConditionRule;\n new(): CSSConditionRule;\n};\n\ninterface CSSFontFaceRule extends CSSRule {\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSFontFaceRule: {\n prototype: CSSFontFaceRule;\n new(): CSSFontFaceRule;\n};\n\ninterface CSSGroupingRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n deleteRule(index: number): void;\n insertRule(rule: string, index: number): number;\n}\n\ndeclare var CSSGroupingRule: {\n prototype: CSSGroupingRule;\n new(): CSSGroupingRule;\n};\n\ninterface CSSImportRule extends CSSRule {\n readonly href: string;\n readonly media: MediaList;\n readonly styleSheet: CSSStyleSheet;\n}\n\ndeclare var CSSImportRule: {\n prototype: CSSImportRule;\n new(): CSSImportRule;\n};\n\ninterface CSSKeyframeRule extends CSSRule {\n keyText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSKeyframeRule: {\n prototype: CSSKeyframeRule;\n new(): CSSKeyframeRule;\n};\n\ninterface CSSKeyframesRule extends CSSRule {\n readonly cssRules: CSSRuleList;\n name: string;\n appendRule(rule: string): void;\n deleteRule(select: string): void;\n findRule(select: string): CSSKeyframeRule | null;\n}\n\ndeclare var CSSKeyframesRule: {\n prototype: CSSKeyframesRule;\n new(): CSSKeyframesRule;\n};\n\ninterface CSSMediaRule extends CSSConditionRule {\n readonly media: MediaList;\n}\n\ndeclare var CSSMediaRule: {\n prototype: CSSMediaRule;\n new(): CSSMediaRule;\n};\n\ninterface CSSNamespaceRule extends CSSRule {\n readonly namespaceURI: string;\n readonly prefix: string;\n}\n\ndeclare var CSSNamespaceRule: {\n prototype: CSSNamespaceRule;\n new(): CSSNamespaceRule;\n};\n\ninterface CSSPageRule extends CSSRule {\n readonly pseudoClass: string;\n readonly selector: string;\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSPageRule: {\n prototype: CSSPageRule;\n new(): CSSPageRule;\n};\n\ninterface CSSRule {\n cssText: string;\n readonly parentRule: CSSRule | null;\n readonly parentStyleSheet: CSSStyleSheet | null;\n readonly type: number;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n}\n\ndeclare var CSSRule: {\n prototype: CSSRule;\n new(): CSSRule;\n readonly CHARSET_RULE: number;\n readonly FONT_FACE_RULE: number;\n readonly IMPORT_RULE: number;\n readonly KEYFRAMES_RULE: number;\n readonly KEYFRAME_RULE: number;\n readonly MEDIA_RULE: number;\n readonly NAMESPACE_RULE: number;\n readonly PAGE_RULE: number;\n readonly STYLE_RULE: number;\n readonly SUPPORTS_RULE: number;\n readonly UNKNOWN_RULE: number;\n readonly VIEWPORT_RULE: number;\n};\n\ninterface CSSRuleList {\n readonly length: number;\n item(index: number): CSSRule | null;\n [index: number]: CSSRule;\n}\n\ndeclare var CSSRuleList: {\n prototype: CSSRuleList;\n new(): CSSRuleList;\n};\n\ninterface CSSStyleDeclaration {\n alignContent: string | null;\n alignItems: string | null;\n alignSelf: string | null;\n alignmentBaseline: string | null;\n animation: string | null;\n animationDelay: string | null;\n animationDirection: string | null;\n animationDuration: string | null;\n animationFillMode: string | null;\n animationIterationCount: string | null;\n animationName: string | null;\n animationPlayState: string | null;\n animationTimingFunction: string | null;\n backfaceVisibility: string | null;\n background: string | null;\n backgroundAttachment: string | null;\n backgroundClip: string | null;\n backgroundColor: string | null;\n backgroundImage: string | null;\n backgroundOrigin: string | null;\n backgroundPosition: string | null;\n backgroundPositionX: string | null;\n backgroundPositionY: string | null;\n backgroundRepeat: string | null;\n backgroundSize: string | null;\n baselineShift: string | null;\n border: string | null;\n borderBottom: string | null;\n borderBottomColor: string | null;\n borderBottomLeftRadius: string | null;\n borderBottomRightRadius: string | null;\n borderBottomStyle: string | null;\n borderBottomWidth: string | null;\n borderCollapse: string | null;\n borderColor: string | null;\n borderImage: string | null;\n borderImageOutset: string | null;\n borderImageRepeat: string | null;\n borderImageSlice: string | null;\n borderImageSource: string | null;\n borderImageWidth: string | null;\n borderLeft: string | null;\n borderLeftColor: string | null;\n borderLeftStyle: string | null;\n borderLeftWidth: string | null;\n borderRadius: string | null;\n borderRight: string | null;\n borderRightColor: string | null;\n borderRightStyle: string | null;\n borderRightWidth: string | null;\n borderSpacing: string | null;\n borderStyle: string | null;\n borderTop: string | null;\n borderTopColor: string | null;\n borderTopLeftRadius: string | null;\n borderTopRightRadius: string | null;\n borderTopStyle: string | null;\n borderTopWidth: string | null;\n borderWidth: string | null;\n bottom: string | null;\n boxShadow: string | null;\n boxSizing: string | null;\n breakAfter: string | null;\n breakBefore: string | null;\n breakInside: string | null;\n captionSide: string | null;\n clear: string | null;\n clip: string | null;\n clipPath: string | null;\n clipRule: string | null;\n color: string | null;\n colorInterpolationFilters: string | null;\n columnCount: any;\n columnFill: string | null;\n columnGap: any;\n columnRule: string | null;\n columnRuleColor: any;\n columnRuleStyle: string | null;\n columnRuleWidth: any;\n columnSpan: string | null;\n columnWidth: any;\n columns: string | null;\n content: string | null;\n counterIncrement: string | null;\n counterReset: string | null;\n cssFloat: string | null;\n cssText: string;\n cursor: string | null;\n direction: string | null;\n display: string | null;\n dominantBaseline: string | null;\n emptyCells: string | null;\n enableBackground: string | null;\n fill: string | null;\n fillOpacity: string | null;\n fillRule: string | null;\n filter: string | null;\n flex: string | null;\n flexBasis: string | null;\n flexDirection: string | null;\n flexFlow: string | null;\n flexGrow: string | null;\n flexShrink: string | null;\n flexWrap: string | null;\n floodColor: string | null;\n floodOpacity: string | null;\n font: string | null;\n fontFamily: string | null;\n fontFeatureSettings: string | null;\n fontSize: string | null;\n fontSizeAdjust: string | null;\n fontStretch: string | null;\n fontStyle: string | null;\n fontVariant: string | null;\n fontWeight: string | null;\n gap: string | null;\n glyphOrientationHorizontal: string | null;\n glyphOrientationVertical: string | null;\n grid: string | null;\n gridArea: string | null;\n gridAutoColumns: string | null;\n gridAutoFlow: string | null;\n gridAutoRows: string | null;\n gridColumn: string | null;\n gridColumnEnd: string | null;\n gridColumnGap: string | null;\n gridColumnStart: string | null;\n gridGap: string | null;\n gridRow: string | null;\n gridRowEnd: string | null;\n gridRowGap: string | null;\n gridRowStart: string | null;\n gridTemplate: string | null;\n gridTemplateAreas: string | null;\n gridTemplateColumns: string | null;\n gridTemplateRows: string | null;\n height: string | null;\n imeMode: string | null;\n justifyContent: string | null;\n justifyItems: string | null;\n justifySelf: string | null;\n kerning: string | null;\n layoutGrid: string | null;\n layoutGridChar: string | null;\n layoutGridLine: string | null;\n layoutGridMode: string | null;\n layoutGridType: string | null;\n left: string | null;\n readonly length: number;\n letterSpacing: string | null;\n lightingColor: string | null;\n lineBreak: string | null;\n lineHeight: string | null;\n listStyle: string | null;\n listStyleImage: string | null;\n listStylePosition: string | null;\n listStyleType: string | null;\n margin: string | null;\n marginBottom: string | null;\n marginLeft: string | null;\n marginRight: string | null;\n marginTop: string | null;\n marker: string | null;\n markerEnd: string | null;\n markerMid: string | null;\n markerStart: string | null;\n mask: string | null;\n maskImage: string | null;\n maxHeight: string | null;\n maxWidth: string | null;\n minHeight: string | null;\n minWidth: string | null;\n msContentZoomChaining: string | null;\n msContentZoomLimit: string | null;\n msContentZoomLimitMax: any;\n msContentZoomLimitMin: any;\n msContentZoomSnap: string | null;\n msContentZoomSnapPoints: string | null;\n msContentZoomSnapType: string | null;\n msContentZooming: string | null;\n msFlowFrom: string | null;\n msFlowInto: string | null;\n msFontFeatureSettings: string | null;\n msGridColumn: any;\n msGridColumnAlign: string | null;\n msGridColumnSpan: any;\n msGridColumns: string | null;\n msGridRow: any;\n msGridRowAlign: string | null;\n msGridRowSpan: any;\n msGridRows: string | null;\n msHighContrastAdjust: string | null;\n msHyphenateLimitChars: string | null;\n msHyphenateLimitLines: any;\n msHyphenateLimitZone: any;\n msHyphens: string | null;\n msImeAlign: string | null;\n msOverflowStyle: string | null;\n msScrollChaining: string | null;\n msScrollLimit: string | null;\n msScrollLimitXMax: any;\n msScrollLimitXMin: any;\n msScrollLimitYMax: any;\n msScrollLimitYMin: any;\n msScrollRails: string | null;\n msScrollSnapPointsX: string | null;\n msScrollSnapPointsY: string | null;\n msScrollSnapType: string | null;\n msScrollSnapX: string | null;\n msScrollSnapY: string | null;\n msScrollTranslation: string | null;\n msTextCombineHorizontal: string | null;\n msTextSizeAdjust: any;\n msTouchAction: string | null;\n msTouchSelect: string | null;\n msUserSelect: string | null;\n msWrapFlow: string;\n msWrapMargin: any;\n msWrapThrough: string;\n objectFit: string | null;\n objectPosition: string | null;\n opacity: string | null;\n order: string | null;\n orphans: string | null;\n outline: string | null;\n outlineColor: string | null;\n outlineOffset: string | null;\n outlineStyle: string | null;\n outlineWidth: string | null;\n overflow: string | null;\n overflowX: string | null;\n overflowY: string | null;\n padding: string | null;\n paddingBottom: string | null;\n paddingLeft: string | null;\n paddingRight: string | null;\n paddingTop: string | null;\n pageBreakAfter: string | null;\n pageBreakBefore: string | null;\n pageBreakInside: string | null;\n readonly parentRule: CSSRule;\n penAction: string | null;\n perspective: string | null;\n perspectiveOrigin: string | null;\n pointerEvents: string | null;\n position: string | null;\n quotes: string | null;\n resize: string | null;\n right: string | null;\n rotate: string | null;\n rowGap: string | null;\n rubyAlign: string | null;\n rubyOverhang: string | null;\n rubyPosition: string | null;\n scale: string | null;\n stopColor: string | null;\n stopOpacity: string | null;\n stroke: string | null;\n strokeDasharray: string | null;\n strokeDashoffset: string | null;\n strokeLinecap: string | null;\n strokeLinejoin: string | null;\n strokeMiterlimit: string | null;\n strokeOpacity: string | null;\n strokeWidth: string | null;\n tableLayout: string | null;\n textAlign: string | null;\n textAlignLast: string | null;\n textAnchor: string | null;\n textCombineUpright: string | null;\n textDecoration: string | null;\n textIndent: string | null;\n textJustify: string | null;\n textKashida: string | null;\n textKashidaSpace: string | null;\n textOverflow: string | null;\n textShadow: string | null;\n textTransform: string | null;\n textUnderlinePosition: string | null;\n top: string | null;\n touchAction: string | null;\n transform: string | null;\n transformOrigin: string | null;\n transformStyle: string | null;\n transition: string | null;\n transitionDelay: string | null;\n transitionDuration: string | null;\n transitionProperty: string | null;\n transitionTimingFunction: string | null;\n translate: string | null;\n unicodeBidi: string | null;\n userSelect: string | null;\n verticalAlign: string | null;\n visibility: string | null;\n webkitAlignContent: string | null;\n webkitAlignItems: string | null;\n webkitAlignSelf: string | null;\n webkitAnimation: string | null;\n webkitAnimationDelay: string | null;\n webkitAnimationDirection: string | null;\n webkitAnimationDuration: string | null;\n webkitAnimationFillMode: string | null;\n webkitAnimationIterationCount: string | null;\n webkitAnimationName: string | null;\n webkitAnimationPlayState: string | null;\n webkitAnimationTimingFunction: string | null;\n webkitAppearance: string | null;\n webkitBackfaceVisibility: string | null;\n webkitBackgroundClip: string | null;\n webkitBackgroundOrigin: string | null;\n webkitBackgroundSize: string | null;\n webkitBorderBottomLeftRadius: string | null;\n webkitBorderBottomRightRadius: string | null;\n webkitBorderImage: string | null;\n webkitBorderRadius: string | null;\n webkitBorderTopLeftRadius: string | null;\n webkitBorderTopRightRadius: string | null;\n webkitBoxAlign: string | null;\n webkitBoxDirection: string | null;\n webkitBoxFlex: string | null;\n webkitBoxOrdinalGroup: string | null;\n webkitBoxOrient: string | null;\n webkitBoxPack: string | null;\n webkitBoxSizing: string | null;\n webkitColumnBreakAfter: string | null;\n webkitColumnBreakBefore: string | null;\n webkitColumnBreakInside: string | null;\n webkitColumnCount: any;\n webkitColumnGap: any;\n webkitColumnRule: string | null;\n webkitColumnRuleColor: any;\n webkitColumnRuleStyle: string | null;\n webkitColumnRuleWidth: any;\n webkitColumnSpan: string | null;\n webkitColumnWidth: any;\n webkitColumns: string | null;\n webkitFilter: string | null;\n webkitFlex: string | null;\n webkitFlexBasis: string | null;\n webkitFlexDirection: string | null;\n webkitFlexFlow: string | null;\n webkitFlexGrow: string | null;\n webkitFlexShrink: string | null;\n webkitFlexWrap: string | null;\n webkitJustifyContent: string | null;\n webkitOrder: string | null;\n webkitPerspective: string | null;\n webkitPerspectiveOrigin: string | null;\n webkitTapHighlightColor: string | null;\n webkitTextFillColor: string | null;\n webkitTextSizeAdjust: any;\n webkitTextStroke: string | null;\n webkitTextStrokeColor: string | null;\n webkitTextStrokeWidth: string | null;\n webkitTransform: string | null;\n webkitTransformOrigin: string | null;\n webkitTransformStyle: string | null;\n webkitTransition: string | null;\n webkitTransitionDelay: string | null;\n webkitTransitionDuration: string | null;\n webkitTransitionProperty: string | null;\n webkitTransitionTimingFunction: string | null;\n webkitUserModify: string | null;\n webkitUserSelect: string | null;\n webkitWritingMode: string | null;\n whiteSpace: string | null;\n widows: string | null;\n width: string | null;\n wordBreak: string | null;\n wordSpacing: string | null;\n wordWrap: string | null;\n writingMode: string | null;\n zIndex: string | null;\n zoom: string | null;\n getPropertyPriority(propertyName: string): string;\n getPropertyValue(propertyName: string): string;\n item(index: number): string;\n removeProperty(propertyName: string): string;\n setProperty(propertyName: string, value: string | null, priority?: string | null): void;\n [index: number]: string;\n}\n\ndeclare var CSSStyleDeclaration: {\n prototype: CSSStyleDeclaration;\n new(): CSSStyleDeclaration;\n};\n\ninterface CSSStyleRule extends CSSRule {\n selectorText: string;\n readonly style: CSSStyleDeclaration;\n}\n\ndeclare var CSSStyleRule: {\n prototype: CSSStyleRule;\n new(): CSSStyleRule;\n};\n\ninterface CSSStyleSheet extends StyleSheet {\n readonly cssRules: CSSRuleList;\n /** @deprecated */\n cssText: string;\n /** @deprecated */\n readonly id: string;\n /** @deprecated */\n readonly imports: StyleSheetList;\n /** @deprecated */\n readonly isAlternate: boolean;\n /** @deprecated */\n readonly isPrefAlternate: boolean;\n readonly ownerRule: CSSRule | null;\n /** @deprecated */\n readonly owningElement: Element;\n /** @deprecated */\n readonly pages: any;\n /** @deprecated */\n readonly readOnly: boolean;\n readonly rules: CSSRuleList;\n /** @deprecated */\n addImport(bstrURL: string, lIndex?: number): number;\n /** @deprecated */\n addPageRule(bstrSelector: string, bstrStyle: string, lIndex?: number): number;\n addRule(bstrSelector: string, bstrStyle?: string, lIndex?: number): number;\n deleteRule(index?: number): void;\n insertRule(rule: string, index?: number): number;\n /** @deprecated */\n removeImport(lIndex: number): void;\n removeRule(lIndex: number): void;\n}\n\ndeclare var CSSStyleSheet: {\n prototype: CSSStyleSheet;\n new(): CSSStyleSheet;\n};\n\ninterface CSSSupportsRule extends CSSConditionRule {\n}\n\ndeclare var CSSSupportsRule: {\n prototype: CSSSupportsRule;\n new(): CSSSupportsRule;\n};\n\ninterface Cache {\n add(request: RequestInfo): Promise;\n addAll(requests: RequestInfo[]): Promise;\n delete(request: RequestInfo, options?: CacheQueryOptions): Promise;\n keys(request?: RequestInfo, options?: CacheQueryOptions): Promise>;\n match(request: RequestInfo, options?: CacheQueryOptions): Promise;\n matchAll(request?: RequestInfo, options?: CacheQueryOptions): Promise>;\n put(request: RequestInfo, response: Response): Promise;\n}\n\ndeclare var Cache: {\n prototype: Cache;\n new(): Cache;\n};\n\ninterface CacheStorage {\n delete(cacheName: string): Promise;\n has(cacheName: string): Promise;\n keys(): Promise;\n match(request: RequestInfo, options?: CacheQueryOptions): Promise;\n open(cacheName: string): Promise;\n}\n\ndeclare var CacheStorage: {\n prototype: CacheStorage;\n new(): CacheStorage;\n};\n\ninterface Canvas2DContextAttributes {\n alpha?: boolean;\n storage?: boolean;\n willReadFrequently?: boolean;\n [attribute: string]: boolean | string | undefined;\n}\n\ninterface CanvasGradient {\n addColorStop(offset: number, color: string): void;\n}\n\ndeclare var CanvasGradient: {\n prototype: CanvasGradient;\n new(): CanvasGradient;\n};\n\ninterface CanvasPathMethods {\n arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void;\n arcTo(x1: number, y1: number, x2: number, y2: number, radiusX: number, radiusY: number, rotation: number): void;\n bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void;\n closePath(): void;\n ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void;\n lineTo(x: number, y: number): void;\n moveTo(x: number, y: number): void;\n quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;\n rect(x: number, y: number, w: number, h: number): void;\n}\n\ninterface CanvasPattern {\n setTransform(matrix: SVGMatrix): void;\n}\n\ndeclare var CanvasPattern: {\n prototype: CanvasPattern;\n new(): CanvasPattern;\n};\n\ninterface CanvasRenderingContext2D extends CanvasPathMethods {\n readonly canvas: HTMLCanvasElement;\n fillStyle: string | CanvasGradient | CanvasPattern;\n font: string;\n globalAlpha: number;\n globalCompositeOperation: string;\n imageSmoothingEnabled: boolean;\n lineCap: string;\n lineDashOffset: number;\n lineJoin: string;\n lineWidth: number;\n miterLimit: number;\n mozImageSmoothingEnabled: boolean;\n msFillRule: CanvasFillRule;\n oImageSmoothingEnabled: boolean;\n shadowBlur: number;\n shadowColor: string;\n shadowOffsetX: number;\n shadowOffsetY: number;\n strokeStyle: string | CanvasGradient | CanvasPattern;\n textAlign: string;\n textBaseline: string;\n webkitImageSmoothingEnabled: boolean;\n beginPath(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n clip(fillRule?: CanvasFillRule): void;\n clip(path: Path2D, fillRule?: CanvasFillRule): void;\n createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;\n createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;\n createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;\n createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;\n drawFocusIfNeeded(element: Element): void;\n drawFocusIfNeeded(path: Path2D, element: Element): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void;\n drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void;\n fill(fillRule?: CanvasFillRule): void;\n fill(path: Path2D, fillRule?: CanvasFillRule): void;\n fillRect(x: number, y: number, w: number, h: number): void;\n fillText(text: string, x: number, y: number, maxWidth?: number): void;\n getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;\n getLineDash(): number[];\n isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInPath(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(x: number, y: number, fillRule?: CanvasFillRule): boolean;\n isPointInStroke(path: Path2D, x: number, y: number, fillRule?: CanvasFillRule): boolean;\n measureText(text: string): TextMetrics;\n putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void;\n restore(): void;\n rotate(angle: number): void;\n save(): void;\n scale(x: number, y: number): void;\n setLineDash(segments: number[]): void;\n setTransform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n stroke(path?: Path2D): void;\n strokeRect(x: number, y: number, w: number, h: number): void;\n strokeText(text: string, x: number, y: number, maxWidth?: number): void;\n transform(m11: number, m12: number, m21: number, m22: number, dx: number, dy: number): void;\n translate(x: number, y: number): void;\n}\n\ndeclare var CanvasRenderingContext2D: {\n prototype: CanvasRenderingContext2D;\n new(): CanvasRenderingContext2D;\n};\n\ninterface ChannelMergerNode extends AudioNode {\n}\n\ndeclare var ChannelMergerNode: {\n prototype: ChannelMergerNode;\n new(context: BaseAudioContext, options?: ChannelMergerOptions): ChannelMergerNode;\n};\n\ninterface ChannelSplitterNode extends AudioNode {\n}\n\ndeclare var ChannelSplitterNode: {\n prototype: ChannelSplitterNode;\n new(context: BaseAudioContext, options?: ChannelSplitterOptions): ChannelSplitterNode;\n};\n\ninterface CharacterData extends Node, ChildNode {\n data: string;\n readonly length: number;\n appendData(arg: string): void;\n deleteData(offset: number, count: number): void;\n insertData(offset: number, arg: string): void;\n replaceData(offset: number, count: number, arg: string): void;\n substringData(offset: number, count: number): string;\n}\n\ndeclare var CharacterData: {\n prototype: CharacterData;\n new(): CharacterData;\n};\n\ninterface ChildNode {\n remove(): void;\n}\n\ninterface ClientRect {\n bottom: number;\n readonly height: number;\n left: number;\n right: number;\n top: number;\n readonly width: number;\n}\n\ndeclare var ClientRect: {\n prototype: ClientRect;\n new(): ClientRect;\n};\n\ninterface ClientRectList {\n readonly length: number;\n item(index: number): ClientRect;\n [index: number]: ClientRect;\n}\n\ndeclare var ClientRectList: {\n prototype: ClientRectList;\n new(): ClientRectList;\n};\n\ninterface ClipboardEvent extends Event {\n readonly clipboardData: DataTransfer;\n}\n\ndeclare var ClipboardEvent: {\n prototype: ClipboardEvent;\n new(type: string, eventInitDict?: ClipboardEventInit): ClipboardEvent;\n};\n\ninterface ClipboardEventInit extends EventInit {\n data?: string;\n dataType?: string;\n}\n\ninterface CloseEvent extends Event {\n readonly code: number;\n readonly reason: string;\n readonly wasClean: boolean;\n /** @deprecated */\n initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;\n}\n\ndeclare var CloseEvent: {\n prototype: CloseEvent;\n new(type: string, eventInitDict?: CloseEventInit): CloseEvent;\n};\n\ninterface Comment extends CharacterData {\n text: string;\n}\n\ndeclare var Comment: {\n prototype: Comment;\n new(data?: string): Comment;\n};\n\ninterface CompositionEvent extends UIEvent {\n readonly data: string;\n readonly locale: string;\n initCompositionEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, locale: string): void;\n}\n\ndeclare var CompositionEvent: {\n prototype: CompositionEvent;\n new(typeArg: string, eventInitDict?: CompositionEventInit): CompositionEvent;\n};\n\ninterface ConcatParams extends Algorithm {\n algorithmId: Uint8Array;\n hash?: string | Algorithm;\n partyUInfo: Uint8Array;\n partyVInfo: Uint8Array;\n privateInfo?: Uint8Array;\n publicInfo?: Uint8Array;\n}\n\ninterface Console {\n memory: any;\n assert(condition?: boolean, message?: string, ...data: any[]): void;\n clear(): void;\n count(label?: string): void;\n debug(message?: any, ...optionalParams: any[]): void;\n dir(value?: any, ...optionalParams: any[]): void;\n dirxml(value: any): void;\n error(message?: any, ...optionalParams: any[]): void;\n exception(message?: string, ...optionalParams: any[]): void;\n group(groupTitle?: string, ...optionalParams: any[]): void;\n groupCollapsed(groupTitle?: string, ...optionalParams: any[]): void;\n groupEnd(): void;\n info(message?: any, ...optionalParams: any[]): void;\n log(message?: any, ...optionalParams: any[]): void;\n markTimeline(label?: string): void;\n msIsIndependentlyComposed(element: Element): boolean;\n profile(reportName?: string): void;\n profileEnd(): void;\n select(element: Element): void;\n table(...tabularData: any[]): void;\n time(label?: string): void;\n timeEnd(label?: string): void;\n timeStamp(label?: string): void;\n timeline(label?: string): void;\n timelineEnd(label?: string): void;\n trace(message?: any, ...optionalParams: any[]): void;\n warn(message?: any, ...optionalParams: any[]): void;\n}\n\ndeclare var Console: {\n prototype: Console;\n new(): Console;\n};\n\ninterface ConstantSourceNode extends AudioScheduledSourceNode {\n readonly offset: AudioParam;\n addEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ConstantSourceNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ConstantSourceNode: {\n prototype: ConstantSourceNode;\n new(context: BaseAudioContext, options?: ConstantSourceOptions): ConstantSourceNode;\n};\n\ninterface ConvolverNode extends AudioNode {\n buffer: AudioBuffer | null;\n normalize: boolean;\n}\n\ndeclare var ConvolverNode: {\n prototype: ConvolverNode;\n new(context: BaseAudioContext, options?: ConvolverOptions): ConvolverNode;\n};\n\ninterface Coordinates {\n readonly accuracy: number;\n readonly altitude: number | null;\n readonly altitudeAccuracy: number | null;\n readonly heading: number | null;\n readonly latitude: number;\n readonly longitude: number;\n readonly speed: number | null;\n}\n\ninterface CountQueuingStrategy {\n highWaterMark: number;\n size(): number;\n}\n\ndeclare var CountQueuingStrategy: {\n prototype: CountQueuingStrategy;\n new(strategy: QueuingStrategy): CountQueuingStrategy;\n};\n\ninterface Crypto {\n readonly subtle: SubtleCrypto;\n getRandomValues(array: T): T;\n}\n\ndeclare var Crypto: {\n prototype: Crypto;\n new(): Crypto;\n};\n\ninterface CryptoKey {\n readonly algorithm: KeyAlgorithm;\n readonly extractable: boolean;\n readonly type: string;\n readonly usages: string[];\n}\n\ndeclare var CryptoKey: {\n prototype: CryptoKey;\n new(): CryptoKey;\n};\n\ninterface CryptoKeyPair {\n privateKey: CryptoKey;\n publicKey: CryptoKey;\n}\n\ndeclare var CryptoKeyPair: {\n prototype: CryptoKeyPair;\n new(): CryptoKeyPair;\n};\n\ninterface CustomElementRegistry {\n define(name: string, constructor: Function, options?: ElementDefinitionOptions): void;\n get(name: string): any;\n whenDefined(name: string): PromiseLike;\n}\n\ninterface CustomEvent extends Event {\n readonly detail: T;\n initCustomEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, detailArg: T): void;\n}\n\ndeclare var CustomEvent: {\n prototype: CustomEvent;\n new(typeArg: string, eventInitDict?: CustomEventInit): CustomEvent;\n};\n\ninterface DOMError {\n readonly name: string;\n toString(): string;\n}\n\ndeclare var DOMError: {\n prototype: DOMError;\n new(): DOMError;\n};\n\ninterface DOMException {\n readonly code: number;\n readonly message: string;\n readonly name: string;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n}\n\ndeclare var DOMException: {\n prototype: DOMException;\n new(message?: string, name?: string): DOMException;\n readonly ABORT_ERR: number;\n readonly DATA_CLONE_ERR: number;\n readonly DOMSTRING_SIZE_ERR: number;\n readonly HIERARCHY_REQUEST_ERR: number;\n readonly INDEX_SIZE_ERR: number;\n readonly INUSE_ATTRIBUTE_ERR: number;\n readonly INVALID_ACCESS_ERR: number;\n readonly INVALID_CHARACTER_ERR: number;\n readonly INVALID_MODIFICATION_ERR: number;\n readonly INVALID_NODE_TYPE_ERR: number;\n readonly INVALID_STATE_ERR: number;\n readonly NAMESPACE_ERR: number;\n readonly NETWORK_ERR: number;\n readonly NOT_FOUND_ERR: number;\n readonly NOT_SUPPORTED_ERR: number;\n readonly NO_DATA_ALLOWED_ERR: number;\n readonly NO_MODIFICATION_ALLOWED_ERR: number;\n readonly QUOTA_EXCEEDED_ERR: number;\n readonly SECURITY_ERR: number;\n readonly SYNTAX_ERR: number;\n readonly TIMEOUT_ERR: number;\n readonly TYPE_MISMATCH_ERR: number;\n readonly URL_MISMATCH_ERR: number;\n readonly VALIDATION_ERR: number;\n readonly WRONG_DOCUMENT_ERR: number;\n};\n\ninterface DOMImplementation {\n createDocument(namespaceURI: string | null, qualifiedName: string | null, doctype: DocumentType | null): Document;\n createDocumentType(qualifiedName: string, publicId: string, systemId: string): DocumentType;\n createHTMLDocument(title?: string): Document;\n hasFeature(feature: string | null, version: string | null): boolean;\n}\n\ndeclare var DOMImplementation: {\n prototype: DOMImplementation;\n new(): DOMImplementation;\n};\n\ninterface DOML2DeprecatedColorProperty {\n color: string;\n}\n\ninterface DOML2DeprecatedSizeProperty {\n size: number;\n}\n\ninterface DOMMatrix extends DOMMatrixReadOnly {\n a: number;\n b: number;\n c: number;\n d: number;\n e: number;\n f: number;\n m11: number;\n m12: number;\n m13: number;\n m14: number;\n m21: number;\n m22: number;\n m23: number;\n m24: number;\n m31: number;\n m32: number;\n m33: number;\n m34: number;\n m41: number;\n m42: number;\n m43: number;\n m44: number;\n invertSelf(): DOMMatrix;\n multiplySelf(other?: DOMMatrixInit): DOMMatrix;\n preMultiplySelf(other?: DOMMatrixInit): DOMMatrix;\n rotateAxisAngleSelf(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\n rotateFromVectorSelf(x?: number, y?: number): DOMMatrix;\n rotateSelf(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\n scale3dSelf(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n scaleSelf(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n setMatrixValue(transformList: string): DOMMatrix;\n skewXSelf(sx?: number): DOMMatrix;\n skewYSelf(sy?: number): DOMMatrix;\n translateSelf(tx?: number, ty?: number, tz?: number): DOMMatrix;\n}\n\ndeclare var DOMMatrix: {\n prototype: DOMMatrix;\n new(init?: string | number[]): DOMMatrix;\n fromFloat32Array(array32: Float32Array): DOMMatrix;\n fromFloat64Array(array64: Float64Array): DOMMatrix;\n fromMatrix(other?: DOMMatrixInit): DOMMatrix;\n};\n\ntype SVGMatrix = DOMMatrix;\ndeclare var SVGMatrix: typeof DOMMatrix;\n\ntype WebKitCSSMatrix = DOMMatrix;\ndeclare var WebKitCSSMatrix: typeof DOMMatrix;\n\ninterface DOMMatrixReadOnly {\n readonly a: number;\n readonly b: number;\n readonly c: number;\n readonly d: number;\n readonly e: number;\n readonly f: number;\n readonly is2D: boolean;\n readonly isIdentity: boolean;\n readonly m11: number;\n readonly m12: number;\n readonly m13: number;\n readonly m14: number;\n readonly m21: number;\n readonly m22: number;\n readonly m23: number;\n readonly m24: number;\n readonly m31: number;\n readonly m32: number;\n readonly m33: number;\n readonly m34: number;\n readonly m41: number;\n readonly m42: number;\n readonly m43: number;\n readonly m44: number;\n flipX(): DOMMatrix;\n flipY(): DOMMatrix;\n inverse(): DOMMatrix;\n multiply(other?: DOMMatrixInit): DOMMatrix;\n rotate(rotX?: number, rotY?: number, rotZ?: number): DOMMatrix;\n rotateAxisAngle(x?: number, y?: number, z?: number, angle?: number): DOMMatrix;\n rotateFromVector(x?: number, y?: number): DOMMatrix;\n scale(scaleX?: number, scaleY?: number, scaleZ?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n scale3d(scale?: number, originX?: number, originY?: number, originZ?: number): DOMMatrix;\n skewX(sx?: number): DOMMatrix;\n skewY(sy?: number): DOMMatrix;\n toFloat32Array(): Float32Array;\n toFloat64Array(): Float64Array;\n toJSON(): any;\n transformPoint(point?: DOMPointInit): DOMPoint;\n translate(tx?: number, ty?: number, tz?: number): DOMMatrix;\n}\n\ndeclare var DOMMatrixReadOnly: {\n prototype: DOMMatrixReadOnly;\n new(init?: string | number[]): DOMMatrixReadOnly;\n fromFloat32Array(array32: Float32Array): DOMMatrixReadOnly;\n fromFloat64Array(array64: Float64Array): DOMMatrixReadOnly;\n fromMatrix(other?: DOMMatrixInit): DOMMatrixReadOnly;\n};\n\ninterface DOMParser {\n parseFromString(source: string, mimeType: string): Document;\n}\n\ndeclare var DOMParser: {\n prototype: DOMParser;\n new(): DOMParser;\n};\n\ninterface DOMPoint extends DOMPointReadOnly {\n w: number;\n x: number;\n y: number;\n z: number;\n}\n\ndeclare var DOMPoint: {\n prototype: DOMPoint;\n new(x?: number, y?: number, z?: number, w?: number): DOMPoint;\n fromPoint(other?: DOMPointInit): DOMPoint;\n};\n\ntype SVGPoint = DOMPoint;\ndeclare var SVGPoint: typeof DOMPoint;\n\ninterface DOMPointReadOnly {\n readonly w: number;\n readonly x: number;\n readonly y: number;\n readonly z: number;\n matrixTransform(matrix?: DOMMatrixInit): DOMPoint;\n toJSON(): any;\n}\n\ndeclare var DOMPointReadOnly: {\n prototype: DOMPointReadOnly;\n new(x?: number, y?: number, z?: number, w?: number): DOMPointReadOnly;\n fromPoint(other?: DOMPointInit): DOMPointReadOnly;\n};\n\ninterface DOMQuad {\n readonly p1: DOMPoint;\n readonly p2: DOMPoint;\n readonly p3: DOMPoint;\n readonly p4: DOMPoint;\n getBounds(): DOMRect;\n toJSON(): any;\n}\n\ndeclare var DOMQuad: {\n prototype: DOMQuad;\n new(p1?: DOMPointInit, p2?: DOMPointInit, p3?: DOMPointInit, p4?: DOMPointInit): DOMQuad;\n fromQuad(other?: DOMQuadInit): DOMQuad;\n fromRect(other?: DOMRectInit): DOMQuad;\n};\n\ninterface DOMRect extends DOMRectReadOnly {\n height: number;\n width: number;\n x: number;\n y: number;\n}\n\ndeclare var DOMRect: {\n prototype: DOMRect;\n new(x?: number, y?: number, width?: number, height?: number): DOMRect;\n fromRect(other?: DOMRectInit): DOMRect;\n};\n\ntype SVGRect = DOMRect;\ndeclare var SVGRect: typeof DOMRect;\n\ninterface DOMRectList {\n readonly length: number;\n item(index: number): DOMRect | null;\n [index: number]: DOMRect;\n}\n\ndeclare var DOMRectList: {\n prototype: DOMRectList;\n new(): DOMRectList;\n};\n\ninterface DOMRectReadOnly {\n readonly bottom: number;\n readonly height: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n toJSON(): any;\n}\n\ndeclare var DOMRectReadOnly: {\n prototype: DOMRectReadOnly;\n new(x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly;\n fromRect(other?: DOMRectInit): DOMRectReadOnly;\n};\n\ninterface DOMSettableTokenList extends DOMTokenList {\n value: string;\n}\n\ndeclare var DOMSettableTokenList: {\n prototype: DOMSettableTokenList;\n new(): DOMSettableTokenList;\n};\n\ninterface DOMStringList {\n /**\n * Returns the number of strings in strings.\n */\n readonly length: number;\n /**\n * Returns true if strings contains string, and false\n * otherwise.\n */\n contains(string: string): boolean;\n /**\n * Returns the string with index index from strings.\n */\n item(index: number): string | null;\n [index: number]: string;\n}\n\ndeclare var DOMStringList: {\n prototype: DOMStringList;\n new(): DOMStringList;\n};\n\ninterface DOMStringMap {\n [name: string]: string | undefined;\n}\n\ndeclare var DOMStringMap: {\n prototype: DOMStringMap;\n new(): DOMStringMap;\n};\n\ninterface DOMTokenList {\n readonly length: number;\n add(...tokens: string[]): void;\n contains(token: string): boolean;\n item(index: number): string | null;\n remove(...tokens: string[]): void;\n replace(oldToken: string, newToken: string): void;\n toString(): string;\n toggle(token: string, force?: boolean): boolean;\n [index: number]: string;\n}\n\ndeclare var DOMTokenList: {\n prototype: DOMTokenList;\n new(): DOMTokenList;\n};\n\ninterface DataCue extends TextTrackCue {\n data: ArrayBuffer;\n addEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: DataCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var DataCue: {\n prototype: DataCue;\n new(): DataCue;\n};\n\ninterface DataTransfer {\n dropEffect: string;\n effectAllowed: string;\n readonly files: FileList;\n readonly items: DataTransferItemList;\n readonly types: string[];\n clearData(format?: string): boolean;\n getData(format: string): string;\n setData(format: string, data: string): boolean;\n setDragImage(image: Element, x: number, y: number): void;\n}\n\ndeclare var DataTransfer: {\n prototype: DataTransfer;\n new(): DataTransfer;\n};\n\ninterface DataTransferItem {\n readonly kind: string;\n readonly type: string;\n getAsFile(): File | null;\n getAsString(_callback: FunctionStringCallback | null): void;\n webkitGetAsEntry(): any;\n}\n\ndeclare var DataTransferItem: {\n prototype: DataTransferItem;\n new(): DataTransferItem;\n};\n\ninterface DataTransferItemList {\n readonly length: number;\n add(data: File): DataTransferItem | null;\n add(data: string, type: string): DataTransferItem | null;\n clear(): void;\n item(index: number): DataTransferItem;\n remove(index: number): void;\n [name: number]: DataTransferItem;\n}\n\ndeclare var DataTransferItemList: {\n prototype: DataTransferItemList;\n new(): DataTransferItemList;\n};\n\ninterface DeferredPermissionRequest {\n readonly id: number;\n readonly type: MSWebViewPermissionType;\n readonly uri: string;\n allow(): void;\n deny(): void;\n}\n\ndeclare var DeferredPermissionRequest: {\n prototype: DeferredPermissionRequest;\n new(): DeferredPermissionRequest;\n};\n\ninterface DelayNode extends AudioNode {\n readonly delayTime: AudioParam;\n}\n\ndeclare var DelayNode: {\n prototype: DelayNode;\n new(context: BaseAudioContext, options?: DelayOptions): DelayNode;\n};\n\ninterface DeviceAcceleration {\n readonly x: number | null;\n readonly y: number | null;\n readonly z: number | null;\n}\n\ndeclare var DeviceAcceleration: {\n prototype: DeviceAcceleration;\n new(): DeviceAcceleration;\n};\n\ninterface DeviceLightEvent extends Event {\n readonly value: number;\n}\n\ndeclare var DeviceLightEvent: {\n prototype: DeviceLightEvent;\n new(typeArg: string, eventInitDict?: DeviceLightEventInit): DeviceLightEvent;\n};\n\ninterface DeviceMotionEvent extends Event {\n readonly acceleration: DeviceAcceleration | null;\n readonly accelerationIncludingGravity: DeviceAcceleration | null;\n readonly interval: number | null;\n readonly rotationRate: DeviceRotationRate | null;\n initDeviceMotionEvent(type: string, bubbles: boolean, cancelable: boolean, acceleration: DeviceAccelerationDict | null, accelerationIncludingGravity: DeviceAccelerationDict | null, rotationRate: DeviceRotationRateDict | null, interval: number | null): void;\n}\n\ndeclare var DeviceMotionEvent: {\n prototype: DeviceMotionEvent;\n new(typeArg: string, eventInitDict?: DeviceMotionEventInit): DeviceMotionEvent;\n};\n\ninterface DeviceOrientationEvent extends Event {\n readonly absolute: boolean;\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n initDeviceOrientationEvent(type: string, bubbles: boolean, cancelable: boolean, alpha: number | null, beta: number | null, gamma: number | null, absolute: boolean): void;\n}\n\ndeclare var DeviceOrientationEvent: {\n prototype: DeviceOrientationEvent;\n new(typeArg: string, eventInitDict?: DeviceOrientationEventInit): DeviceOrientationEvent;\n};\n\ninterface DeviceRotationRate {\n readonly alpha: number | null;\n readonly beta: number | null;\n readonly gamma: number | null;\n}\n\ndeclare var DeviceRotationRate: {\n prototype: DeviceRotationRate;\n new(): DeviceRotationRate;\n};\n\ninterface DhImportKeyParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyAlgorithm extends KeyAlgorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DhKeyDeriveParams extends Algorithm {\n public: CryptoKey;\n}\n\ninterface DhKeyGenParams extends Algorithm {\n generator: Uint8Array;\n prime: Uint8Array;\n}\n\ninterface DocumentEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforedeactivate\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"fullscreenchange\": Event;\n \"fullscreenerror\": Event;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSManipulationStateChanged\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"mssitemodejumplistitemremoved\": Event;\n \"msthumbnailclick\": Event;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"pointerlockchange\": Event;\n \"pointerlockerror\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectionchange\": Event;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"stop\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"volumechange\": Event;\n \"waiting\": Event;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Document extends Node, GlobalEventHandlers, ParentNode, DocumentEvent {\n /**\n * Sets or gets the URL for the current document.\n */\n readonly URL: string;\n /**\n * Gets the URL for the document, stripped of any character encoding.\n */\n readonly URLUnencoded: string;\n /**\n * Gets the object that has the focus when the parent document has focus.\n */\n readonly activeElement: Element;\n /**\n * Sets or gets the color of all active links in the document.\n */\n /** @deprecated */\n alinkColor: string;\n /**\n * Returns a reference to the collection of elements contained by the object.\n */\n /** @deprecated */\n readonly all: HTMLAllCollection;\n /**\n * Retrieves a collection of all a objects that have a name and/or id property. Objects in this collection are in HTML source order.\n */\n /** @deprecated */\n readonly anchors: HTMLCollectionOf;\n /**\n * Retrieves a collection of all applet objects in the document.\n */\n /** @deprecated */\n readonly applets: HTMLCollectionOf;\n /**\n * Deprecated. Sets or retrieves a value that indicates the background color behind the object.\n */\n /** @deprecated */\n bgColor: string;\n /**\n * Specifies the beginning and end of the document body.\n */\n body: HTMLElement;\n readonly characterSet: string;\n /**\n * Gets or sets the character set used to encode the object.\n */\n charset: string;\n /**\n * Gets a value that indicates whether standards-compliant mode is switched on for the object.\n */\n readonly compatMode: string;\n cookie: string;\n readonly currentScript: HTMLScriptElement | SVGScriptElement | null;\n readonly defaultView: Window;\n /**\n * Sets or gets a value that indicates whether the document can be edited.\n */\n designMode: string;\n /**\n * Sets or retrieves a value that indicates the reading order of the object.\n */\n dir: string;\n /**\n * Gets an object representing the document type declaration associated with the current document.\n */\n readonly doctype: DocumentType;\n /**\n * Gets a reference to the root node of the document.\n */\n readonly documentElement: HTMLElement;\n /**\n * Sets or gets the security domain of the document.\n */\n domain: string;\n /**\n * Retrieves a collection of all embed objects in the document.\n */\n readonly embeds: HTMLCollectionOf;\n /**\n * Sets or gets the foreground (text) color of the document.\n */\n /** @deprecated */\n fgColor: string;\n /**\n * Retrieves a collection, in source order, of all form objects in the document.\n */\n readonly forms: HTMLCollectionOf;\n readonly fullscreenElement: Element | null;\n readonly fullscreenEnabled: boolean;\n readonly head: HTMLHeadElement;\n readonly hidden: boolean;\n /**\n * Retrieves a collection, in source order, of img objects in the document.\n */\n readonly images: HTMLCollectionOf;\n /**\n * Gets the implementation object of the current document.\n */\n readonly implementation: DOMImplementation;\n /**\n * Returns the character encoding used to create the webpage that is loaded into the document object.\n */\n readonly inputEncoding: string | null;\n /**\n * Gets the date that the page was last modified, if the page supplies one.\n */\n readonly lastModified: string;\n /**\n * Sets or gets the color of the document links.\n */\n /** @deprecated */\n linkColor: string;\n /**\n * Retrieves a collection of all a objects that specify the href property and all area objects in the document.\n */\n readonly links: HTMLCollectionOf;\n /**\n * Contains information about the current URL.\n */\n location: Location;\n msCSSOMElementFloatMetrics: boolean;\n msCapsLockWarningOff: boolean;\n /**\n * Fires when the user aborts the download.\n * @param ev The event.\n */\n onabort: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the object is set as the active element.\n * @param ev The event.\n */\n onactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the object is set as the active element.\n * @param ev The event.\n */\n onbeforeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires immediately before the activeElement is changed from the current object to another object in the parent document.\n * @param ev The event.\n */\n onbeforedeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the object loses the input focus.\n * @param ev The focus event.\n */\n onblur: ((this: Document, ev: FocusEvent) => any) | null;\n /**\n * Occurs when playback is possible, but would require further buffering.\n * @param ev The event.\n */\n oncanplay: ((this: Document, ev: Event) => any) | null;\n oncanplaythrough: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the contents of the object or selection have changed.\n * @param ev The event.\n */\n onchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the left mouse button on the object\n * @param ev The mouse event.\n */\n onclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user clicks the right mouse button in the client area, opening the context menu.\n * @param ev The mouse event.\n */\n oncontextmenu: ((this: Document, ev: PointerEvent) => any) | null;\n /**\n * Fires when the user double-clicks the object.\n * @param ev The mouse event.\n */\n ondblclick: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the activeElement is changed from the current object to another object in the parent document.\n * @param ev The UI Event\n */\n ondeactivate: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires on the source object continuously during a drag operation.\n * @param ev The event.\n */\n ondrag: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user releases the mouse at the close of a drag operation.\n * @param ev The event.\n */\n ondragend: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element when the user drags the object to a valid drop target.\n * @param ev The drag event.\n */\n ondragenter: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation.\n * @param ev The drag event.\n */\n ondragleave: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the target element continuously while the user drags the object over a valid drop target.\n * @param ev The event.\n */\n ondragover: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Fires on the source object when the user starts to drag a text selection or selected object.\n * @param ev The event.\n */\n ondragstart: ((this: Document, ev: DragEvent) => any) | null;\n ondrop: ((this: Document, ev: DragEvent) => any) | null;\n /**\n * Occurs when the duration attribute is updated.\n * @param ev The event.\n */\n ondurationchange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the media element is reset to its initial state.\n * @param ev The event.\n */\n onemptied: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the end of playback is reached.\n * @param ev The event\n */\n onended: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when an error occurs during object loading.\n * @param ev The event.\n */\n onerror: ((this: Document, ev: ErrorEvent) => any) | null;\n /**\n * Fires when the object receives focus.\n * @param ev The event.\n */\n onfocus: ((this: Document, ev: FocusEvent) => any) | null;\n onfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onfullscreenerror: ((this: Document, ev: Event) => any) | null;\n oninput: ((this: Document, ev: Event) => any) | null;\n oninvalid: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user presses a key.\n * @param ev The keyboard event\n */\n onkeydown: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user presses an alphanumeric key.\n * @param ev The event.\n */\n onkeypress: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires when the user releases a key.\n * @param ev The keyboard event\n */\n onkeyup: ((this: Document, ev: KeyboardEvent) => any) | null;\n /**\n * Fires immediately after the browser loads the object.\n * @param ev The event.\n */\n onload: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when media data is loaded at the current playback position.\n * @param ev The event.\n */\n onloadeddata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the duration and dimensions of the media have been determined.\n * @param ev The event.\n */\n onloadedmetadata: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when Internet Explorer begins looking for media data.\n * @param ev The event.\n */\n onloadstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the object with either mouse button.\n * @param ev The mouse event.\n */\n onmousedown: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse over the object.\n * @param ev The mouse event.\n */\n onmousemove: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer outside the boundaries of the object.\n * @param ev The mouse event.\n */\n onmouseout: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user moves the mouse pointer into the object.\n * @param ev The mouse event.\n */\n onmouseover: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the user releases a mouse button while the mouse is over the object.\n * @param ev The mouse event.\n */\n onmouseup: ((this: Document, ev: MouseEvent) => any) | null;\n /**\n * Fires when the wheel button is rotated.\n * @param ev The mouse event\n */\n onmousewheel: ((this: Document, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: Document, ev: Event) => any) | null;\n onmsgesturechange: ((this: Document, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Document, ev: Event) => any) | null;\n onmsgestureend: ((this: Document, ev: Event) => any) | null;\n onmsgesturehold: ((this: Document, ev: Event) => any) | null;\n onmsgesturestart: ((this: Document, ev: Event) => any) | null;\n onmsgesturetap: ((this: Document, ev: Event) => any) | null;\n onmsinertiastart: ((this: Document, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: Document, ev: Event) => any) | null;\n onmspointercancel: ((this: Document, ev: Event) => any) | null;\n onmspointerdown: ((this: Document, ev: Event) => any) | null;\n onmspointerenter: ((this: Document, ev: Event) => any) | null;\n onmspointerleave: ((this: Document, ev: Event) => any) | null;\n onmspointermove: ((this: Document, ev: Event) => any) | null;\n onmspointerout: ((this: Document, ev: Event) => any) | null;\n onmspointerover: ((this: Document, ev: Event) => any) | null;\n onmspointerup: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when an item is removed from a Jump List of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmssitemodejumplistitemremoved: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when a user clicks a button in a Thumbnail Toolbar of a webpage running in Site Mode.\n * @param ev The event.\n */\n onmsthumbnailclick: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback is paused.\n * @param ev The event.\n */\n onpause: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the play method is requested.\n * @param ev The event.\n */\n onplay: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the audio or video has started playing.\n * @param ev The event.\n */\n onplaying: ((this: Document, ev: Event) => any) | null;\n onpointerlockchange: ((this: Document, ev: Event) => any) | null;\n onpointerlockerror: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate progress while downloading media data.\n * @param ev The event.\n */\n onprogress: ((this: Document, ev: ProgressEvent) => any) | null;\n /**\n * Occurs when the playback rate is increased or decreased.\n * @param ev The event.\n */\n onratechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the state of the object has changed.\n * @param ev The event\n */\n onreadystatechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user resets a form.\n * @param ev The event.\n */\n onreset: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user repositions the scroll box in the scroll bar on the object.\n * @param ev The event.\n */\n onscroll: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Occurs when the seek operation ends.\n * @param ev The event.\n */\n onseeked: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the current playback position is moved.\n * @param ev The event.\n */\n onseeking: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the current selection changes.\n * @param ev The event.\n */\n onselect: ((this: Document, ev: UIEvent) => any) | null;\n /**\n * Fires when the selection state of a document changes.\n * @param ev The event.\n */\n onselectionchange: ((this: Document, ev: Event) => any) | null;\n onselectstart: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when the download has stopped.\n * @param ev The event.\n */\n onstalled: ((this: Document, ev: Event) => any) | null;\n /**\n * Fires when the user clicks the Stop button or leaves the Web page.\n * @param ev The event.\n */\n onstop: ((this: Document, ev: Event) => any) | null;\n onsubmit: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs if the load operation has been intentionally halted.\n * @param ev The event.\n */\n onsuspend: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs to indicate the current playback position.\n * @param ev The event.\n */\n ontimeupdate: ((this: Document, ev: Event) => any) | null;\n onvisibilitychange: (this: Document, ev: Event) => any;\n /**\n * Occurs when the volume is changed, or playback is muted or unmuted.\n * @param ev The event.\n */\n onvolumechange: ((this: Document, ev: Event) => any) | null;\n /**\n * Occurs when playback stops because the next frame of a video resource is not available.\n * @param ev The event.\n */\n onwaiting: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Document, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Document, ev: Event) => any) | null;\n readonly plugins: HTMLCollectionOf;\n readonly pointerLockElement: Element;\n /**\n * Retrieves a value that indicates the current state of the object.\n */\n readonly readyState: DocumentReadyState;\n /**\n * Gets the URL of the location that referred the user to the current page.\n */\n readonly referrer: string;\n /**\n * Gets the root svg element in the document hierarchy.\n */\n readonly rootElement: SVGSVGElement;\n /**\n * Retrieves a collection of all script objects in the document.\n */\n readonly scripts: HTMLCollectionOf;\n readonly scrollingElement: Element | null;\n /**\n * Retrieves a collection of styleSheet objects representing the style sheets that correspond to each instance of a link or style object in the document.\n */\n readonly styleSheets: StyleSheetList;\n readonly timeline: DocumentTimeline;\n /**\n * Contains the title of the document.\n */\n title: string;\n readonly visibilityState: VisibilityState;\n /**\n * Sets or gets the color of the links that the user has visited.\n */\n /** @deprecated */\n vlinkColor: string;\n readonly webkitCurrentFullScreenElement: Element | null;\n readonly webkitFullscreenElement: Element | null;\n readonly webkitFullscreenEnabled: boolean;\n readonly webkitIsFullScreen: boolean;\n readonly xmlEncoding: string | null;\n xmlStandalone: boolean;\n /**\n * Gets or sets the version attribute specified in the declaration of an XML document.\n */\n xmlVersion: string | null;\n adoptNode(source: T): T;\n /** @deprecated */\n captureEvents(): void;\n caretRangeFromPoint(x: number, y: number): Range;\n /** @deprecated */\n clear(): void;\n /**\n * Closes an output stream and forces the sent data to display.\n */\n close(): void;\n /**\n * Creates an attribute object with a specified name.\n * @param name String that sets the attribute object's name.\n */\n createAttribute(name: string): Attr;\n createAttributeNS(namespaceURI: string | null, qualifiedName: string): Attr;\n createCDATASection(data: string): CDATASection;\n /**\n * Creates a comment object with the specified data.\n * @param data Sets the comment object's data.\n */\n createComment(data: string): Comment;\n /**\n * Creates a new document.\n */\n createDocumentFragment(): DocumentFragment;\n /**\n * Creates an instance of the element for the specified tag.\n * @param tagName The name of an element.\n */\n createElement(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];\n createElement(tagName: string, options?: ElementCreationOptions): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", qualifiedName: string): HTMLElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"a\"): SVGAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"circle\"): SVGCircleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"clipPath\"): SVGClipPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"componentTransferFunction\"): SVGComponentTransferFunctionElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"defs\"): SVGDefsElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"desc\"): SVGDescElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"ellipse\"): SVGEllipseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feBlend\"): SVGFEBlendElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feColorMatrix\"): SVGFEColorMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComponentTransfer\"): SVGFEComponentTransferElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feComposite\"): SVGFECompositeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feConvolveMatrix\"): SVGFEConvolveMatrixElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDiffuseLighting\"): SVGFEDiffuseLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDisplacementMap\"): SVGFEDisplacementMapElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feDistantLight\"): SVGFEDistantLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFlood\"): SVGFEFloodElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncA\"): SVGFEFuncAElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncB\"): SVGFEFuncBElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncG\"): SVGFEFuncGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feFuncR\"): SVGFEFuncRElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feGaussianBlur\"): SVGFEGaussianBlurElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feImage\"): SVGFEImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMerge\"): SVGFEMergeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMergeNode\"): SVGFEMergeNodeElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feMorphology\"): SVGFEMorphologyElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feOffset\"): SVGFEOffsetElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"fePointLight\"): SVGFEPointLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpecularLighting\"): SVGFESpecularLightingElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feSpotLight\"): SVGFESpotLightElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTile\"): SVGFETileElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"feTurbulence\"): SVGFETurbulenceElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"filter\"): SVGFilterElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"foreignObject\"): SVGForeignObjectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"g\"): SVGGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"image\"): SVGImageElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"gradient\"): SVGGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"line\"): SVGLineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"linearGradient\"): SVGLinearGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"marker\"): SVGMarkerElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"mask\"): SVGMaskElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"path\"): SVGPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"metadata\"): SVGMetadataElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"pattern\"): SVGPatternElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polygon\"): SVGPolygonElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"polyline\"): SVGPolylineElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"radialGradient\"): SVGRadialGradientElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"rect\"): SVGRectElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"svg\"): SVGSVGElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"script\"): SVGScriptElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"stop\"): SVGStopElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"style\"): SVGStyleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"switch\"): SVGSwitchElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"symbol\"): SVGSymbolElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"tspan\"): SVGTSpanElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textContent\"): SVGTextContentElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"text\"): SVGTextElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPath\"): SVGTextPathElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"textPositioning\"): SVGTextPositioningElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"title\"): SVGTitleElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"use\"): SVGUseElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: \"view\"): SVGViewElement;\n createElementNS(namespaceURI: \"http://www.w3.org/2000/svg\", qualifiedName: string): SVGElement;\n createElementNS(namespaceURI: string | null, qualifiedName: string): Element;\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver: Node): XPathNSResolver;\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list\n * @param filter A custom NodeFilter function to use. For more information, see filter. Use null for no filter.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createNodeIterator(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): NodeIterator;\n createProcessingInstruction(target: string, data: string): ProcessingInstruction;\n /**\n * Returns an empty range object that has both of its boundary points positioned at the beginning of the document.\n */\n createRange(): Range;\n /**\n * Creates a text string from the specified value.\n * @param data String that specifies the nodeValue property of the text node.\n */\n createTextNode(data: string): Text;\n createTouch(view: Window, target: EventTarget, identifier: number, pageX: number, pageY: number, screenX: number, screenY: number): Touch;\n createTouchList(...touches: Touch[]): TouchList;\n /**\n * Creates a TreeWalker object that you can use to traverse filtered lists of nodes or elements in a document.\n * @param root The root element or node to start traversing on.\n * @param whatToShow The type of nodes or elements to appear in the node list. For more information, see whatToShow.\n * @param filter A custom NodeFilter function to use.\n * @param entityReferenceExpansion A flag that specifies whether entity reference nodes are expanded.\n */\n createTreeWalker(root: Node, whatToShow?: number, filter?: NodeFilter, entityReferenceExpansion?: boolean): TreeWalker;\n /**\n * Returns the element for the specified x coordinate and the specified y coordinate.\n * @param x The x-offset\n * @param y The y-offset\n */\n elementFromPoint(x: number, y: number): Element;\n elementsFromPoint(x: number, y: number): Element[];\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n /**\n * Executes a command on the current document, current selection, or the given range.\n * @param commandId String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.\n * @param showUI Display the user interface, defaults to false.\n * @param value Value to assign.\n */\n execCommand(commandId: string, showUI?: boolean, value?: any): boolean;\n /**\n * Displays help information for the given command identifier.\n * @param commandId Displays help information for the given command identifier.\n */\n execCommandShowHelp(commandId: string): boolean;\n exitFullscreen(): void;\n exitPointerLock(): void;\n /**\n * Causes the element to receive the focus and executes the code specified by the onfocus event.\n */\n /** @deprecated */\n focus(): void;\n getAnimations(): Animation[];\n /**\n * Returns a reference to the first object with the specified value of the ID or NAME attribute.\n * @param elementId String that specifies the ID value. Case-insensitive.\n */\n getElementById(elementId: string): HTMLElement | null;\n getElementsByClassName(classNames: string): HTMLCollectionOf;\n /**\n * Gets a collection of objects based on the value of the NAME or ID attribute.\n * @param elementName Gets a collection of objects based on the value of the NAME or ID attribute.\n */\n getElementsByName(elementName: string): NodeListOf;\n /**\n * Retrieves a collection of objects based on the specified element name.\n * @param name Specifies the name of an element.\n */\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: K): NodeListOf;\n getElementsByTagName(tagname: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n /**\n * Returns an object representing the current selection of the document that is loaded into the object displaying a webpage.\n */\n getSelection(): Selection;\n /**\n * Gets a value indicating whether the object currently has focus.\n */\n hasFocus(): boolean;\n importNode(importedNode: T, deep: boolean): T;\n msElementsFromPoint(x: number, y: number): NodeListOf;\n msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf;\n /**\n * Opens a new window and loads a document specified by a given URL. Also, opens a new window that uses the url parameter and the name parameter to collect the output of the write method and the writeln method.\n * @param url Specifies a MIME type for the document.\n * @param name Specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an anchor element.\n * @param features Contains a list of items separated by commas. Each item consists of an option and a value, separated by an equals sign (for example, \"fullscreen=yes, toolbar=yes\"). The following values are supported.\n * @param replace Specifies whether the existing entry for the document is replaced in the history list.\n */\n open(url?: string, name?: string, features?: string, replace?: boolean): Document;\n /**\n * Returns a Boolean value that indicates whether a specified command can be successfully executed using execCommand, given the current state of the document.\n * @param commandId Specifies a command identifier.\n */\n queryCommandEnabled(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the specified command is in the indeterminate state.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandIndeterm(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates the current state of the command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandState(commandId: string): boolean;\n /**\n * Returns a Boolean value that indicates whether the current command is supported on the current range.\n * @param commandId Specifies a command identifier.\n */\n queryCommandSupported(commandId: string): boolean;\n /**\n * Retrieves the string associated with a command.\n * @param commandId String that contains the identifier of a command. This can be any command identifier given in the list of Command Identifiers.\n */\n queryCommandText(commandId: string): string;\n /**\n * Returns the current value of the document, range, or current selection for the given command.\n * @param commandId String that specifies a command identifier.\n */\n queryCommandValue(commandId: string): string;\n /** @deprecated */\n releaseEvents(): void;\n updateSettings(): void;\n webkitCancelFullScreen(): void;\n webkitExitFullscreen(): void;\n /**\n * Writes one or more HTML expressions to a document in the specified window.\n * @param content Specifies the text and HTML tags to write.\n */\n write(...content: string[]): void;\n /**\n * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window.\n * @param content The text and HTML tags to write.\n */\n writeln(...content: string[]): void;\n addEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Document: {\n prototype: Document;\n new(): Document;\n};\n\ninterface DocumentEvent {\n createEvent(eventInterface: \"AnimationEvent\"): AnimationEvent;\n createEvent(eventInterface: \"AnimationPlaybackEvent\"): AnimationPlaybackEvent;\n createEvent(eventInterface: \"AudioProcessingEvent\"): AudioProcessingEvent;\n createEvent(eventInterface: \"BeforeUnloadEvent\"): BeforeUnloadEvent;\n createEvent(eventInterface: \"ClipboardEvent\"): ClipboardEvent;\n createEvent(eventInterface: \"CloseEvent\"): CloseEvent;\n createEvent(eventInterface: \"CompositionEvent\"): CompositionEvent;\n createEvent(eventInterface: \"CustomEvent\"): CustomEvent;\n createEvent(eventInterface: \"DeviceLightEvent\"): DeviceLightEvent;\n createEvent(eventInterface: \"DeviceMotionEvent\"): DeviceMotionEvent;\n createEvent(eventInterface: \"DeviceOrientationEvent\"): DeviceOrientationEvent;\n createEvent(eventInterface: \"DragEvent\"): DragEvent;\n createEvent(eventInterface: \"ErrorEvent\"): ErrorEvent;\n createEvent(eventInterface: \"Event\"): Event;\n createEvent(eventInterface: \"Events\"): Event;\n createEvent(eventInterface: \"FocusEvent\"): FocusEvent;\n createEvent(eventInterface: \"FocusNavigationEvent\"): FocusNavigationEvent;\n createEvent(eventInterface: \"GamepadEvent\"): GamepadEvent;\n createEvent(eventInterface: \"HashChangeEvent\"): HashChangeEvent;\n createEvent(eventInterface: \"IDBVersionChangeEvent\"): IDBVersionChangeEvent;\n createEvent(eventInterface: \"KeyboardEvent\"): KeyboardEvent;\n createEvent(eventInterface: \"ListeningStateChangedEvent\"): ListeningStateChangedEvent;\n createEvent(eventInterface: \"MSDCCEvent\"): MSDCCEvent;\n createEvent(eventInterface: \"MSDSHEvent\"): MSDSHEvent;\n createEvent(eventInterface: \"MSMediaKeyMessageEvent\"): MSMediaKeyMessageEvent;\n createEvent(eventInterface: \"MSMediaKeyNeededEvent\"): MSMediaKeyNeededEvent;\n createEvent(eventInterface: \"MediaEncryptedEvent\"): MediaEncryptedEvent;\n createEvent(eventInterface: \"MediaKeyMessageEvent\"): MediaKeyMessageEvent;\n createEvent(eventInterface: \"MediaStreamErrorEvent\"): MediaStreamErrorEvent;\n createEvent(eventInterface: \"MediaStreamEvent\"): MediaStreamEvent;\n createEvent(eventInterface: \"MediaStreamTrackEvent\"): MediaStreamTrackEvent;\n createEvent(eventInterface: \"MessageEvent\"): MessageEvent;\n createEvent(eventInterface: \"MouseEvent\"): MouseEvent;\n createEvent(eventInterface: \"MouseEvents\"): MouseEvent;\n createEvent(eventInterface: \"MutationEvent\"): MutationEvent;\n createEvent(eventInterface: \"MutationEvents\"): MutationEvent;\n createEvent(eventInterface: \"OfflineAudioCompletionEvent\"): OfflineAudioCompletionEvent;\n createEvent(eventInterface: \"OverflowEvent\"): OverflowEvent;\n createEvent(eventInterface: \"PageTransitionEvent\"): PageTransitionEvent;\n createEvent(eventInterface: \"PaymentRequestUpdateEvent\"): PaymentRequestUpdateEvent;\n createEvent(eventInterface: \"PermissionRequestedEvent\"): PermissionRequestedEvent;\n createEvent(eventInterface: \"PointerEvent\"): PointerEvent;\n createEvent(eventInterface: \"PopStateEvent\"): PopStateEvent;\n createEvent(eventInterface: \"ProgressEvent\"): ProgressEvent;\n createEvent(eventInterface: \"PromiseRejectionEvent\"): PromiseRejectionEvent;\n createEvent(eventInterface: \"RTCDTMFToneChangeEvent\"): RTCDTMFToneChangeEvent;\n createEvent(eventInterface: \"RTCDataChannelEvent\"): RTCDataChannelEvent;\n createEvent(eventInterface: \"RTCDtlsTransportStateChangedEvent\"): RTCDtlsTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCErrorEvent\"): RTCErrorEvent;\n createEvent(eventInterface: \"RTCIceCandidatePairChangedEvent\"): RTCIceCandidatePairChangedEvent;\n createEvent(eventInterface: \"RTCIceGathererEvent\"): RTCIceGathererEvent;\n createEvent(eventInterface: \"RTCIceTransportStateChangedEvent\"): RTCIceTransportStateChangedEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceErrorEvent\"): RTCPeerConnectionIceErrorEvent;\n createEvent(eventInterface: \"RTCPeerConnectionIceEvent\"): RTCPeerConnectionIceEvent;\n createEvent(eventInterface: \"RTCSsrcConflictEvent\"): RTCSsrcConflictEvent;\n createEvent(eventInterface: \"RTCStatsEvent\"): RTCStatsEvent;\n createEvent(eventInterface: \"RTCTrackEvent\"): RTCTrackEvent;\n createEvent(eventInterface: \"SVGZoomEvent\"): SVGZoomEvent;\n createEvent(eventInterface: \"SVGZoomEvents\"): SVGZoomEvent;\n createEvent(eventInterface: \"SecurityPolicyViolationEvent\"): SecurityPolicyViolationEvent;\n createEvent(eventInterface: \"ServiceWorkerMessageEvent\"): ServiceWorkerMessageEvent;\n createEvent(eventInterface: \"SpeechSynthesisEvent\"): SpeechSynthesisEvent;\n createEvent(eventInterface: \"StorageEvent\"): StorageEvent;\n createEvent(eventInterface: \"TextEvent\"): TextEvent;\n createEvent(eventInterface: \"TouchEvent\"): TouchEvent;\n createEvent(eventInterface: \"TrackEvent\"): TrackEvent;\n createEvent(eventInterface: \"TransitionEvent\"): TransitionEvent;\n createEvent(eventInterface: \"UIEvent\"): UIEvent;\n createEvent(eventInterface: \"UIEvents\"): UIEvent;\n createEvent(eventInterface: \"VRDisplayEvent\"): VRDisplayEvent;\n createEvent(eventInterface: \"VRDisplayEvent \"): VRDisplayEvent ;\n createEvent(eventInterface: \"WebGLContextEvent\"): WebGLContextEvent;\n createEvent(eventInterface: \"WheelEvent\"): WheelEvent;\n createEvent(eventInterface: string): Event;\n}\n\ninterface DocumentFragment extends Node, ParentNode {\n getElementById(elementId: string): HTMLElement | null;\n}\n\ndeclare var DocumentFragment: {\n prototype: DocumentFragment;\n new(): DocumentFragment;\n};\n\ninterface DocumentOrShadowRoot {\n readonly activeElement: Element | null;\n readonly styleSheets: StyleSheetList;\n elementFromPoint(x: number, y: number): Element | null;\n elementsFromPoint(x: number, y: number): Element[];\n getSelection(): Selection | null;\n}\n\ninterface DocumentTimeline extends AnimationTimeline {\n}\n\ndeclare var DocumentTimeline: {\n prototype: DocumentTimeline;\n new(options?: DocumentTimelineOptions): DocumentTimeline;\n};\n\ninterface DocumentType extends Node, ChildNode {\n readonly entities: NamedNodeMap;\n readonly internalSubset: string | null;\n readonly name: string;\n readonly notations: NamedNodeMap;\n readonly publicId: string;\n readonly systemId: string;\n}\n\ndeclare var DocumentType: {\n prototype: DocumentType;\n new(): DocumentType;\n};\n\ninterface DragEvent extends MouseEvent {\n readonly dataTransfer: DataTransfer;\n initDragEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, dataTransferArg: DataTransfer): void;\n msConvertURL(file: File, targetType: string, targetURL?: string): void;\n}\n\ndeclare var DragEvent: {\n prototype: DragEvent;\n new(type: \"drag\" | \"dragend\" | \"dragenter\" | \"dragexit\" | \"dragleave\" | \"dragover\" | \"dragstart\" | \"drop\", dragEventInit?: { dataTransfer?: DataTransfer }): DragEvent;\n};\n\ninterface DynamicsCompressorNode extends AudioNode {\n readonly attack: AudioParam;\n readonly knee: AudioParam;\n readonly ratio: AudioParam;\n readonly reduction: number;\n readonly release: AudioParam;\n readonly threshold: AudioParam;\n}\n\ndeclare var DynamicsCompressorNode: {\n prototype: DynamicsCompressorNode;\n new(context: BaseAudioContext, options?: DynamicsCompressorOptions): DynamicsCompressorNode;\n};\n\ninterface EXT_blend_minmax {\n readonly MAX_EXT: number;\n readonly MIN_EXT: number;\n}\n\ninterface EXT_frag_depth {\n}\n\ninterface EXT_sRGB {\n readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number;\n readonly SRGB8_ALPHA8_EXT: number;\n readonly SRGB_ALPHA_EXT: number;\n readonly SRGB_EXT: number;\n}\n\ninterface EXT_shader_texture_lod {\n}\n\ninterface EXT_texture_filter_anisotropic {\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n}\n\ndeclare var EXT_texture_filter_anisotropic: {\n prototype: EXT_texture_filter_anisotropic;\n new(): EXT_texture_filter_anisotropic;\n readonly MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;\n readonly TEXTURE_MAX_ANISOTROPY_EXT: number;\n};\n\ninterface ElementEventMap extends GlobalEventHandlersEventMap {\n \"ariarequest\": Event;\n \"command\": Event;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSGotPointerCapture\": Event;\n \"MSInertiaStart\": Event;\n \"MSLostPointerCapture\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"webkitfullscreenchange\": Event;\n \"webkitfullscreenerror\": Event;\n}\n\ninterface Element extends Node, GlobalEventHandlers, ElementTraversal, ParentNode, ChildNode, Animatable {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly attributes: NamedNodeMap;\n readonly classList: DOMTokenList;\n className: string;\n readonly clientHeight: number;\n readonly clientLeft: number;\n readonly clientTop: number;\n readonly clientWidth: number;\n id: string;\n innerHTML: string;\n msContentZoomFactor: number;\n readonly msRegionOverflow: string;\n onariarequest: ((this: Element, ev: Event) => any) | null;\n oncommand: ((this: Element, ev: Event) => any) | null;\n onmsgesturechange: ((this: Element, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Element, ev: Event) => any) | null;\n onmsgestureend: ((this: Element, ev: Event) => any) | null;\n onmsgesturehold: ((this: Element, ev: Event) => any) | null;\n onmsgesturestart: ((this: Element, ev: Event) => any) | null;\n onmsgesturetap: ((this: Element, ev: Event) => any) | null;\n onmsgotpointercapture: ((this: Element, ev: Event) => any) | null;\n onmsinertiastart: ((this: Element, ev: Event) => any) | null;\n onmslostpointercapture: ((this: Element, ev: Event) => any) | null;\n onmspointercancel: ((this: Element, ev: Event) => any) | null;\n onmspointerdown: ((this: Element, ev: Event) => any) | null;\n onmspointerenter: ((this: Element, ev: Event) => any) | null;\n onmspointerleave: ((this: Element, ev: Event) => any) | null;\n onmspointermove: ((this: Element, ev: Event) => any) | null;\n onmspointerout: ((this: Element, ev: Event) => any) | null;\n onmspointerover: ((this: Element, ev: Event) => any) | null;\n onmspointerup: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenchange: ((this: Element, ev: Event) => any) | null;\n onwebkitfullscreenerror: ((this: Element, ev: Event) => any) | null;\n outerHTML: string;\n readonly prefix: string | null;\n readonly scrollHeight: number;\n scrollLeft: number;\n scrollTop: number;\n readonly scrollWidth: number;\n readonly shadowRoot: ShadowRoot | null;\n slot: string;\n readonly tagName: string;\n attachShadow(shadowRootInitDict: ShadowRootInit): ShadowRoot;\n closest(selector: K): HTMLElementTagNameMap[K] | null;\n closest(selector: K): SVGElementTagNameMap[K] | null;\n closest(selector: string): Element | null;\n getAttribute(qualifiedName: string): string | null;\n getAttributeNS(namespaceURI: string, localName: string): string;\n getAttributeNode(name: string): Attr | null;\n getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n getElementsByClassName(classNames: string): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: K): NodeListOf;\n getElementsByTagName(name: string): NodeListOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/1999/xhtml\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: \"http://www.w3.org/2000/svg\", localName: string): HTMLCollectionOf;\n getElementsByTagNameNS(namespaceURI: string, localName: string): HTMLCollectionOf;\n hasAttribute(name: string): boolean;\n hasAttributeNS(namespaceURI: string, localName: string): boolean;\n hasAttributes(): boolean;\n hasPointerCapture(pointerId: number): boolean;\n insertAdjacentElement(position: InsertPosition, insertedElement: Element): Element | null;\n insertAdjacentHTML(where: InsertPosition, html: string): void;\n insertAdjacentText(where: InsertPosition, text: string): void;\n matches(selectors: string): boolean;\n msGetRegionContent(): any;\n msGetUntransformedBounds(): ClientRect;\n msMatchesSelector(selectors: string): boolean;\n msReleasePointerCapture(pointerId: number): void;\n msSetPointerCapture(pointerId: number): void;\n msZoomTo(args: MsZoomToOptions): void;\n releasePointerCapture(pointerId: number): void;\n removeAttribute(qualifiedName: string): void;\n removeAttributeNS(namespaceURI: string, localName: string): void;\n removeAttributeNode(oldAttr: Attr): Attr;\n requestFullscreen(): void;\n requestPointerLock(): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x: number, y: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x: number, y: number): void;\n scrollIntoView(arg?: boolean | ScrollIntoViewOptions): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x: number, y: number): void;\n setAttribute(qualifiedName: string, value: string): void;\n setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): void;\n setAttributeNode(newAttr: Attr): Attr;\n setAttributeNodeNS(newAttr: Attr): Attr;\n setPointerCapture(pointerId: number): void;\n webkitMatchesSelector(selectors: string): boolean;\n webkitRequestFullScreen(): void;\n webkitRequestFullscreen(): void;\n addEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Element, ev: ElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Element: {\n prototype: Element;\n new(): Element;\n};\n\ninterface ElementCSSInlineStyle {\n readonly style: CSSStyleDeclaration;\n}\n\ninterface ElementCreationOptions {\n is?: string;\n}\n\ninterface ElementDefinitionOptions {\n extends: string;\n}\n\ninterface ElementTraversal {\n readonly childElementCount: number;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n readonly nextElementSibling: Element | null;\n readonly previousElementSibling: Element | null;\n}\n\ninterface ErrorEvent extends Event {\n readonly colno: number;\n readonly error: any;\n readonly filename: string;\n readonly lineno: number;\n readonly message: string;\n initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;\n}\n\ndeclare var ErrorEvent: {\n prototype: ErrorEvent;\n new(typeArg: string, eventInitDict?: ErrorEventInit): ErrorEvent;\n};\n\ninterface Event {\n readonly bubbles: boolean;\n cancelBubble: boolean;\n readonly cancelable: boolean;\n readonly composed: boolean;\n readonly currentTarget: EventTarget | null;\n readonly defaultPrevented: boolean;\n readonly eventPhase: number;\n readonly isTrusted: boolean;\n returnValue: boolean;\n readonly srcElement: Element | null;\n readonly target: EventTarget | null;\n readonly timeStamp: number;\n readonly type: string;\n deepPath(): EventTarget[];\n initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;\n preventDefault(): void;\n stopImmediatePropagation(): void;\n stopPropagation(): void;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n}\n\ndeclare var Event: {\n prototype: Event;\n new(typeArg: string, eventInitDict?: EventInit): Event;\n readonly AT_TARGET: number;\n readonly BUBBLING_PHASE: number;\n readonly CAPTURING_PHASE: number;\n readonly NONE: number;\n};\n\ninterface EventListenerObject {\n handleEvent(evt: Event): void;\n}\n\ninterface EventSource extends EventTarget {\n readonly CLOSED: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n onerror: (evt: MessageEvent) => any;\n onmessage: (evt: MessageEvent) => any;\n onopen: (evt: MessageEvent) => any;\n readonly readyState: number;\n readonly url: string;\n readonly withCredentials: boolean;\n close(): void;\n}\n\ndeclare var EventSource: {\n prototype: EventSource;\n new(url: string, eventSourceInitDict?: EventSourceInit): EventSource;\n};\n\ninterface EventSourceInit {\n readonly withCredentials: boolean;\n}\n\ninterface EventTarget {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;\n dispatchEvent(evt: Event): boolean;\n removeEventListener(type: string, listener?: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;\n}\n\ndeclare var EventTarget: {\n prototype: EventTarget;\n new(): EventTarget;\n};\n\ninterface ExtensionScriptApis {\n extensionIdToShortId(extensionId: string): number;\n fireExtensionApiTelemetry(functionName: string, isSucceeded: boolean, isSupported: boolean, errorString: string): void;\n genericFunction(routerAddress: any, parameters?: string, callbackId?: number): void;\n genericSynchronousFunction(functionId: number, parameters?: string): string;\n genericWebRuntimeCallout(to: any, from: any, payload: string): void;\n getExtensionId(): string;\n registerGenericFunctionCallbackHandler(callbackHandler: Function): void;\n registerGenericPersistentCallbackHandler(callbackHandler: Function): void;\n registerWebRuntimeCallbackHandler(handler: Function): any;\n}\n\ndeclare var ExtensionScriptApis: {\n prototype: ExtensionScriptApis;\n new(): ExtensionScriptApis;\n};\n\ninterface External {\n /** @deprecated */\n AddSearchProvider(): void;\n /** @deprecated */\n IsSearchProviderInstalled(): void;\n}\n\ninterface File extends Blob {\n readonly lastModified: number;\n readonly name: string;\n}\n\ndeclare var File: {\n prototype: File;\n new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;\n};\n\ninterface FileList {\n readonly length: number;\n item(index: number): File | null;\n [index: number]: File;\n}\n\ndeclare var FileList: {\n prototype: FileList;\n new(): FileList;\n};\n\ninterface FileReaderEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n}\n\ninterface FileReader extends EventTarget {\n readonly error: DOMException | null;\n onabort: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onerror: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onload: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadend: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: FileReader, ev: ProgressEvent) => any) | null;\n onprogress: ((this: FileReader, ev: ProgressEvent) => any) | null;\n readonly readyState: number;\n readonly result: string | ArrayBuffer | null;\n abort(): void;\n readAsArrayBuffer(blob: Blob): void;\n readAsBinaryString(blob: Blob): void;\n readAsDataURL(blob: Blob): void;\n readAsText(blob: Blob, label?: string): void;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n addEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var FileReader: {\n prototype: FileReader;\n new(): FileReader;\n readonly DONE: number;\n readonly EMPTY: number;\n readonly LOADING: number;\n};\n\ninterface FocusEvent extends UIEvent {\n readonly relatedTarget: EventTarget;\n initFocusEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, relatedTargetArg: EventTarget): void;\n}\n\ndeclare var FocusEvent: {\n prototype: FocusEvent;\n new(typeArg: string, eventInitDict?: FocusEventInit): FocusEvent;\n};\n\ninterface FocusNavigationEvent extends Event {\n readonly navigationReason: NavigationReason;\n readonly originHeight: number;\n readonly originLeft: number;\n readonly originTop: number;\n readonly originWidth: number;\n requestFocus(): void;\n}\n\ndeclare var FocusNavigationEvent: {\n prototype: FocusNavigationEvent;\n new(type: string, eventInitDict?: FocusNavigationEventInit): FocusNavigationEvent;\n};\n\ninterface FormData {\n append(name: string, value: string | Blob, fileName?: string): void;\n delete(name: string): void;\n get(name: string): FormDataEntryValue | null;\n getAll(name: string): FormDataEntryValue[];\n has(name: string): boolean;\n set(name: string, value: string | Blob, fileName?: string): void;\n forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;\n}\n\ndeclare var FormData: {\n prototype: FormData;\n new(form?: HTMLFormElement): FormData;\n};\n\ninterface GainNode extends AudioNode {\n readonly gain: AudioParam;\n}\n\ndeclare var GainNode: {\n prototype: GainNode;\n new(context: BaseAudioContext, options?: GainOptions): GainNode;\n};\n\ninterface Gamepad {\n readonly axes: number[];\n readonly buttons: GamepadButton[];\n readonly connected: boolean;\n readonly displayId: number;\n readonly hand: GamepadHand;\n readonly hapticActuators: GamepadHapticActuator[];\n readonly id: string;\n readonly index: number;\n readonly mapping: GamepadMappingType;\n readonly pose: GamepadPose | null;\n readonly timestamp: number;\n}\n\ndeclare var Gamepad: {\n prototype: Gamepad;\n new(): Gamepad;\n};\n\ninterface GamepadButton {\n readonly pressed: boolean;\n readonly touched: boolean;\n readonly value: number;\n}\n\ndeclare var GamepadButton: {\n prototype: GamepadButton;\n new(): GamepadButton;\n};\n\ninterface GamepadEvent extends Event {\n readonly gamepad: Gamepad;\n}\n\ndeclare var GamepadEvent: {\n prototype: GamepadEvent;\n new(typeArg: string, eventInitDict?: GamepadEventInit): GamepadEvent;\n};\n\ninterface GamepadHapticActuator {\n readonly type: GamepadHapticActuatorType;\n pulse(value: number, duration: number): Promise;\n}\n\ndeclare var GamepadHapticActuator: {\n prototype: GamepadHapticActuator;\n new(): GamepadHapticActuator;\n};\n\ninterface GamepadPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n}\n\ndeclare var GamepadPose: {\n prototype: GamepadPose;\n new(): GamepadPose;\n};\n\ninterface Geolocation {\n clearWatch(watchId: number): void;\n getCurrentPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): void;\n watchPosition(successCallback: PositionCallback, errorCallback?: PositionErrorCallback, options?: PositionOptions): number;\n}\n\ninterface GetSVGDocument {\n getSVGDocument(): Document;\n}\n\ninterface GlobalEventHandlersEventMap {\n \"animationcancel\": AnimationEvent;\n \"animationend\": AnimationEvent;\n \"animationiteration\": AnimationEvent;\n \"animationstart\": AnimationEvent;\n \"gotpointercapture\": PointerEvent;\n \"lostpointercapture\": PointerEvent;\n \"pointercancel\": PointerEvent;\n \"pointerdown\": PointerEvent;\n \"pointerenter\": PointerEvent;\n \"pointerleave\": PointerEvent;\n \"pointermove\": PointerEvent;\n \"pointerout\": PointerEvent;\n \"pointerover\": PointerEvent;\n \"pointerup\": PointerEvent;\n \"touchcancel\": TouchEvent;\n \"touchend\": TouchEvent;\n \"touchmove\": TouchEvent;\n \"touchstart\": TouchEvent;\n \"transitioncancel\": TransitionEvent;\n \"transitionend\": TransitionEvent;\n \"transitionrun\": TransitionEvent;\n \"transitionstart\": TransitionEvent;\n \"wheel\": WheelEvent;\n}\n\ninterface GlobalEventHandlers {\n onanimationcancel: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationend: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationiteration: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n onanimationstart: ((this: GlobalEventHandlers, ev: AnimationEvent) => any) | null;\n ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null;\n ontouchcancel: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchend: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchmove: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontouchstart: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null;\n ontransitioncancel: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionend: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionrun: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n ontransitionstart: ((this: GlobalEventHandlers, ev: TransitionEvent) => any) | null;\n onwheel: ((this: GlobalEventHandlers, ev: WheelEvent) => any) | null;\n addEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface GlobalFetch {\n fetch(input?: Request | string, init?: RequestInit): Promise;\n}\n\ninterface HTMLAllCollection {\n /**\n * Returns the number of elements in the collection.\n */\n readonly length: number;\n /**\n * element = collection(index)\n */\n item(nameOrIndex?: string): HTMLCollection | Element | null;\n /**\n * element = collection(name)\n */\n namedItem(name: string): HTMLCollection | Element | null;\n [index: number]: Element;\n}\n\ndeclare var HTMLAllCollection: {\n prototype: HTMLAllCollection;\n new(): HTMLAllCollection;\n};\n\ninterface HTMLAnchorElement extends HTMLElement, HTMLHyperlinkElementUtils {\n Methods: string;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n /** @deprecated */\n coords: string;\n download: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n readonly mimeType: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n readonly nameProp: string;\n readonly protocolLong: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n type: string;\n urn: string;\n addEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAnchorElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAnchorElement: {\n prototype: HTMLAnchorElement;\n new(): HTMLAnchorElement;\n};\n\ninterface HTMLAppletElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n /** @deprecated */\n alt: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves the shape of the object.\n */\n /** @deprecated */\n name: string;\n /** @deprecated */\n object: string;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAppletElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAppletElement: {\n prototype: HTMLAppletElement;\n new(): HTMLAppletElement;\n};\n\ninterface HTMLAreaElement extends HTMLElement, HTMLHyperlinkElementUtils {\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Sets or retrieves the coordinates of the object.\n */\n coords: string;\n download: string;\n /**\n * Sets or gets whether clicks in this region cause action.\n */\n /** @deprecated */\n noHref: boolean;\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the shape of the object.\n */\n shape: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAreaElement: {\n prototype: HTMLAreaElement;\n new(): HTMLAreaElement;\n};\n\ninterface HTMLAreasCollection extends HTMLCollectionBase {\n}\n\ndeclare var HTMLAreasCollection: {\n prototype: HTMLAreasCollection;\n new(): HTMLAreasCollection;\n};\n\ninterface HTMLAudioElement extends HTMLMediaElement {\n addEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLAudioElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLAudioElement: {\n prototype: HTMLAudioElement;\n new(): HTMLAudioElement;\n};\n\ninterface HTMLBRElement extends HTMLElement {\n /**\n * Sets or retrieves the side on which floating objects are not to be positioned when any IHTMLBlockElement is inserted into the document.\n */\n /** @deprecated */\n clear: string;\n addEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBRElement: {\n prototype: HTMLBRElement;\n new(): HTMLBRElement;\n};\n\ninterface HTMLBaseElement extends HTMLElement {\n /**\n * Gets or sets the baseline URL on which relative links are based.\n */\n href: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n addEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseElement: {\n prototype: HTMLBaseElement;\n new(): HTMLBaseElement;\n};\n\ninterface HTMLBaseFontElement extends HTMLElement, DOML2DeprecatedColorProperty {\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /**\n * Sets or retrieves the font size of the object.\n */\n /** @deprecated */\n size: number;\n addEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBaseFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBaseFontElement: {\n prototype: HTMLBaseFontElement;\n new(): HTMLBaseFontElement;\n};\n\ninterface HTMLBodyElementEventMap extends HTMLElementEventMap, WindowEventHandlersEventMap {\n \"blur\": FocusEvent;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"load\": Event;\n \"orientationchange\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n}\n\ninterface HTMLBodyElement extends HTMLElement, WindowEventHandlers {\n /** @deprecated */\n aLink: string;\n /** @deprecated */\n background: string;\n /** @deprecated */\n bgColor: string;\n bgProperties: string;\n /** @deprecated */\n link: string;\n /** @deprecated */\n noWrap: boolean;\n onorientationchange: ((this: HTMLBodyElement, ev: Event) => any) | null;\n onresize: ((this: HTMLBodyElement, ev: UIEvent) => any) | null;\n /** @deprecated */\n text: string;\n /** @deprecated */\n vLink: string;\n addEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLBodyElement, ev: HTMLBodyElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLBodyElement: {\n prototype: HTMLBodyElement;\n new(): HTMLBodyElement;\n};\n\ninterface HTMLButtonElement extends HTMLElement {\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets the classification and default behavior of the button.\n */\n type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the default or selected value of the control.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLButtonElement: {\n prototype: HTMLButtonElement;\n new(): HTMLButtonElement;\n};\n\ninterface HTMLCanvasElement extends HTMLElement {\n /**\n * Gets or sets the height of a canvas element on a document.\n */\n height: number;\n /**\n * Gets or sets the width of a canvas element on a document.\n */\n width: number;\n /**\n * Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.\n * @param contextId The identifier (ID) of the type of canvas to create. Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using canvas.getContext(\"2d\"); IE11 Preview also supports 3-D or WebGL context using canvas.getContext(\"experimental-webgl\");\n */\n getContext(contextId: \"2d\", contextAttributes?: Canvas2DContextAttributes): CanvasRenderingContext2D | null;\n getContext(contextId: \"webgl\" | \"experimental-webgl\", contextAttributes?: WebGLContextAttributes): WebGLRenderingContext | null;\n getContext(contextId: string, contextAttributes?: {}): CanvasRenderingContext2D | WebGLRenderingContext | null;\n /**\n * Returns a blob object encoded as a Portable Network Graphics (PNG) format from a canvas image or drawing.\n */\n msToBlob(): Blob;\n toBlob(callback: (result: Blob | null) => void, type?: string, ...arguments: any[]): void;\n /**\n * Returns the content of the current canvas as an image that you can use as a source for another canvas or an HTML element.\n * @param type The standard MIME type for the image format to return. If you do not specify this parameter, the default value is a PNG format image.\n */\n toDataURL(type?: string, ...args: any[]): string;\n addEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLCanvasElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLCanvasElement: {\n prototype: HTMLCanvasElement;\n new(): HTMLCanvasElement;\n};\n\ninterface HTMLCollectionBase {\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Retrieves an object from various collections.\n */\n item(index: number): Element;\n [index: number]: Element;\n}\n\ninterface HTMLCollection extends HTMLCollectionBase {\n /**\n * Retrieves a select object or an object from an options collection.\n */\n namedItem(name: string): Element | null;\n}\n\ndeclare var HTMLCollection: {\n prototype: HTMLCollection;\n new(): HTMLCollection;\n};\n\ninterface HTMLCollectionOf extends HTMLCollectionBase {\n item(index: number): T;\n namedItem(name: string): T;\n forEach(callbackfn: (value: T, key: number, parent: HTMLCollectionOf) => void, thisArg?: any): void;\n [index: number]: T;\n}\n\ninterface HTMLDListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDListElement: {\n prototype: HTMLDListElement;\n new(): HTMLDListElement;\n};\n\ninterface HTMLDataElement extends HTMLElement {\n value: string;\n addEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataElement: {\n prototype: HTMLDataElement;\n new(): HTMLDataElement;\n};\n\ninterface HTMLDataListElement extends HTMLElement {\n readonly options: HTMLCollectionOf;\n addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDataListElement: {\n prototype: HTMLDataListElement;\n new(): HTMLDataListElement;\n};\n\ninterface HTMLDetailsElement extends HTMLElement {\n open: boolean;\n addEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDetailsElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDetailsElement: {\n prototype: HTMLDetailsElement;\n new(): HTMLDetailsElement;\n};\n\ninterface HTMLDialogElement extends HTMLElement {\n open: boolean;\n returnValue: string;\n close(returnValue?: string): void;\n show(): void;\n showModal(): void;\n addEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDialogElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDialogElement: {\n prototype: HTMLDialogElement;\n new(): HTMLDialogElement;\n};\n\ninterface HTMLDirectoryElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n addEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDirectoryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDirectoryElement: {\n prototype: HTMLDirectoryElement;\n new(): HTMLDirectoryElement;\n};\n\ninterface HTMLDivElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n noWrap: boolean;\n addEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDivElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDivElement: {\n prototype: HTMLDivElement;\n new(): HTMLDivElement;\n};\n\ninterface HTMLDocument extends Document {\n addEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLDocument: {\n prototype: HTMLDocument;\n new(): HTMLDocument;\n};\n\ninterface HTMLElementEventMap extends ElementEventMap {\n \"abort\": UIEvent;\n \"activate\": Event;\n \"beforeactivate\": Event;\n \"beforecopy\": Event;\n \"beforecut\": Event;\n \"beforedeactivate\": Event;\n \"beforepaste\": Event;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"contextmenu\": PointerEvent;\n \"copy\": ClipboardEvent;\n \"cuechange\": Event;\n \"cut\": ClipboardEvent;\n \"dblclick\": MouseEvent;\n \"deactivate\": Event;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSContentZoom\": Event;\n \"MSManipulationStateChanged\": Event;\n \"paste\": ClipboardEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"reset\": Event;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"selectstart\": Event;\n \"stalled\": Event;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"volumechange\": Event;\n \"waiting\": Event;\n}\n\ninterface HTMLElement extends Element, ElementCSSInlineStyle {\n accessKey: string;\n contentEditable: string;\n readonly dataset: DOMStringMap;\n dir: string;\n draggable: boolean;\n hidden: boolean;\n hideFocus: boolean;\n innerText: string;\n readonly isContentEditable: boolean;\n lang: string;\n readonly offsetHeight: number;\n readonly offsetLeft: number;\n readonly offsetParent: Element;\n readonly offsetTop: number;\n readonly offsetWidth: number;\n onabort: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecopy: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforecut: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforedeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n onbeforepaste: ((this: HTMLElement, ev: Event) => any) | null;\n onblur: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oncanplay: ((this: HTMLElement, ev: Event) => any) | null;\n oncanplaythrough: ((this: HTMLElement, ev: Event) => any) | null;\n onchange: ((this: HTMLElement, ev: Event) => any) | null;\n onclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n oncontextmenu: ((this: HTMLElement, ev: PointerEvent) => any) | null;\n oncopy: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n oncuechange: ((this: HTMLElement, ev: Event) => any) | null;\n oncut: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n ondblclick: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n ondeactivate: ((this: HTMLElement, ev: Event) => any) | null;\n ondrag: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragend: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragenter: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragleave: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragover: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondragstart: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondrop: ((this: HTMLElement, ev: DragEvent) => any) | null;\n ondurationchange: ((this: HTMLElement, ev: Event) => any) | null;\n onemptied: ((this: HTMLElement, ev: Event) => any) | null;\n onended: ((this: HTMLElement, ev: Event) => any) | null;\n onerror: ((this: HTMLElement, ev: ErrorEvent) => any) | null;\n onfocus: ((this: HTMLElement, ev: FocusEvent) => any) | null;\n oninput: ((this: HTMLElement, ev: Event) => any) | null;\n oninvalid: ((this: HTMLElement, ev: Event) => any) | null;\n onkeydown: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: HTMLElement, ev: KeyboardEvent) => any) | null;\n onload: ((this: HTMLElement, ev: Event) => any) | null;\n onloadeddata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadedmetadata: ((this: HTMLElement, ev: Event) => any) | null;\n onloadstart: ((this: HTMLElement, ev: Event) => any) | null;\n onmousedown: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: HTMLElement, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: HTMLElement, ev: WheelEvent) => any) | null;\n onmscontentzoom: ((this: HTMLElement, ev: Event) => any) | null;\n onmsmanipulationstatechanged: ((this: HTMLElement, ev: Event) => any) | null;\n onpaste: ((this: HTMLElement, ev: ClipboardEvent) => any) | null;\n onpause: ((this: HTMLElement, ev: Event) => any) | null;\n onplay: ((this: HTMLElement, ev: Event) => any) | null;\n onplaying: ((this: HTMLElement, ev: Event) => any) | null;\n onprogress: ((this: HTMLElement, ev: ProgressEvent) => any) | null;\n onratechange: ((this: HTMLElement, ev: Event) => any) | null;\n onreset: ((this: HTMLElement, ev: Event) => any) | null;\n onscroll: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onseeked: ((this: HTMLElement, ev: Event) => any) | null;\n onseeking: ((this: HTMLElement, ev: Event) => any) | null;\n onselect: ((this: HTMLElement, ev: UIEvent) => any) | null;\n onselectstart: ((this: HTMLElement, ev: Event) => any) | null;\n onstalled: ((this: HTMLElement, ev: Event) => any) | null;\n onsubmit: ((this: HTMLElement, ev: Event) => any) | null;\n onsuspend: ((this: HTMLElement, ev: Event) => any) | null;\n ontimeupdate: ((this: HTMLElement, ev: Event) => any) | null;\n onvolumechange: ((this: HTMLElement, ev: Event) => any) | null;\n onwaiting: ((this: HTMLElement, ev: Event) => any) | null;\n outerText: string;\n spellcheck: boolean;\n tabIndex: number;\n title: string;\n blur(): void;\n click(): void;\n dragDrop(): boolean;\n focus(): void;\n msGetInputContext(): MSInputMethodContext;\n addEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLElement: {\n prototype: HTMLElement;\n new(): HTMLElement;\n};\n\ninterface HTMLEmbedElement extends HTMLElement, GetSVGDocument {\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n hidden: any;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * Retrieves the palette used for the embedded document.\n */\n readonly palette: string;\n /**\n * Retrieves the URL of the plug-in used to view an embedded document.\n */\n readonly pluginspage: string;\n readonly readyState: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrieves the height and width units of the embed object.\n */\n units: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLEmbedElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLEmbedElement: {\n prototype: HTMLEmbedElement;\n new(): HTMLEmbedElement;\n};\n\ninterface HTMLFieldSetElement extends HTMLElement {\n disabled: boolean;\n readonly elements: HTMLCollection;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n name: string;\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFieldSetElement: {\n prototype: HTMLFieldSetElement;\n new(): HTMLFieldSetElement;\n};\n\ninterface HTMLFontElement extends HTMLElement {\n /** @deprecated */\n color: string;\n /**\n * Sets or retrieves the current typeface family.\n */\n /** @deprecated */\n face: string;\n /** @deprecated */\n size: string;\n addEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFontElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFontElement: {\n prototype: HTMLFontElement;\n new(): HTMLFontElement;\n};\n\ninterface HTMLFormControlsCollection extends HTMLCollectionBase {\n /**\n * element = collection[name]\n */\n namedItem(name: string): RadioNodeList | Element | null;\n}\n\ndeclare var HTMLFormControlsCollection: {\n prototype: HTMLFormControlsCollection;\n new(): HTMLFormControlsCollection;\n};\n\ninterface HTMLFormElement extends HTMLElement {\n /**\n * Sets or retrieves a list of character encodings for input data that must be accepted by the server processing the form.\n */\n acceptCharset: string;\n /**\n * Sets or retrieves the URL to which the form content is sent for processing.\n */\n action: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Retrieves a collection, in source order, of all controls in a given form.\n */\n readonly elements: HTMLFormControlsCollection;\n /**\n * Sets or retrieves the MIME encoding for the form.\n */\n encoding: string;\n /**\n * Sets or retrieves the encoding type for the form.\n */\n enctype: string;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n readonly length: number;\n /**\n * Sets or retrieves how to send the form data to the server.\n */\n method: string;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Designates a form that is not validated when submitted.\n */\n noValidate: boolean;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n target: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a form object or an object from an elements collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is a Number, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(name?: any, index?: any): any;\n /**\n * Retrieves a form object or an object from an elements collection.\n */\n namedItem(name: string): any;\n reportValidity(): boolean;\n /**\n * Fires when the user resets a form.\n */\n reset(): void;\n /**\n * Fires when a FORM is about to be submitted.\n */\n submit(): void;\n addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [name: string]: any;\n}\n\ndeclare var HTMLFormElement: {\n prototype: HTMLFormElement;\n new(): HTMLFormElement;\n};\n\ninterface HTMLFrameElement extends HTMLElement {\n /**\n * Retrieves the document object of the page or frame.\n */\n /** @deprecated */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n /** @deprecated */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n /** @deprecated */\n name: string;\n /**\n * Sets or retrieves whether the user can resize the frame.\n */\n /** @deprecated */\n noResize: boolean;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n /** @deprecated */\n src: string;\n addEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameElement: {\n prototype: HTMLFrameElement;\n new(): HTMLFrameElement;\n};\n\ninterface HTMLFrameSetElement extends HTMLElement, WindowEventHandlers {\n /**\n * Sets or retrieves the frame widths of the object.\n */\n /** @deprecated */\n cols: string;\n /**\n * Sets or retrieves the frame heights of the object.\n */\n /** @deprecated */\n rows: string;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLFrameSetElement, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLFrameSetElement: {\n prototype: HTMLFrameSetElement;\n new(): HTMLFrameSetElement;\n};\n\ninterface HTMLHRElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n color: string;\n /**\n * Sets or retrieves whether the horizontal rule is drawn with 3-D shading.\n */\n /** @deprecated */\n noShade: boolean;\n /** @deprecated */\n size: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHRElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHRElement: {\n prototype: HTMLHRElement;\n new(): HTMLHRElement;\n};\n\ninterface HTMLHeadElement extends HTMLElement {\n /** @deprecated */\n profile: string;\n addEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadElement: {\n prototype: HTMLHeadElement;\n new(): HTMLHeadElement;\n};\n\ninterface HTMLHeadingElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHeadingElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHeadingElement: {\n prototype: HTMLHeadingElement;\n new(): HTMLHeadingElement;\n};\n\ninterface HTMLHtmlElement extends HTMLElement {\n /**\n * Sets or retrieves the DTD version that governs the current document.\n */\n /** @deprecated */\n version: string;\n addEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLHtmlElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLHtmlElement: {\n prototype: HTMLHtmlElement;\n new(): HTMLHtmlElement;\n};\n\ninterface HTMLHyperlinkElementUtils {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n toString(): string;\n}\n\ninterface HTMLIFrameElementEventMap extends HTMLElementEventMap {\n \"load\": Event;\n}\n\ninterface HTMLIFrameElement extends HTMLElement, GetSVGDocument {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n allowFullscreen: boolean;\n allowPaymentRequest: boolean;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Retrieves the object of the specified.\n */\n readonly contentWindow: Window | null;\n /**\n * Sets or retrieves whether to display a border for the frame.\n */\n /** @deprecated */\n frameBorder: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /**\n * Sets or retrieves a URI to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /**\n * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n */\n /** @deprecated */\n marginHeight: string;\n /**\n * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n */\n /** @deprecated */\n marginWidth: string;\n /**\n * Sets or retrieves the frame name.\n */\n name: string;\n readonly sandbox: DOMTokenList;\n /**\n * Sets or retrieves whether the frame can be scrolled.\n */\n /** @deprecated */\n scrolling: string;\n /**\n * Sets or retrieves a URL to be loaded by the object.\n */\n src: string;\n /**\n * Sets or retrives the content of the page that is to contain.\n */\n srcdoc: string;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLIFrameElement: {\n prototype: HTMLIFrameElement;\n new(): HTMLIFrameElement;\n};\n\ninterface HTMLImageElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies the properties of a border drawn around an object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves whether the object is fully loaded.\n */\n readonly complete: boolean;\n crossOrigin: string | null;\n readonly currentSrc: string;\n decoding: \"async\" | \"sync\" | \"auto\";\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n hspace: number;\n /**\n * Sets or retrieves whether the image is a server-side image map.\n */\n isMap: boolean;\n /**\n * Sets or retrieves a Uniform Resource Identifier (URI) to a long description of the object.\n */\n /** @deprecated */\n longDesc: string;\n /** @deprecated */\n lowsrc: string;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n /** @deprecated */\n name: string;\n /**\n * The original height of the image resource before sizing.\n */\n readonly naturalHeight: number;\n /**\n * The original width of the image resource before sizing.\n */\n readonly naturalWidth: number;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Sets or retrieves the vertical margin for the object.\n */\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n readonly x: number;\n readonly y: number;\n msGetAsCastingSource(): any;\n addEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLImageElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLImageElement: {\n prototype: HTMLImageElement;\n new(): HTMLImageElement;\n};\n\ninterface HTMLInputElement extends HTMLElement {\n /**\n * Sets or retrieves a comma-separated list of content types.\n */\n accept: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a text alternative to the graphic.\n */\n alt: string;\n /**\n * Specifies whether autocomplete is applied to an editable text field.\n */\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n checked: boolean;\n /**\n * Sets or retrieves the state of the check box or radio button.\n */\n defaultChecked: boolean;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n disabled: boolean;\n /**\n * Returns a FileList object on a file type input object.\n */\n files: FileList | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Overrides the action attribute (where the data on a form is sent) on the parent form element.\n */\n formAction: string;\n /**\n * Used to override the encoding (formEnctype attribute) specified on the form element.\n */\n formEnctype: string;\n /**\n * Overrides the submit method attribute previously specified on a form element.\n */\n formMethod: string;\n /**\n * Overrides any validation or required attributes on a form or form elements to allow it to be submitted without validation. This can be used to create a \"save draft\"-type submit option.\n */\n formNoValidate: boolean;\n /**\n * Overrides the target attribute on a form element.\n */\n formTarget: string;\n /**\n * Sets or retrieves the height of the object.\n */\n height: number;\n indeterminate: boolean;\n /**\n * Specifies the ID of a pre-defined datalist of options for an input element.\n */\n readonly list: HTMLElement | null;\n /**\n * Defines the maximum acceptable value for an input element with type=\"number\".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field.\n */\n max: string;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n /**\n * Defines the minimum acceptable value for an input element with type=\"number\". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field.\n */\n min: string;\n minLength: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a string containing a regular expression that the user's input must match.\n */\n pattern: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n selectionDirection: string | null;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number | null;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number | null;\n size: number;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n /**\n * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field.\n */\n step: string;\n /**\n * Returns the content type of the object.\n */\n type: string;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n /** @deprecated */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Returns the value of the data at the cursor's current position.\n */\n value: string;\n valueAsDate: any;\n /**\n * Returns the input field value as a number.\n */\n valueAsNumber: number;\n webkitdirectory: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n width: number;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Makes the selection equal to the current object.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n /**\n * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value.\n * @param n Value to decrement the value by.\n */\n stepDown(n?: number): void;\n /**\n * Increments a range input control's value by the value given by the Step attribute. If the optional parameter is used, will increment the input control's value by that value.\n * @param n Value to increment the value by.\n */\n stepUp(n?: number): void;\n addEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLInputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLInputElement: {\n prototype: HTMLInputElement;\n new(): HTMLInputElement;\n};\n\ninterface HTMLLIElement extends HTMLElement {\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of a list item.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLIElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLIElement: {\n prototype: HTMLLIElement;\n new(): HTMLLIElement;\n};\n\ninterface HTMLLabelElement extends HTMLElement {\n readonly control: HTMLInputElement | null;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the object to which the given label object is assigned.\n */\n htmlFor: string;\n addEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLabelElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLabelElement: {\n prototype: HTMLLabelElement;\n new(): HTMLLabelElement;\n};\n\ninterface HTMLLegendElement extends HTMLElement {\n /** @deprecated */\n align: string;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLegendElement: {\n prototype: HTMLLegendElement;\n new(): HTMLLegendElement;\n};\n\ninterface HTMLLinkElement extends HTMLElement, LinkStyle {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves a destination URL or an anchor point.\n */\n href: string;\n /**\n * Sets or retrieves the language code of the object.\n */\n hreflang: string;\n import?: Document;\n integrity: string;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n rel: string;\n readonly relList: DOMTokenList;\n /**\n * Sets or retrieves the relationship between the object and the destination of the link.\n */\n /** @deprecated */\n rev: string;\n /**\n * Sets or retrieves the window or frame at which to target content.\n */\n /** @deprecated */\n target: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLLinkElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLLinkElement: {\n prototype: HTMLLinkElement;\n new(): HTMLLinkElement;\n};\n\ninterface HTMLMainElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMainElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMainElement: {\n prototype: HTMLMainElement;\n new(): HTMLMainElement;\n};\n\ninterface HTMLMapElement extends HTMLElement {\n /**\n * Retrieves a collection of the area objects defined for the given map object.\n */\n readonly areas: HTMLAreasCollection;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n addEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMapElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMapElement: {\n prototype: HTMLMapElement;\n new(): HTMLMapElement;\n};\n\ninterface HTMLMarqueeElementEventMap extends HTMLElementEventMap {\n \"bounce\": Event;\n \"finish\": Event;\n \"start\": Event;\n}\n\ninterface HTMLMarqueeElement extends HTMLElement {\n /** @deprecated */\n behavior: string;\n /** @deprecated */\n bgColor: string;\n /** @deprecated */\n direction: string;\n /** @deprecated */\n height: string;\n /** @deprecated */\n hspace: number;\n /** @deprecated */\n loop: number;\n /** @deprecated */\n onbounce: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onfinish: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n onstart: ((this: HTMLMarqueeElement, ev: Event) => any) | null;\n /** @deprecated */\n scrollAmount: number;\n /** @deprecated */\n scrollDelay: number;\n /** @deprecated */\n trueSpeed: boolean;\n /** @deprecated */\n vspace: number;\n /** @deprecated */\n width: string;\n /** @deprecated */\n start(): void;\n /** @deprecated */\n stop(): void;\n addEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMarqueeElement, ev: HTMLMarqueeElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMarqueeElement: {\n prototype: HTMLMarqueeElement;\n new(): HTMLMarqueeElement;\n};\n\ninterface HTMLMediaElementEventMap extends HTMLElementEventMap {\n \"encrypted\": MediaEncryptedEvent;\n \"msneedkey\": Event;\n}\n\ninterface HTMLMediaElement extends HTMLElement {\n /**\n * Returns an AudioTrackList object with the audio tracks for a given video element.\n */\n readonly audioTracks: AudioTrackList;\n /**\n * Gets or sets a value that indicates whether to start playing the media automatically.\n */\n autoplay: boolean;\n /**\n * Gets a collection of buffered time ranges.\n */\n readonly buffered: TimeRanges;\n /**\n * Gets or sets a flag that indicates whether the client provides a set of controls for the media (in case the developer does not include controls for the player).\n */\n controls: boolean;\n crossOrigin: string | null;\n /**\n * Gets the address or URL of the current media resource that is selected by IHTMLMediaElement.\n */\n readonly currentSrc: string;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n currentTime: number;\n defaultMuted: boolean;\n /**\n * Gets or sets the default playback rate when the user is not using fast forward or reverse for a video or audio resource.\n */\n defaultPlaybackRate: number;\n /**\n * Returns the duration in seconds of the current media resource. A NaN value is returned if duration is not available, or Infinity if the media resource is streaming.\n */\n readonly duration: number;\n /**\n * Gets information about whether the playback has ended or not.\n */\n readonly ended: boolean;\n /**\n * Returns an object representing the current error state of the audio or video element.\n */\n readonly error: MediaError | null;\n /**\n * Gets or sets a flag to specify whether playback should restart after it completes.\n */\n loop: boolean;\n readonly mediaKeys: MediaKeys | null;\n /**\n * Specifies the purpose of the audio or video media, such as background audio or alerts.\n */\n msAudioCategory: string;\n /**\n * Specifies the output device id that the audio will be sent to.\n */\n msAudioDeviceType: string;\n readonly msGraphicsTrustStatus: MSGraphicsTrust;\n /**\n * Gets the MSMediaKeys object, which is used for decrypting media data, that is associated with this media element.\n */\n /** @deprecated */\n readonly msKeys: MSMediaKeys;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Specifies whether or not to enable low-latency playback on the media element.\n */\n msRealTime: boolean;\n /**\n * Gets or sets a flag that indicates whether the audio (either audio or the audio track on video media) is muted.\n */\n muted: boolean;\n /**\n * Gets the current network activity for the element.\n */\n readonly networkState: number;\n onencrypted: ((this: HTMLMediaElement, ev: MediaEncryptedEvent) => any) | null;\n /** @deprecated */\n onmsneedkey: ((this: HTMLMediaElement, ev: Event) => any) | null;\n /**\n * Gets a flag that specifies whether playback is paused.\n */\n readonly paused: boolean;\n /**\n * Gets or sets the current rate of speed for the media resource to play. This speed is expressed as a multiple of the normal speed of the media resource.\n */\n playbackRate: number;\n /**\n * Gets TimeRanges for the current media resource that has been played.\n */\n readonly played: TimeRanges;\n /**\n * Gets or sets the current playback position, in seconds.\n */\n preload: string;\n readonly readyState: number;\n /**\n * Returns a TimeRanges object that represents the ranges of the current media resource that can be seeked.\n */\n readonly seekable: TimeRanges;\n /**\n * Gets a flag that indicates whether the the client is currently moving to a new playback position in the media resource.\n */\n readonly seeking: boolean;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcObject: MediaStream | MediaSource | Blob | null;\n readonly textTracks: TextTrackList;\n readonly videoTracks: VideoTrackList;\n /**\n * Gets or sets the volume level for audio portions of the media element.\n */\n volume: number;\n addTextTrack(kind: TextTrackKind, label?: string, language?: string): TextTrack;\n /**\n * Returns a string that specifies whether the client can play a given media resource type.\n */\n canPlayType(type: string): CanPlayTypeResult;\n /**\n * Resets the audio or video object and loads a new media resource.\n */\n load(): void;\n /**\n * Clears all effects from the media pipeline.\n */\n msClearEffects(): void;\n msGetAsCastingSource(): any;\n /**\n * Inserts the specified audio effect into media pipeline.\n */\n msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n /** @deprecated */\n msSetMediaKeys(mediaKeys: MSMediaKeys): void;\n /**\n * Specifies the media protection manager for a given media pipeline.\n */\n msSetMediaProtectionManager(mediaProtectionManager?: any): void;\n /**\n * Pauses the current playback and sets paused to TRUE. This can be used to test whether the media is playing or paused. You can also use the pause or play events to tell whether the media is playing or not.\n */\n pause(): void;\n /**\n * Loads and starts playback of a media resource.\n */\n play(): Promise;\n setMediaKeys(mediaKeys: MediaKeys | null): Promise;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n addEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMediaElement, ev: HTMLMediaElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMediaElement: {\n prototype: HTMLMediaElement;\n new(): HTMLMediaElement;\n readonly HAVE_CURRENT_DATA: number;\n readonly HAVE_ENOUGH_DATA: number;\n readonly HAVE_FUTURE_DATA: number;\n readonly HAVE_METADATA: number;\n readonly HAVE_NOTHING: number;\n readonly NETWORK_EMPTY: number;\n readonly NETWORK_IDLE: number;\n readonly NETWORK_LOADING: number;\n readonly NETWORK_NO_SOURCE: number;\n};\n\ninterface HTMLMenuElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n type: string;\n addEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMenuElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMenuElement: {\n prototype: HTMLMenuElement;\n new(): HTMLMenuElement;\n};\n\ninterface HTMLMetaElement extends HTMLElement {\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n /**\n * Gets or sets meta-information to associate with httpEquiv or name.\n */\n content: string;\n /**\n * Gets or sets information used to bind the value of a content attribute of a meta element to an HTTP response header.\n */\n httpEquiv: string;\n /**\n * Sets or retrieves the value specified in the content attribute of the meta object.\n */\n name: string;\n /**\n * Sets or retrieves a scheme to be used in interpreting the value of a property specified for the object.\n */\n /** @deprecated */\n scheme: string;\n /**\n * Sets or retrieves the URL property that will be loaded after the specified time has elapsed.\n */\n /** @deprecated */\n url: string;\n addEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMetaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMetaElement: {\n prototype: HTMLMetaElement;\n new(): HTMLMetaElement;\n};\n\ninterface HTMLMeterElement extends HTMLElement {\n high: number;\n readonly labels: NodeListOf;\n low: number;\n max: number;\n min: number;\n optimum: number;\n value: number;\n addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLMeterElement: {\n prototype: HTMLMeterElement;\n new(): HTMLMeterElement;\n};\n\ninterface HTMLModElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n /**\n * Sets or retrieves the date and time of a modification to the object.\n */\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLModElement: {\n prototype: HTMLModElement;\n new(): HTMLModElement;\n};\n\ninterface HTMLOListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /**\n * The starting number.\n */\n start: number;\n type: string;\n addEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOListElement: {\n prototype: HTMLOListElement;\n new(): HTMLOListElement;\n};\n\ninterface HTMLObjectElement extends HTMLElement, GetSVGDocument {\n /**\n * Retrieves a string of the URL where the object tag can be found. This is often the href of the document that the object is in, or the value set by a base element.\n */\n readonly BaseHref: string;\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a character string that can be used to implement your own archive functionality for the object.\n */\n /** @deprecated */\n archive: string;\n /** @deprecated */\n border: string;\n /**\n * Sets or retrieves the URL of the file containing the compiled Java class.\n */\n /** @deprecated */\n code: string;\n /**\n * Sets or retrieves the URL of the component.\n */\n /** @deprecated */\n codeBase: string;\n /**\n * Sets or retrieves the Internet media type for the code associated with the object.\n */\n /** @deprecated */\n codeType: string;\n /**\n * Retrieves the document object of the page or frame.\n */\n readonly contentDocument: Document | null;\n /**\n * Sets or retrieves the URL that references the data of the object.\n */\n data: string;\n /** @deprecated */\n declare: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the height of the object.\n */\n height: string;\n /** @deprecated */\n hspace: number;\n /**\n * Gets or sets whether the DLNA PlayTo device is available.\n */\n msPlayToDisabled: boolean;\n /**\n * Gets or sets the path to the preferred media source. This enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.\n */\n msPlayToPreferredSourceUri: string;\n /**\n * Gets or sets the primary DLNA PlayTo device.\n */\n msPlayToPrimary: boolean;\n /**\n * Gets the source associated with the media element for use by the PlayToManager.\n */\n readonly msPlayToSource: any;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly readyState: number;\n /**\n * Sets or retrieves a message to be displayed while an object is loading.\n */\n /** @deprecated */\n standby: string;\n /**\n * Sets or retrieves the MIME type of the object.\n */\n type: string;\n typemustmatch: boolean;\n /**\n * Sets or retrieves the URL, often with a bookmark extension (#name), to use as a client-side image map.\n */\n useMap: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /** @deprecated */\n vspace: number;\n /**\n * Sets or retrieves the width of the object.\n */\n width: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLObjectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLObjectElement: {\n prototype: HTMLObjectElement;\n new(): HTMLObjectElement;\n};\n\ninterface HTMLOptGroupElement extends HTMLElement {\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptGroupElement: {\n prototype: HTMLOptGroupElement;\n new(): HTMLOptGroupElement;\n};\n\ninterface HTMLOptionElement extends HTMLElement {\n /**\n * Sets or retrieves the status of an option.\n */\n defaultSelected: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n /**\n * Sets or retrieves the ordinal position of an option in a list box.\n */\n readonly index: number;\n /**\n * Sets or retrieves a value that you can use to implement your own label functionality for the object.\n */\n label: string;\n /**\n * Sets or retrieves whether the option in the list box is the default item.\n */\n selected: boolean;\n /**\n * Sets or retrieves the text string specified by the option tag.\n */\n text: string;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOptionElement: {\n prototype: HTMLOptionElement;\n new(): HTMLOptionElement;\n};\n\ninterface HTMLOptionsCollection extends HTMLCollectionOf {\n /**\n * Returns the number of elements in the collection.\n * When set to a smaller number, truncates the number of option elements in the corresponding container.\n * When set to a greater number, adds new blank option elements to that container.\n */\n length: number;\n /**\n * Returns the index of the first selected item, if any, or −1 if there is no selected\n * item.\n * Can be set, to change the selection.\n */\n selectedIndex: number;\n /**\n * Inserts element before the node given by before.\n * The before argument can be a number, in which case element is inserted before the item with that number, or an element from the\n * collection, in which case element is inserted before that element.\n * If before is omitted, null, or a number out of range, then element will be added at the end of the list.\n * This method will throw a \"HierarchyRequestError\" DOMException if\n * element is an ancestor of the element into which it is to be inserted.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void;\n /**\n * Removes the item with index index from the collection.\n */\n remove(index: number): void;\n}\n\ndeclare var HTMLOptionsCollection: {\n prototype: HTMLOptionsCollection;\n new(): HTMLOptionsCollection;\n};\n\ninterface HTMLOutputElement extends HTMLElement {\n defaultValue: string;\n readonly form: HTMLFormElement | null;\n readonly htmlFor: DOMTokenList;\n readonly labels: NodeListOf;\n name: string;\n readonly type: string;\n readonly validationMessage: string;\n readonly validity: ValidityState;\n value: string;\n readonly willValidate: boolean;\n checkValidity(): boolean;\n reportValidity(): boolean;\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLOutputElement: {\n prototype: HTMLOutputElement;\n new(): HTMLOutputElement;\n};\n\ninterface HTMLParagraphElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n clear: string;\n addEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParagraphElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParagraphElement: {\n prototype: HTMLParagraphElement;\n new(): HTMLParagraphElement;\n};\n\ninterface HTMLParamElement extends HTMLElement {\n /**\n * Sets or retrieves the name of an input parameter for an element.\n */\n name: string;\n /**\n * Sets or retrieves the content type of the resource designated by the value attribute.\n */\n /** @deprecated */\n type: string;\n /**\n * Sets or retrieves the value of an input parameter for an element.\n */\n value: string;\n /**\n * Sets or retrieves the data type of the value attribute.\n */\n /** @deprecated */\n valueType: string;\n addEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLParamElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLParamElement: {\n prototype: HTMLParamElement;\n new(): HTMLParamElement;\n};\n\ninterface HTMLPictureElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPictureElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPictureElement: {\n prototype: HTMLPictureElement;\n new(): HTMLPictureElement;\n};\n\ninterface HTMLPreElement extends HTMLElement {\n /**\n * Sets or gets a value that you can use to implement your own width functionality for the object.\n */\n /** @deprecated */\n width: number;\n addEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLPreElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLPreElement: {\n prototype: HTMLPreElement;\n new(): HTMLPreElement;\n};\n\ninterface HTMLProgressElement extends HTMLElement {\n readonly labels: NodeListOf;\n /**\n * Defines the maximum, or \"done\" value for a progress element.\n */\n max: number;\n /**\n * Returns the quotient of value/max when the value attribute is set (determinate progress bar), or -1 when the value attribute is missing (indeterminate progress bar).\n */\n readonly position: number;\n /**\n * Sets or gets the current value of a progress element. The value must be a non-negative number between 0 and the max value.\n */\n value: number;\n addEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLProgressElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLProgressElement: {\n prototype: HTMLProgressElement;\n new(): HTMLProgressElement;\n};\n\ninterface HTMLQuoteElement extends HTMLElement {\n /**\n * Sets or retrieves reference information about the object.\n */\n cite: string;\n addEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLQuoteElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLQuoteElement: {\n prototype: HTMLQuoteElement;\n new(): HTMLQuoteElement;\n};\n\ninterface HTMLScriptElement extends HTMLElement {\n async: boolean;\n /**\n * Sets or retrieves the character set used to encode the object.\n */\n /** @deprecated */\n charset: string;\n crossOrigin: string | null;\n /**\n * Sets or retrieves the status of the script.\n */\n defer: boolean;\n /**\n * Sets or retrieves the event for which the script is written.\n */\n /** @deprecated */\n event: string;\n /**\n * Sets or retrieves the object that is bound to the event script.\n */\n /** @deprecated */\n htmlFor: string;\n integrity: string;\n noModule: boolean;\n /**\n * Retrieves the URL to an external file that contains the source code or data.\n */\n src: string;\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n /**\n * Sets or retrieves the MIME type for the associated scripting engine.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLScriptElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLScriptElement: {\n prototype: HTMLScriptElement;\n new(): HTMLScriptElement;\n};\n\ninterface HTMLSelectElement extends HTMLElement {\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the number of objects in a collection.\n */\n length: number;\n /**\n * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list.\n */\n multiple: boolean;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n readonly options: HTMLOptionsCollection;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the index of the selected option in a select object.\n */\n selectedIndex: number;\n readonly selectedOptions: HTMLCollectionOf;\n /**\n * Sets or retrieves the number of rows in the list box.\n */\n size: number;\n /**\n * Retrieves the type of select control based on the value of the MULTIPLE attribute.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Sets or retrieves the value which is returned to the server when the form control is submitted.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Adds an element to the areas, controlRange, or options collection.\n * @param element Variant of type Number that specifies the index position in the collection where the element is placed. If no value is given, the method places the element at the end of the collection.\n * @param before Variant of type Object that specifies an element to insert before, or null to append the object to the collection.\n */\n add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number): void;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param name Variant of type Number or String that specifies the object or collection to retrieve. If this parameter is an integer, it is the zero-based index of the object. If this parameter is a string, all objects with matching name or id properties are retrieved, and a collection is returned if more than one match is made.\n * @param index Variant of type Number that specifies the zero-based index of the object to retrieve when a collection is returned.\n */\n item(index: number): Element | null;\n /**\n * Retrieves a select object or an object from an options collection.\n * @param namedItem A String that specifies the name or id property of the object to retrieve. A collection is returned if more than one match is made.\n */\n namedItem(name: string): HTMLOptionElement | null;\n /**\n * Removes an element from the collection.\n * @param index Number that specifies the zero-based index of the element to remove from the collection.\n */\n remove(): void;\n remove(index: number): void;\n reportValidity(): boolean;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n addEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSelectElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: Element;\n}\n\ndeclare var HTMLSelectElement: {\n prototype: HTMLSelectElement;\n new(): HTMLSelectElement;\n};\n\ninterface HTMLSlotElement extends HTMLElement {\n name: string;\n assignedNodes(options?: AssignedNodesOptions): Node[];\n addEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSlotElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface HTMLSourceElement extends HTMLElement {\n /**\n * Gets or sets the intended media type of the media source.\n */\n media: string;\n /** @deprecated */\n msKeySystem: string;\n sizes: string;\n /**\n * The address or URL of the a media resource that is to be considered.\n */\n src: string;\n srcset: string;\n /**\n * Gets or sets the MIME type of a media resource.\n */\n type: string;\n addEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSourceElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSourceElement: {\n prototype: HTMLSourceElement;\n new(): HTMLSourceElement;\n};\n\ninterface HTMLSpanElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSpanElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSpanElement: {\n prototype: HTMLSpanElement;\n new(): HTMLSpanElement;\n};\n\ninterface HTMLStyleElement extends HTMLElement, LinkStyle {\n /** @deprecated */\n disabled: boolean;\n /**\n * Sets or retrieves the media type.\n */\n media: string;\n /**\n * Retrieves the CSS language in which the style sheet is written.\n */\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLStyleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLStyleElement: {\n prototype: HTMLStyleElement;\n new(): HTMLStyleElement;\n};\n\ninterface HTMLSummaryElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLSummaryElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLSummaryElement: {\n prototype: HTMLSummaryElement;\n new(): HTMLSummaryElement;\n};\n\ninterface HTMLTableCaptionElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the caption or legend.\n */\n /** @deprecated */\n align: string;\n addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCaptionElement: {\n prototype: HTMLTableCaptionElement;\n new(): HTMLTableCaptionElement;\n};\n\ninterface HTMLTableCellElement extends HTMLElement {\n /**\n * Sets or retrieves abbreviated text for the object.\n */\n abbr: string;\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /**\n * Sets or retrieves a comma-delimited list of conceptual categories associated with the object.\n */\n /** @deprecated */\n axis: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves the position of the object in the cells collection of a row.\n */\n readonly cellIndex: number;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number columns in the table that the object should span.\n */\n colSpan: number;\n /**\n * Sets or retrieves a list of header cells that provide information for the object.\n */\n headers: string;\n /**\n * Sets or retrieves the height of the object.\n */\n /** @deprecated */\n height: string;\n /**\n * Sets or retrieves whether the browser automatically performs wordwrap.\n */\n /** @deprecated */\n noWrap: boolean;\n /**\n * Sets or retrieves how many rows in a table the cell should span.\n */\n rowSpan: number;\n /**\n * Sets or retrieves the group of cells in a table to which the object's information applies.\n */\n scope: string;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableCellElement: {\n prototype: HTMLTableCellElement;\n new(): HTMLTableCellElement;\n};\n\ninterface HTMLTableColElement extends HTMLElement {\n /**\n * Sets or retrieves the alignment of the object relative to the display or table.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of columns in the group.\n */\n span: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n addEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableColElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableColElement: {\n prototype: HTMLTableColElement;\n new(): HTMLTableColElement;\n};\n\ninterface HTMLTableDataCellElement extends HTMLTableCellElement {\n addEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableDataCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableDataCellElement: {\n prototype: HTMLTableDataCellElement;\n new(): HTMLTableDataCellElement;\n};\n\ninterface HTMLTableElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Sets or retrieves the width of the border to draw around the object.\n */\n /** @deprecated */\n border: string;\n /**\n * Retrieves the caption object of a table.\n */\n caption: HTMLTableCaptionElement | null;\n /**\n * Sets or retrieves the amount of space between the border of the cell and the content of the cell.\n */\n /** @deprecated */\n cellPadding: string;\n /**\n * Sets or retrieves the amount of space between cells in a table.\n */\n /** @deprecated */\n cellSpacing: string;\n /**\n * Sets or retrieves the way the border frame around the table is displayed.\n */\n /** @deprecated */\n frame: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /**\n * Sets or retrieves which dividing lines (inner borders) are displayed.\n */\n /** @deprecated */\n rules: string;\n /**\n * Sets or retrieves a description and/or structure of the object.\n */\n /** @deprecated */\n summary: string;\n /**\n * Retrieves a collection of all tBody objects in the table. Objects in this collection are in source order.\n */\n readonly tBodies: HTMLCollectionOf;\n /**\n * Retrieves the tFoot object of the table.\n */\n tFoot: HTMLTableSectionElement | null;\n /**\n * Retrieves the tHead object of the table.\n */\n tHead: HTMLTableSectionElement | null;\n /**\n * Sets or retrieves the width of the object.\n */\n /** @deprecated */\n width: string;\n /**\n * Creates an empty caption element in the table.\n */\n createCaption(): HTMLTableCaptionElement;\n /**\n * Creates an empty tBody element in the table.\n */\n createTBody(): HTMLTableSectionElement;\n /**\n * Creates an empty tFoot element in the table.\n */\n createTFoot(): HTMLTableSectionElement;\n /**\n * Returns the tHead element object if successful, or null otherwise.\n */\n createTHead(): HTMLTableSectionElement;\n /**\n * Deletes the caption element and its contents from the table.\n */\n deleteCaption(): void;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Deletes the tFoot element and its contents from the table.\n */\n deleteTFoot(): void;\n /**\n * Deletes the tHead element and its contents from the table.\n */\n deleteTHead(): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableElement: {\n prototype: HTMLTableElement;\n new(): HTMLTableElement;\n};\n\ninterface HTMLTableHeaderCellElement extends HTMLTableCellElement {\n scope: string;\n addEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableHeaderCellElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableHeaderCellElement: {\n prototype: HTMLTableHeaderCellElement;\n new(): HTMLTableHeaderCellElement;\n};\n\ninterface HTMLTableRowElement extends HTMLElement {\n /**\n * Sets or retrieves how the object is aligned with adjacent text.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n bgColor: string;\n /**\n * Retrieves a collection of all cells in the table row.\n */\n readonly cells: HTMLCollectionOf;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Retrieves the position of the object in the rows collection for the table.\n */\n readonly rowIndex: number;\n /**\n * Retrieves the position of the object in the collection.\n */\n readonly sectionRowIndex: number;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified cell from the table row, as well as from the cells collection.\n * @param index Number that specifies the zero-based position of the cell to remove from the table row. If no value is provided, the last cell in the cells collection is deleted.\n */\n deleteCell(index?: number): void;\n /**\n * Creates a new cell in the table row, and adds the cell to the cells collection.\n * @param index Number that specifies where to insert the cell in the tr. The default value is -1, which appends the new cell to the end of the cells collection.\n */\n insertCell(index?: number): HTMLTableDataCellElement;\n addEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableRowElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableRowElement: {\n prototype: HTMLTableRowElement;\n new(): HTMLTableRowElement;\n};\n\ninterface HTMLTableSectionElement extends HTMLElement {\n /**\n * Sets or retrieves a value that indicates the table alignment.\n */\n /** @deprecated */\n align: string;\n /** @deprecated */\n ch: string;\n /** @deprecated */\n chOff: string;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n readonly rows: HTMLCollectionOf;\n /** @deprecated */\n vAlign: string;\n /**\n * Removes the specified row (tr) from the element and from the rows collection.\n * @param index Number that specifies the zero-based position in the rows collection of the row to remove.\n */\n deleteRow(index?: number): void;\n /**\n * Creates a new row (tr) in the table, and adds the row to the rows collection.\n * @param index Number that specifies where to insert the row in the rows collection. The default value is -1, which appends the new row to the end of the rows collection.\n */\n insertRow(index?: number): HTMLTableRowElement;\n addEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTableSectionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTableSectionElement: {\n prototype: HTMLTableSectionElement;\n new(): HTMLTableSectionElement;\n};\n\ninterface HTMLTemplateElement extends HTMLElement {\n readonly content: DocumentFragment;\n addEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTemplateElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTemplateElement: {\n prototype: HTMLTemplateElement;\n new(): HTMLTemplateElement;\n};\n\ninterface HTMLTextAreaElement extends HTMLElement {\n autocomplete: string;\n /**\n * Provides a way to direct a user to a specific field when a document loads. This can provide both direction and convenience for a user, reducing the need to click or tab to a field when a page opens. This attribute is true when present on an element, and false when missing.\n */\n autofocus: boolean;\n /**\n * Sets or retrieves the width of the object.\n */\n cols: number;\n /**\n * Sets or retrieves the initial contents of the object.\n */\n defaultValue: string;\n dirName: string;\n disabled: boolean;\n /**\n * Retrieves a reference to the form that the object is embedded in.\n */\n readonly form: HTMLFormElement | null;\n readonly labels: NodeListOf;\n /**\n * Sets or retrieves the maximum number of characters that the user can enter in a text control.\n */\n maxLength: number;\n minLength: number;\n /**\n * Sets or retrieves the name of the object.\n */\n name: string;\n /**\n * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field.\n */\n placeholder: string;\n /**\n * Sets or retrieves the value indicated whether the content of the object is read-only.\n */\n readOnly: boolean;\n /**\n * When present, marks an element that can't be submitted without a value.\n */\n required: boolean;\n /**\n * Sets or retrieves the number of horizontal rows contained in the object.\n */\n rows: number;\n selectionDirection: string;\n /**\n * Gets or sets the end position or offset of a text selection.\n */\n selectionEnd: number;\n /**\n * Gets or sets the starting position or offset of a text selection.\n */\n selectionStart: number;\n readonly textLength: number;\n /**\n * Retrieves the type of control.\n */\n readonly type: string;\n /**\n * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as \"this is a required field\". The result is that the user sees validation messages without actually submitting.\n */\n readonly validationMessage: string;\n /**\n * Returns a ValidityState object that represents the validity states of an element.\n */\n readonly validity: ValidityState;\n /**\n * Retrieves or sets the text in the entry field of the textArea element.\n */\n value: string;\n /**\n * Returns whether an element will successfully validate based on forms validation rules and constraints.\n */\n readonly willValidate: boolean;\n /**\n * Sets or retrieves how to handle wordwrapping in the object.\n */\n wrap: string;\n /**\n * Returns whether a form will validate when it is submitted, without having to submit it.\n */\n checkValidity(): boolean;\n reportValidity(): boolean;\n /**\n * Highlights the input area of a form element.\n */\n select(): void;\n /**\n * Sets a custom error message that is displayed when a form is submitted.\n * @param error Sets a custom error message that is displayed when a form is submitted.\n */\n setCustomValidity(error: string): void;\n setRangeText(replacement: string): void;\n setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void;\n /**\n * Sets the start and end positions of a selection in a text field.\n * @param start The offset into the text field for the start of the selection.\n * @param end The offset into the text field for the end of the selection.\n * @param direction The direction in which the selection is performed.\n */\n setSelectionRange(start: number, end: number, direction?: \"forward\" | \"backward\" | \"none\"): void;\n addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTextAreaElement: {\n prototype: HTMLTextAreaElement;\n new(): HTMLTextAreaElement;\n};\n\ninterface HTMLTimeElement extends HTMLElement {\n dateTime: string;\n addEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTimeElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTimeElement: {\n prototype: HTMLTimeElement;\n new(): HTMLTimeElement;\n};\n\ninterface HTMLTitleElement extends HTMLElement {\n /**\n * Retrieves or sets the text of the object as a string.\n */\n text: string;\n addEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTitleElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTitleElement: {\n prototype: HTMLTitleElement;\n new(): HTMLTitleElement;\n};\n\ninterface HTMLTrackElement extends HTMLElement {\n default: boolean;\n kind: string;\n label: string;\n readonly readyState: number;\n src: string;\n srclang: string;\n readonly track: TextTrack;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n addEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLTrackElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLTrackElement: {\n prototype: HTMLTrackElement;\n new(): HTMLTrackElement;\n readonly ERROR: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n};\n\ninterface HTMLUListElement extends HTMLElement {\n /** @deprecated */\n compact: boolean;\n /** @deprecated */\n type: string;\n addEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUListElement: {\n prototype: HTMLUListElement;\n new(): HTMLUListElement;\n};\n\ninterface HTMLUnknownElement extends HTMLElement {\n addEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLUnknownElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLUnknownElement: {\n prototype: HTMLUnknownElement;\n new(): HTMLUnknownElement;\n};\n\ninterface HTMLVideoElementEventMap extends HTMLMediaElementEventMap {\n \"MSVideoFormatChanged\": Event;\n \"MSVideoFrameStepCompleted\": Event;\n \"MSVideoOptimalLayoutChanged\": Event;\n}\n\ninterface HTMLVideoElement extends HTMLMediaElement {\n /**\n * Gets or sets the height of the video element.\n */\n height: number;\n msHorizontalMirror: boolean;\n readonly msIsLayoutOptimalForPlayback: boolean;\n readonly msIsStereo3D: boolean;\n msStereo3DPackingMode: string;\n msStereo3DRenderMode: string;\n msZoom: boolean;\n onMSVideoFormatChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoFrameStepCompleted: ((this: HTMLVideoElement, ev: Event) => any) | null;\n onMSVideoOptimalLayoutChanged: ((this: HTMLVideoElement, ev: Event) => any) | null;\n /**\n * Gets or sets a URL of an image to display, for example, like a movie poster. This can be a still frame from the video, or another image if no video data is available.\n */\n poster: string;\n /**\n * Gets the intrinsic height of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoHeight: number;\n /**\n * Gets the intrinsic width of a video in CSS pixels, or zero if the dimensions are not known.\n */\n readonly videoWidth: number;\n readonly webkitDisplayingFullscreen: boolean;\n readonly webkitSupportsFullscreen: boolean;\n /**\n * Gets or sets the width of the video element.\n */\n width: number;\n getVideoPlaybackQuality(): VideoPlaybackQuality;\n msFrameStep(forward: boolean): void;\n msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config?: any): void;\n msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void;\n webkitEnterFullScreen(): void;\n webkitEnterFullscreen(): void;\n webkitExitFullScreen(): void;\n webkitExitFullscreen(): void;\n addEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: HTMLVideoElement, ev: HTMLVideoElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var HTMLVideoElement: {\n prototype: HTMLVideoElement;\n new(): HTMLVideoElement;\n};\n\ninterface HashChangeEvent extends Event {\n readonly newURL: string;\n readonly oldURL: string;\n}\n\ndeclare var HashChangeEvent: {\n prototype: HashChangeEvent;\n new(type: string, eventInitDict?: HashChangeEventInit): HashChangeEvent;\n};\n\ninterface Headers {\n append(name: string, value: string): void;\n delete(name: string): void;\n get(name: string): string | null;\n has(name: string): boolean;\n set(name: string, value: string): void;\n forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;\n}\n\ndeclare var Headers: {\n prototype: Headers;\n new(init?: HeadersInit): Headers;\n};\n\ninterface History {\n readonly length: number;\n scrollRestoration: ScrollRestoration;\n readonly state: any;\n back(distance?: any): void;\n forward(distance?: any): void;\n go(delta?: any): void;\n pushState(data: any, title?: string, url?: string | null): void;\n replaceState(data: any, title?: string, url?: string | null): void;\n}\n\ndeclare var History: {\n prototype: History;\n new(): History;\n};\n\ninterface HkdfCtrParams extends Algorithm {\n context: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n hash: string | Algorithm;\n label: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer;\n}\n\ninterface IDBArrayKey extends Array {\n}\n\ninterface IDBCursor {\n /**\n * Returns the direction (\"next\", \"nextunique\", \"prev\" or \"prevunique\")\n * of the cursor.\n */\n readonly direction: IDBCursorDirection;\n /**\n * Returns the key of the cursor.\n * Throws a \"InvalidStateError\" DOMException if the cursor is advancing or is finished.\n */\n readonly key: IDBValidKey | IDBKeyRange;\n /**\n * Returns the effective key of the cursor.\n * Throws a \"InvalidStateError\" DOMException if the cursor is advancing or is finished.\n */\n readonly primaryKey: IDBValidKey | IDBKeyRange;\n /**\n * Returns the IDBObjectStore or IDBIndex the cursor was opened from.\n */\n readonly source: IDBObjectStore | IDBIndex;\n /**\n * Advances the cursor through the next count records in\n * range.\n */\n advance(count: number): void;\n /**\n * Advances the cursor to the next record in range matching or\n * after key.\n */\n continue(key?: IDBValidKey | IDBKeyRange): void;\n /**\n * Advances the cursor to the next record in range matching\n * or after key and primaryKey. Throws an \"InvalidAccessError\" DOMException if the source is not an index.\n */\n continuePrimaryKey(key: IDBValidKey | IDBKeyRange, primaryKey: IDBValidKey | IDBKeyRange): void;\n /**\n * Delete the record pointed at by the cursor with a new value.\n * If successful, request's result will be undefined.\n */\n delete(): IDBRequest;\n /**\n * Updated the record pointed at by the cursor with a new value.\n * Throws a \"DataError\" DOMException if the effective object store uses in-line keys and the key would have changed.\n * If successful, request's result will be the record's key.\n */\n update(value: any): IDBRequest;\n}\n\ndeclare var IDBCursor: {\n prototype: IDBCursor;\n new(): IDBCursor;\n};\n\ninterface IDBCursorWithValue extends IDBCursor {\n /**\n * Returns the cursor's current value.\n */\n readonly value: any;\n}\n\ndeclare var IDBCursorWithValue: {\n prototype: IDBCursorWithValue;\n new(): IDBCursorWithValue;\n};\n\ninterface IDBDatabaseEventMap {\n \"abort\": Event;\n \"close\": Event;\n \"error\": Event;\n \"versionchange\": IDBVersionChangeEvent;\n}\n\ninterface IDBDatabase extends EventTarget {\n /**\n * Returns the name of the database.\n */\n readonly name: string;\n /**\n * Returns a list of the names of object stores in the database.\n */\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBDatabase, ev: Event) => any) | null;\n onclose: ((this: IDBDatabase, ev: Event) => any) | null;\n onerror: ((this: IDBDatabase, ev: Event) => any) | null;\n onversionchange: ((this: IDBDatabase, ev: IDBVersionChangeEvent) => any) | null;\n /**\n * Returns the version of the database.\n */\n readonly version: number;\n /**\n * Closes the connection once all running transactions have finished.\n */\n close(): void;\n /**\n * Creates a new object store with the given name and options and returns a new IDBObjectStore.\n * Throws a \"InvalidStateError\" DOMException if not called within an upgrade transaction.\n */\n createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;\n /**\n * Deletes the object store with the given name.\n * Throws a \"InvalidStateError\" DOMException if not called within an upgrade transaction.\n */\n deleteObjectStore(name: string): void;\n /**\n * Returns a new transaction with the given mode (\"readonly\" or \"readwrite\")\n * and scope which can be a single object store name or an array of names.\n */\n transaction(storeNames: string | string[], mode?: IDBTransactionMode): IDBTransaction;\n addEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBDatabase, ev: IDBDatabaseEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBDatabase: {\n prototype: IDBDatabase;\n new(): IDBDatabase;\n};\n\ninterface IDBEnvironment {\n readonly indexedDB: IDBFactory;\n}\n\ninterface IDBFactory {\n /**\n * Compares two values as keys. Returns -1 if key1 precedes key2, 1 if key2 precedes key1, and 0 if\n * the keys are equal.\n * Throws a \"DataError\" DOMException if either input is not a valid key.\n */\n cmp(first: any, second: any): number;\n /**\n * Attempts to delete the named database. If the\n * database already exists and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close. If the request\n * is successful request's result will be null.\n */\n deleteDatabase(name: string): IDBOpenDBRequest;\n /**\n * Attempts to open a connection to the named database with the specified version. If the database already exists\n * with a lower version and there are open connections that don't close in response to a versionchange event, the request will be blocked until all they close, then an upgrade\n * will occur. If the database already exists with a higher\n * version the request will fail. If the request is\n * successful request's result will\n * be the connection.\n */\n open(name: string, version?: number): IDBOpenDBRequest;\n}\n\ndeclare var IDBFactory: {\n prototype: IDBFactory;\n new(): IDBFactory;\n};\n\ninterface IDBIndex {\n readonly keyPath: string | string[];\n readonly multiEntry: boolean;\n /**\n * Updates the name of the store to newName.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n name: string;\n /**\n * Returns the IDBObjectStore the index belongs to.\n */\n readonly objectStore: IDBObjectStore;\n readonly unique: boolean;\n /**\n * Retrieves the number of records matching the given key or key range in query.\n * If successful, request's result will be the\n * count.\n */\n count(key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the value of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the value, or undefined if there was no matching record.\n */\n get(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the values of the records matching the given key or key range in query (up to count if given).\n * If successful, request's result will be an Array of the values.\n */\n getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the keys of records matching the given key or key range in query (up to count if given).\n * If successful, request's result will be an Array of the keys.\n */\n getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the key of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the key, or undefined if there was no matching record.\n */\n getKey(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Opens a cursor over the records matching query,\n * ordered by direction. If query is null, all records in index are matched.\n * If successful, request's result will be an IDBCursorWithValue, or null if there were no matching records.\n */\n openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n /**\n * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in index are matched.\n * If successful, request's result will be an IDBCursor, or null if there were no matching records.\n */\n openKeyCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n}\n\ndeclare var IDBIndex: {\n prototype: IDBIndex;\n new(): IDBIndex;\n};\n\ninterface IDBKeyRange {\n /**\n * Returns lower bound, or undefined if none.\n */\n readonly lower: any;\n /**\n * Returns true if the lower open flag is set, and false otherwise.\n */\n readonly lowerOpen: boolean;\n /**\n * Returns upper bound, or undefined if none.\n */\n readonly upper: any;\n /**\n * Returns true if the upper open flag is set, and false otherwise.\n */\n readonly upperOpen: boolean;\n /**\n * Returns true if key is included in the range, and false otherwise.\n */\n includes(key: any): boolean;\n}\n\ndeclare var IDBKeyRange: {\n prototype: IDBKeyRange;\n new(): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange spanning from lower to upper.\n * If lowerOpen is true, lower is not included in the range.\n * If upperOpen is true, upper is not included in the range.\n */\n bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange starting at key with no\n * upper bound. If open is true, key is not included in the\n * range.\n */\n lowerBound(lower: any, open?: boolean): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange spanning only key.\n */\n only(value: any): IDBKeyRange;\n /**\n * Returns a new IDBKeyRange with no lower bound and ending at key. If open is true, key is not included in the range.\n */\n upperBound(upper: any, open?: boolean): IDBKeyRange;\n};\n\ninterface IDBObjectStore {\n /**\n * Returns true if the store has a key generator, and false otherwise.\n */\n readonly autoIncrement: boolean;\n /**\n * Returns a list of the names of indexes in the store.\n */\n readonly indexNames: DOMStringList;\n /**\n * Returns the key path of the store, or null if none.\n */\n readonly keyPath: string | string[];\n /**\n * Updates the name of the store to newName.\n * Throws \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n name: string;\n /**\n * Returns the associated transaction.\n */\n readonly transaction: IDBTransaction;\n add(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Deletes all records in store.\n * If successful, request's result will\n * be undefined.\n */\n clear(): IDBRequest;\n /**\n * Retrieves the number of records matching the\n * given key or key range in query.\n * If successful, request's result will be the count.\n */\n count(key?: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be\n * satisfied with the data already in store the upgrade\n * transaction will abort with\n * a \"ConstraintError\" DOMException.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n createIndex(name: string, keyPath: string | string[], options?: IDBIndexParameters): IDBIndex;\n /**\n * Deletes records in store with the given key or in the given key range in query.\n * If successful, request's result will\n * be undefined.\n */\n delete(key: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Deletes the index in store with the given name.\n * Throws an \"InvalidStateError\" DOMException if not called within an upgrade\n * transaction.\n */\n deleteIndex(name: string): void;\n /**\n * Retrieves the value of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the value, or undefined if there was no matching record.\n */\n get(query: IDBValidKey | IDBKeyRange): IDBRequest;\n /**\n * Retrieves the values of the records matching the\n * given key or key range in query (up to count if given).\n * If successful, request's result will\n * be an Array of the values.\n */\n getAll(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the keys of records matching the\n * given key or key range in query (up to count if given).\n * If successful, request's result will\n * be an Array of the keys.\n */\n getAllKeys(query?: IDBValidKey | IDBKeyRange, count?: number): IDBRequest;\n /**\n * Retrieves the key of the first record matching the\n * given key or key range in query.\n * If successful, request's result will be the key, or undefined if there was no matching record.\n */\n getKey(query: IDBValidKey | IDBKeyRange): IDBRequest;\n index(name: string): IDBIndex;\n /**\n * Opens a cursor over the records matching query,\n * ordered by direction. If query is null, all records in store are matched.\n * If successful, request's result will be an IDBCursorWithValue pointing at the first matching record, or null if there were no matching records.\n */\n openCursor(range?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n /**\n * Opens a cursor with key only flag set over the records matching query, ordered by direction. If query is null, all records in store are matched.\n * If successful, request's result will be an IDBCursor pointing at the first matching record, or\n * null if there were no matching records.\n */\n openKeyCursor(query?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): IDBRequest;\n put(value: any, key?: IDBValidKey | IDBKeyRange): IDBRequest;\n}\n\ndeclare var IDBObjectStore: {\n prototype: IDBObjectStore;\n new(): IDBObjectStore;\n};\n\ninterface IDBOpenDBRequestEventMap extends IDBRequestEventMap {\n \"blocked\": Event;\n \"upgradeneeded\": IDBVersionChangeEvent;\n}\n\ninterface IDBOpenDBRequest extends IDBRequest {\n onblocked: ((this: IDBOpenDBRequest, ev: Event) => any) | null;\n onupgradeneeded: ((this: IDBOpenDBRequest, ev: IDBVersionChangeEvent) => any) | null;\n addEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBOpenDBRequest, ev: IDBOpenDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBOpenDBRequest: {\n prototype: IDBOpenDBRequest;\n new(): IDBOpenDBRequest;\n};\n\ninterface IDBRequestEventMap {\n \"error\": Event;\n \"success\": Event;\n}\n\ninterface IDBRequest extends EventTarget {\n /**\n * When a request is completed, returns the error (a DOMException), or null if the request succeeded. Throws\n * a \"InvalidStateError\" DOMException if the request is still pending.\n */\n readonly error: DOMException | null;\n onerror: ((this: IDBRequest, ev: Event) => any) | null;\n onsuccess: ((this: IDBRequest, ev: Event) => any) | null;\n /**\n * Returns \"pending\" until a request is complete,\n * then returns \"done\".\n */\n readonly readyState: IDBRequestReadyState;\n /**\n * When a request is completed, returns the result,\n * or undefined if the request failed. Throws a\n * \"InvalidStateError\" DOMException if the request is still pending.\n */\n readonly result: any;\n /**\n * Returns the IDBObjectStore, IDBIndex, or IDBCursor the request was made against, or null if is was an open\n * request.\n */\n readonly source: IDBObjectStore | IDBIndex | IDBCursor;\n /**\n * Returns the IDBTransaction the request was made within.\n * If this as an open request, then it returns an upgrade transaction while it is running, or null otherwise.\n */\n readonly transaction: IDBTransaction | null;\n addEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBRequest, ev: IDBRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBRequest: {\n prototype: IDBRequest;\n new(): IDBRequest;\n};\n\ninterface IDBTransactionEventMap {\n \"abort\": Event;\n \"complete\": Event;\n \"error\": Event;\n}\n\ninterface IDBTransaction extends EventTarget {\n /**\n * Returns the transaction's connection.\n */\n readonly db: IDBDatabase;\n /**\n * If the transaction was aborted, returns the\n * error (a DOMException) providing the reason.\n */\n readonly error: DOMException;\n /**\n * Returns the mode the transaction was created with\n * (\"readonly\" or \"readwrite\"), or \"versionchange\" for\n * an upgrade transaction.\n */\n readonly mode: IDBTransactionMode;\n /**\n * Returns a list of the names of object stores in the\n * transaction's scope. For an upgrade transaction this is all object stores in the database.\n */\n readonly objectStoreNames: DOMStringList;\n onabort: ((this: IDBTransaction, ev: Event) => any) | null;\n oncomplete: ((this: IDBTransaction, ev: Event) => any) | null;\n onerror: ((this: IDBTransaction, ev: Event) => any) | null;\n /**\n * Aborts the transaction. All pending requests will fail with\n * a \"AbortError\" DOMException and all changes made to the database will be\n * reverted.\n */\n abort(): void;\n /**\n * Returns an IDBObjectStore in the transaction's scope.\n */\n objectStore(name: string): IDBObjectStore;\n addEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: IDBTransaction, ev: IDBTransactionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var IDBTransaction: {\n prototype: IDBTransaction;\n new(): IDBTransaction;\n};\n\ninterface IDBVersionChangeEvent extends Event {\n readonly newVersion: number | null;\n readonly oldVersion: number;\n}\n\ndeclare var IDBVersionChangeEvent: {\n prototype: IDBVersionChangeEvent;\n new(type: string, eventInitDict?: IDBVersionChangeEventInit): IDBVersionChangeEvent;\n};\n\ninterface IIRFilterNode extends AudioNode {\n getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;\n}\n\ndeclare var IIRFilterNode: {\n prototype: IIRFilterNode;\n new(context: BaseAudioContext, options: IIRFilterOptions): IIRFilterNode;\n};\n\ninterface ImageBitmap {\n readonly height: number;\n readonly width: number;\n close(): void;\n}\n\ninterface ImageBitmapOptions {\n colorSpaceConversion?: \"none\" | \"default\";\n imageOrientation?: \"none\" | \"flipY\";\n premultiplyAlpha?: \"none\" | \"premultiply\" | \"default\";\n resizeHeight?: number;\n resizeQuality?: \"pixelated\" | \"low\" | \"medium\" | \"high\";\n resizeWidth?: number;\n}\n\ninterface ImageData {\n readonly data: Uint8ClampedArray;\n readonly height: number;\n readonly width: number;\n}\n\ndeclare var ImageData: {\n prototype: ImageData;\n new(width: number, height: number): ImageData;\n new(array: Uint8ClampedArray, width: number, height: number): ImageData;\n};\n\ninterface IntersectionObserver {\n readonly root: Element | null;\n readonly rootMargin: string;\n readonly thresholds: number[];\n disconnect(): void;\n observe(target: Element): void;\n takeRecords(): IntersectionObserverEntry[];\n unobserve(target: Element): void;\n}\n\ndeclare var IntersectionObserver: {\n prototype: IntersectionObserver;\n new(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver;\n};\n\ninterface IntersectionObserverEntry {\n readonly boundingClientRect: ClientRect | DOMRect;\n readonly intersectionRatio: number;\n readonly intersectionRect: ClientRect | DOMRect;\n readonly isIntersecting: boolean;\n readonly rootBounds: ClientRect | DOMRect;\n readonly target: Element;\n readonly time: number;\n}\n\ndeclare var IntersectionObserverEntry: {\n prototype: IntersectionObserverEntry;\n new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry;\n};\n\ninterface KeyboardEvent extends UIEvent {\n readonly altKey: boolean;\n /** @deprecated */\n char: string;\n /** @deprecated */\n readonly charCode: number;\n readonly code: string;\n readonly ctrlKey: boolean;\n readonly key: string;\n /** @deprecated */\n readonly keyCode: number;\n readonly location: number;\n readonly metaKey: boolean;\n readonly repeat: boolean;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly which: number;\n getModifierState(keyArg: string): boolean;\n /** @deprecated */\n initKeyboardEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, keyArg: string, locationArg: number, modifiersListArg: string, repeat: boolean, locale: string): void;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n}\n\ndeclare var KeyboardEvent: {\n prototype: KeyboardEvent;\n new(typeArg: string, eventInitDict?: KeyboardEventInit): KeyboardEvent;\n readonly DOM_KEY_LOCATION_JOYSTICK: number;\n readonly DOM_KEY_LOCATION_LEFT: number;\n readonly DOM_KEY_LOCATION_MOBILE: number;\n readonly DOM_KEY_LOCATION_NUMPAD: number;\n readonly DOM_KEY_LOCATION_RIGHT: number;\n readonly DOM_KEY_LOCATION_STANDARD: number;\n};\n\ninterface KeyframeEffect extends AnimationEffect {\n composite: CompositeOperation;\n iterationComposite: IterationCompositeOperation;\n target: Element | null;\n getKeyframes(): ComputedKeyframe[];\n setKeyframes(keyframes: Keyframe[] | PropertyIndexedKeyframes | null): void;\n}\n\ndeclare var KeyframeEffect: {\n prototype: KeyframeEffect;\n new(target: Element | null, keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeEffectOptions): KeyframeEffect;\n new(source: KeyframeEffect): KeyframeEffect;\n};\n\ninterface LinkStyle {\n readonly sheet: StyleSheet | null;\n}\n\ninterface ListeningStateChangedEvent extends Event {\n readonly label: string;\n readonly state: ListeningState;\n}\n\ndeclare var ListeningStateChangedEvent: {\n prototype: ListeningStateChangedEvent;\n new(): ListeningStateChangedEvent;\n};\n\ninterface Location {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n assign(url: string): void;\n reload(forcedReload?: boolean): void;\n replace(url: string): void;\n toString(): string;\n}\n\ndeclare var Location: {\n prototype: Location;\n new(): Location;\n};\n\ninterface MSAssertion {\n readonly id: string;\n readonly type: MSCredentialType;\n}\n\ndeclare var MSAssertion: {\n prototype: MSAssertion;\n new(): MSAssertion;\n};\n\ninterface MSBlobBuilder {\n append(data: any, endings?: string): void;\n getBlob(contentType?: string): Blob;\n}\n\ndeclare var MSBlobBuilder: {\n prototype: MSBlobBuilder;\n new(): MSBlobBuilder;\n};\n\ninterface MSCredentials {\n getAssertion(challenge: string, filter?: MSCredentialFilter, params?: MSSignatureParameters): Promise;\n makeCredential(accountInfo: MSAccountInfo, params: MSCredentialParameters[], challenge?: string): Promise;\n}\n\ndeclare var MSCredentials: {\n prototype: MSCredentials;\n new(): MSCredentials;\n};\n\ninterface MSDCCEvent extends Event {\n readonly maxFr: number;\n readonly maxFs: number;\n}\n\ndeclare var MSDCCEvent: {\n prototype: MSDCCEvent;\n new(type: string, eventInitDict: MSDCCEventInit): MSDCCEvent;\n};\n\ninterface MSDSHEvent extends Event {\n readonly sources: number[];\n readonly timestamp: number;\n}\n\ndeclare var MSDSHEvent: {\n prototype: MSDSHEvent;\n new(type: string, eventInitDict: MSDSHEventInit): MSDSHEvent;\n};\n\ninterface MSFIDOCredentialAssertion extends MSAssertion {\n readonly algorithm: string | Algorithm;\n readonly attestation: any;\n readonly publicKey: string;\n readonly transportHints: MSTransportType[];\n}\n\ndeclare var MSFIDOCredentialAssertion: {\n prototype: MSFIDOCredentialAssertion;\n new(): MSFIDOCredentialAssertion;\n};\n\ninterface MSFIDOSignature {\n readonly authnrData: string;\n readonly clientData: string;\n readonly signature: string;\n}\n\ndeclare var MSFIDOSignature: {\n prototype: MSFIDOSignature;\n new(): MSFIDOSignature;\n};\n\ninterface MSFIDOSignatureAssertion extends MSAssertion {\n readonly signature: MSFIDOSignature;\n}\n\ndeclare var MSFIDOSignatureAssertion: {\n prototype: MSFIDOSignatureAssertion;\n new(): MSFIDOSignatureAssertion;\n};\n\ninterface MSFileSaver {\n msSaveBlob(blob: any, defaultName?: string): boolean;\n msSaveOrOpenBlob(blob: any, defaultName?: string): boolean;\n}\n\ninterface MSGesture {\n target: Element;\n addPointer(pointerId: number): void;\n stop(): void;\n}\n\ndeclare var MSGesture: {\n prototype: MSGesture;\n new(): MSGesture;\n};\n\ninterface MSGestureEvent extends UIEvent {\n readonly clientX: number;\n readonly clientY: number;\n readonly expansion: number;\n readonly gestureObject: any;\n readonly hwTimestamp: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly rotation: number;\n readonly scale: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly translationX: number;\n readonly translationY: number;\n readonly velocityAngular: number;\n readonly velocityExpansion: number;\n readonly velocityX: number;\n readonly velocityY: number;\n initGestureEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, offsetXArg: number, offsetYArg: number, translationXArg: number, translationYArg: number, scaleArg: number, expansionArg: number, rotationArg: number, velocityXArg: number, velocityYArg: number, velocityExpansionArg: number, velocityAngularArg: number, hwTimestampArg: number): void;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n}\n\ndeclare var MSGestureEvent: {\n prototype: MSGestureEvent;\n new(): MSGestureEvent;\n readonly MSGESTURE_FLAG_BEGIN: number;\n readonly MSGESTURE_FLAG_CANCEL: number;\n readonly MSGESTURE_FLAG_END: number;\n readonly MSGESTURE_FLAG_INERTIA: number;\n readonly MSGESTURE_FLAG_NONE: number;\n};\n\ninterface MSGraphicsTrust {\n readonly constrictionActive: boolean;\n readonly status: string;\n}\n\ndeclare var MSGraphicsTrust: {\n prototype: MSGraphicsTrust;\n new(): MSGraphicsTrust;\n};\n\ninterface MSInputMethodContextEventMap {\n \"MSCandidateWindowHide\": Event;\n \"MSCandidateWindowShow\": Event;\n \"MSCandidateWindowUpdate\": Event;\n}\n\ninterface MSInputMethodContext extends EventTarget {\n readonly compositionEndOffset: number;\n readonly compositionStartOffset: number;\n oncandidatewindowhide: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowshow: ((this: MSInputMethodContext, ev: Event) => any) | null;\n oncandidatewindowupdate: ((this: MSInputMethodContext, ev: Event) => any) | null;\n readonly target: HTMLElement;\n getCandidateWindowClientRect(): ClientRect;\n getCompositionAlternatives(): string[];\n hasComposition(): boolean;\n isCandidateWindowVisible(): boolean;\n addEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MSInputMethodContext, ev: MSInputMethodContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MSInputMethodContext: {\n prototype: MSInputMethodContext;\n new(): MSInputMethodContext;\n};\n\ninterface MSMediaKeyError {\n readonly code: number;\n readonly systemCode: number;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n}\n\ndeclare var MSMediaKeyError: {\n prototype: MSMediaKeyError;\n new(): MSMediaKeyError;\n readonly MS_MEDIA_KEYERR_CLIENT: number;\n readonly MS_MEDIA_KEYERR_DOMAIN: number;\n readonly MS_MEDIA_KEYERR_HARDWARECHANGE: number;\n readonly MS_MEDIA_KEYERR_OUTPUT: number;\n readonly MS_MEDIA_KEYERR_SERVICE: number;\n readonly MS_MEDIA_KEYERR_UNKNOWN: number;\n};\n\ninterface MSMediaKeyMessageEvent extends Event {\n readonly destinationURL: string | null;\n readonly message: Uint8Array;\n}\n\ndeclare var MSMediaKeyMessageEvent: {\n prototype: MSMediaKeyMessageEvent;\n new(): MSMediaKeyMessageEvent;\n};\n\ninterface MSMediaKeyNeededEvent extends Event {\n readonly initData: Uint8Array | null;\n}\n\ndeclare var MSMediaKeyNeededEvent: {\n prototype: MSMediaKeyNeededEvent;\n new(): MSMediaKeyNeededEvent;\n};\n\ninterface MSMediaKeySession extends EventTarget {\n readonly error: MSMediaKeyError | null;\n readonly keySystem: string;\n readonly sessionId: string;\n close(): void;\n update(key: Uint8Array): void;\n}\n\ndeclare var MSMediaKeySession: {\n prototype: MSMediaKeySession;\n new(): MSMediaKeySession;\n};\n\ninterface MSMediaKeys {\n readonly keySystem: string;\n createSession(type: string, initData: Uint8Array, cdmData?: Uint8Array | null): MSMediaKeySession;\n}\n\ndeclare var MSMediaKeys: {\n prototype: MSMediaKeys;\n new(keySystem: string): MSMediaKeys;\n isTypeSupported(keySystem: string, type?: string | null): boolean;\n isTypeSupportedWithFeatures(keySystem: string, type?: string | null): string;\n};\n\ninterface MSNavigatorDoNotTrack {\n confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean;\n confirmWebWideTrackingException(args: ExceptionInformation): boolean;\n removeSiteSpecificTrackingException(args: ExceptionInformation): void;\n removeWebWideTrackingException(args: ExceptionInformation): void;\n storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void;\n storeWebWideTrackingException(args: StoreExceptionsInformation): void;\n}\n\ninterface MSPointerEvent extends MouseEvent {\n readonly currentPoint: any;\n readonly height: number;\n readonly hwTimestamp: number;\n readonly intermediatePoints: any;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: any;\n readonly pressure: number;\n readonly rotation: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly width: number;\n getCurrentPoint(element: Element): void;\n getIntermediatePoints(element: Element): void;\n initPointerEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget, offsetXArg: number, offsetYArg: number, widthArg: number, heightArg: number, pressure: number, rotation: number, tiltX: number, tiltY: number, pointerIdArg: number, pointerType: any, hwTimestampArg: number, isPrimary: boolean): void;\n}\n\ndeclare var MSPointerEvent: {\n prototype: MSPointerEvent;\n new(typeArg: string, eventInitDict?: PointerEventInit): MSPointerEvent;\n};\n\ninterface MSStream {\n readonly type: string;\n msClose(): void;\n msDetachStream(): any;\n}\n\ndeclare var MSStream: {\n prototype: MSStream;\n new(): MSStream;\n};\n\ninterface MediaDeviceInfo {\n readonly deviceId: string;\n readonly groupId: string;\n readonly kind: MediaDeviceKind;\n readonly label: string;\n}\n\ndeclare var MediaDeviceInfo: {\n prototype: MediaDeviceInfo;\n new(): MediaDeviceInfo;\n};\n\ninterface MediaDevicesEventMap {\n \"devicechange\": Event;\n}\n\ninterface MediaDevices extends EventTarget {\n ondevicechange: ((this: MediaDevices, ev: Event) => any) | null;\n enumerateDevices(): Promise;\n getSupportedConstraints(): MediaTrackSupportedConstraints;\n getUserMedia(constraints: MediaStreamConstraints): Promise;\n addEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaDevices, ev: MediaDevicesEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaDevices: {\n prototype: MediaDevices;\n new(): MediaDevices;\n};\n\ninterface MediaElementAudioSourceNode extends AudioNode {\n readonly mediaElement: HTMLMediaElement;\n}\n\ndeclare var MediaElementAudioSourceNode: {\n prototype: MediaElementAudioSourceNode;\n new(context: AudioContext, options: MediaElementAudioSourceOptions): MediaElementAudioSourceNode;\n};\n\ninterface MediaEncryptedEvent extends Event {\n readonly initData: ArrayBuffer | null;\n readonly initDataType: string;\n}\n\ndeclare var MediaEncryptedEvent: {\n prototype: MediaEncryptedEvent;\n new(type: string, eventInitDict?: MediaEncryptedEventInit): MediaEncryptedEvent;\n};\n\ninterface MediaError {\n readonly code: number;\n readonly message: string;\n readonly msExtendedCode: number;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n}\n\ndeclare var MediaError: {\n prototype: MediaError;\n new(): MediaError;\n readonly MEDIA_ERR_ABORTED: number;\n readonly MEDIA_ERR_DECODE: number;\n readonly MEDIA_ERR_NETWORK: number;\n readonly MEDIA_ERR_SRC_NOT_SUPPORTED: number;\n readonly MS_MEDIA_ERR_ENCRYPTED: number;\n};\n\ninterface MediaKeyMessageEvent extends Event {\n readonly message: ArrayBuffer;\n readonly messageType: MediaKeyMessageType;\n}\n\ndeclare var MediaKeyMessageEvent: {\n prototype: MediaKeyMessageEvent;\n new(type: string, eventInitDict?: MediaKeyMessageEventInit): MediaKeyMessageEvent;\n};\n\ninterface MediaKeySession extends EventTarget {\n readonly closed: Promise;\n readonly expiration: number;\n readonly keyStatuses: MediaKeyStatusMap;\n readonly sessionId: string;\n close(): Promise;\n generateRequest(initDataType: string, initData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n load(sessionId: string): Promise;\n remove(): Promise;\n update(response: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeySession: {\n prototype: MediaKeySession;\n new(): MediaKeySession;\n};\n\ninterface MediaKeyStatusMap {\n readonly size: number;\n forEach(callback: Function, thisArg?: any): void;\n get(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): MediaKeyStatus;\n has(keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): boolean;\n}\n\ndeclare var MediaKeyStatusMap: {\n prototype: MediaKeyStatusMap;\n new(): MediaKeyStatusMap;\n};\n\ninterface MediaKeySystemAccess {\n readonly keySystem: string;\n createMediaKeys(): Promise;\n getConfiguration(): MediaKeySystemConfiguration;\n}\n\ndeclare var MediaKeySystemAccess: {\n prototype: MediaKeySystemAccess;\n new(): MediaKeySystemAccess;\n};\n\ninterface MediaKeys {\n createSession(sessionType?: MediaKeySessionType): MediaKeySession;\n setServerCertificate(serverCertificate: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): Promise;\n}\n\ndeclare var MediaKeys: {\n prototype: MediaKeys;\n new(): MediaKeys;\n};\n\ninterface MediaList {\n readonly length: number;\n mediaText: string;\n appendMedium(medium: string): void;\n deleteMedium(medium: string): void;\n item(index: number): string | null;\n toString(): number;\n [index: number]: string;\n}\n\ndeclare var MediaList: {\n prototype: MediaList;\n new(): MediaList;\n};\n\ninterface MediaQueryList {\n readonly matches: boolean;\n readonly media: string;\n addListener(listener: MediaQueryListListener): void;\n removeListener(listener: MediaQueryListListener): void;\n}\n\ndeclare var MediaQueryList: {\n prototype: MediaQueryList;\n new(): MediaQueryList;\n};\n\ninterface MediaSource extends EventTarget {\n readonly activeSourceBuffers: SourceBufferList;\n duration: number;\n readonly readyState: ReadyState;\n readonly sourceBuffers: SourceBufferList;\n addSourceBuffer(type: string): SourceBuffer;\n endOfStream(error?: EndOfStreamError): void;\n removeSourceBuffer(sourceBuffer: SourceBuffer): void;\n}\n\ndeclare var MediaSource: {\n prototype: MediaSource;\n new(): MediaSource;\n isTypeSupported(type: string): boolean;\n};\n\ninterface MediaStreamEventMap {\n \"active\": Event;\n \"addtrack\": MediaStreamTrackEvent;\n \"inactive\": Event;\n \"removetrack\": MediaStreamTrackEvent;\n}\n\ninterface MediaStream extends EventTarget {\n readonly active: boolean;\n readonly id: string;\n onactive: ((this: MediaStream, ev: Event) => any) | null;\n onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n oninactive: ((this: MediaStream, ev: Event) => any) | null;\n onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null;\n addTrack(track: MediaStreamTrack): void;\n clone(): MediaStream;\n getAudioTracks(): MediaStreamTrack[];\n getTrackById(trackId: string): MediaStreamTrack | null;\n getTracks(): MediaStreamTrack[];\n getVideoTracks(): MediaStreamTrack[];\n removeTrack(track: MediaStreamTrack): void;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStream, ev: MediaStreamEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStream: {\n prototype: MediaStream;\n new(): MediaStream;\n new(stream: MediaStream): MediaStream;\n new(tracks: MediaStreamTrack[]): MediaStream;\n};\n\ninterface MediaStreamAudioDestinationNode extends AudioNode {\n readonly stream: MediaStream;\n}\n\ndeclare var MediaStreamAudioDestinationNode: {\n prototype: MediaStreamAudioDestinationNode;\n new(context: AudioContext, options?: AudioNodeOptions): MediaStreamAudioDestinationNode;\n};\n\ninterface MediaStreamAudioSourceNode extends AudioNode {\n readonly mediaStream: MediaStream;\n}\n\ndeclare var MediaStreamAudioSourceNode: {\n prototype: MediaStreamAudioSourceNode;\n new(context: AudioContext, options: MediaStreamAudioSourceOptions): MediaStreamAudioSourceNode;\n};\n\ninterface MediaStreamError {\n readonly constraintName: string | null;\n readonly message: string | null;\n readonly name: string;\n}\n\ndeclare var MediaStreamError: {\n prototype: MediaStreamError;\n new(): MediaStreamError;\n};\n\ninterface MediaStreamErrorEvent extends Event {\n readonly error: MediaStreamError | null;\n}\n\ndeclare var MediaStreamErrorEvent: {\n prototype: MediaStreamErrorEvent;\n new(typeArg: string, eventInitDict?: MediaStreamErrorEventInit): MediaStreamErrorEvent;\n};\n\ninterface MediaStreamEvent extends Event {\n readonly stream: MediaStream | null;\n}\n\ndeclare var MediaStreamEvent: {\n prototype: MediaStreamEvent;\n new(type: string, eventInitDict: MediaStreamEventInit): MediaStreamEvent;\n};\n\ninterface MediaStreamTrackEventMap {\n \"ended\": MediaStreamErrorEvent;\n \"isolationchange\": Event;\n \"mute\": Event;\n \"overconstrained\": MediaStreamErrorEvent;\n \"unmute\": Event;\n}\n\ninterface MediaStreamTrack extends EventTarget {\n enabled: boolean;\n readonly id: string;\n readonly isolated: boolean;\n readonly kind: string;\n readonly label: string;\n readonly muted: boolean;\n onended: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onisolationchange: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n onoverconstrained: ((this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any) | null;\n onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null;\n readonly readonly: boolean;\n readonly readyState: MediaStreamTrackState;\n readonly remote: boolean;\n applyConstraints(constraints: MediaTrackConstraints): Promise;\n clone(): MediaStreamTrack;\n getCapabilities(): MediaTrackCapabilities;\n getConstraints(): MediaTrackConstraints;\n getSettings(): MediaTrackSettings;\n stop(): void;\n addEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MediaStreamTrack, ev: MediaStreamTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MediaStreamTrack: {\n prototype: MediaStreamTrack;\n new(): MediaStreamTrack;\n};\n\ninterface MediaStreamTrackAudioSourceNode extends AudioNode {\n}\n\ndeclare var MediaStreamTrackAudioSourceNode: {\n prototype: MediaStreamTrackAudioSourceNode;\n new(context: AudioContext, options: MediaStreamTrackAudioSourceOptions): MediaStreamTrackAudioSourceNode;\n};\n\ninterface MediaStreamTrackEvent extends Event {\n readonly track: MediaStreamTrack;\n}\n\ndeclare var MediaStreamTrackEvent: {\n prototype: MediaStreamTrackEvent;\n new(typeArg: string, eventInitDict?: MediaStreamTrackEventInit): MediaStreamTrackEvent;\n};\n\ninterface MessageChannel {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\ndeclare var MessageChannel: {\n prototype: MessageChannel;\n new(): MessageChannel;\n};\n\ninterface MessageEvent extends Event {\n readonly data: any;\n readonly origin: string;\n readonly ports: ReadonlyArray;\n readonly source: MessageEventSource;\n initMessageEvent(type: string, bubbles: boolean, cancelable: boolean, data: any, origin: string, lastEventId: string, source: Window): void;\n}\n\ndeclare var MessageEvent: {\n prototype: MessageEvent;\n new(type: string, eventInitDict?: MessageEventInit): MessageEvent;\n};\n\ninterface MessagePortEventMap {\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface MessagePort extends EventTarget {\n onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null;\n /**\n * Disconnects the port, so that it is no longer active.\n */\n close(): void;\n /**\n * Posts a message through the channel. Objects listed in transfer are\n * transferred, not just cloned, meaning that they are no longer usable on the sending side.\n * Throws a \"DataCloneError\" DOMException if\n * transfer contains duplicate objects or port, or if message\n * could not be cloned.\n */\n postMessage(message: any, transfer?: any[]): void;\n /**\n * Begins dispatching messages received on the port.\n */\n start(): void;\n addEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var MessagePort: {\n prototype: MessagePort;\n new(): MessagePort;\n};\n\ninterface MimeType {\n readonly description: string;\n readonly enabledPlugin: Plugin;\n readonly suffixes: string;\n readonly type: string;\n}\n\ndeclare var MimeType: {\n prototype: MimeType;\n new(): MimeType;\n};\n\ninterface MimeTypeArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(type: string): Plugin;\n [index: number]: Plugin;\n}\n\ndeclare var MimeTypeArray: {\n prototype: MimeTypeArray;\n new(): MimeTypeArray;\n};\n\ninterface MouseEvent extends UIEvent {\n readonly altKey: boolean;\n readonly button: number;\n readonly buttons: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly ctrlKey: boolean;\n /** @deprecated */\n readonly fromElement: Element;\n readonly layerX: number;\n readonly layerY: number;\n readonly metaKey: boolean;\n readonly movementX: number;\n readonly movementY: number;\n readonly offsetX: number;\n readonly offsetY: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly relatedTarget: EventTarget;\n readonly screenX: number;\n readonly screenY: number;\n readonly shiftKey: boolean;\n /** @deprecated */\n readonly toElement: Element;\n /** @deprecated */\n readonly which: number;\n readonly x: number;\n readonly y: number;\n getModifierState(keyArg: string): boolean;\n initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;\n}\n\ndeclare var MouseEvent: {\n prototype: MouseEvent;\n new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;\n};\n\ninterface MutationEvent extends Event {\n readonly attrChange: number;\n readonly attrName: string;\n readonly newValue: string;\n readonly prevValue: string;\n readonly relatedNode: Node;\n initMutationEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, relatedNodeArg: Node, prevValueArg: string, newValueArg: string, attrNameArg: string, attrChangeArg: number): void;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n}\n\ndeclare var MutationEvent: {\n prototype: MutationEvent;\n new(): MutationEvent;\n readonly ADDITION: number;\n readonly MODIFICATION: number;\n readonly REMOVAL: number;\n};\n\ninterface MutationObserver {\n disconnect(): void;\n observe(target: Node, options: MutationObserverInit): void;\n takeRecords(): MutationRecord[];\n}\n\ndeclare var MutationObserver: {\n prototype: MutationObserver;\n new(callback: MutationCallback): MutationObserver;\n};\n\ninterface MutationRecord {\n readonly addedNodes: NodeList;\n readonly attributeName: string | null;\n readonly attributeNamespace: string | null;\n readonly nextSibling: Node | null;\n readonly oldValue: string | null;\n readonly previousSibling: Node | null;\n readonly removedNodes: NodeList;\n readonly target: Node;\n readonly type: MutationRecordType;\n}\n\ndeclare var MutationRecord: {\n prototype: MutationRecord;\n new(): MutationRecord;\n};\n\ninterface NamedNodeMap {\n readonly length: number;\n getNamedItem(qualifiedName: string): Attr | null;\n getNamedItemNS(namespace: string | null, localName: string): Attr | null;\n item(index: number): Attr | null;\n removeNamedItem(qualifiedName: string): Attr;\n removeNamedItemNS(namespace: string | null, localName: string): Attr;\n setNamedItem(attr: Attr): Attr | null;\n setNamedItemNS(attr: Attr): Attr | null;\n [index: number]: Attr;\n}\n\ndeclare var NamedNodeMap: {\n prototype: NamedNodeMap;\n new(): NamedNodeMap;\n};\n\ninterface NavigationPreloadManager {\n disable(): Promise;\n enable(): Promise;\n getState(): Promise;\n setHeaderValue(value: string): Promise;\n}\n\ndeclare var NavigationPreloadManager: {\n prototype: NavigationPreloadManager;\n new(): NavigationPreloadManager;\n};\n\ninterface Navigator extends NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia, NavigatorLanguage, NavigatorStorage {\n readonly activeVRDisplays: ReadonlyArray;\n readonly authentication: WebAuthentication;\n readonly cookieEnabled: boolean;\n readonly doNotTrack: string | null;\n gamepadInputEmulation: GamepadInputEmulationType;\n readonly geolocation: Geolocation;\n readonly maxTouchPoints: number;\n readonly mimeTypes: MimeTypeArray;\n readonly msManipulationViewsEnabled: boolean;\n readonly msMaxTouchPoints: number;\n readonly msPointerEnabled: boolean;\n readonly plugins: PluginArray;\n readonly pointerEnabled: boolean;\n readonly serviceWorker: ServiceWorkerContainer;\n readonly webdriver: boolean;\n getGamepads(): (Gamepad | null)[];\n getVRDisplays(): Promise;\n javaEnabled(): boolean;\n msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;\n requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise;\n vibrate(pattern: number | number[]): boolean;\n}\n\ndeclare var Navigator: {\n prototype: Navigator;\n new(): Navigator;\n};\n\ninterface NavigatorBeacon {\n sendBeacon(url: string, data?: Blob | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | FormData | string | null): boolean;\n}\n\ninterface NavigatorConcurrentHardware {\n readonly hardwareConcurrency: number;\n}\n\ninterface NavigatorContentUtils {\n}\n\ninterface NavigatorID {\n readonly appCodeName: string;\n readonly appName: string;\n readonly appVersion: string;\n readonly platform: string;\n readonly product: string;\n readonly productSub: string;\n readonly userAgent: string;\n readonly vendor: string;\n readonly vendorSub: string;\n}\n\ninterface NavigatorLanguage {\n readonly language: string;\n readonly languages: ReadonlyArray;\n}\n\ninterface NavigatorOnLine {\n readonly onLine: boolean;\n}\n\ninterface NavigatorStorage {\n readonly storage: StorageManager;\n}\n\ninterface NavigatorStorageUtils {\n}\n\ninterface NavigatorUserMedia {\n readonly mediaDevices: MediaDevices;\n getDisplayMedia(constraints: MediaStreamConstraints): Promise;\n getUserMedia(constraints: MediaStreamConstraints, successCallback: NavigatorUserMediaSuccessCallback, errorCallback: NavigatorUserMediaErrorCallback): void;\n}\n\ninterface Node extends EventTarget {\n readonly baseURI: string | null;\n readonly childNodes: NodeListOf;\n readonly firstChild: Node | null;\n readonly isConnected: boolean;\n readonly lastChild: Node | null;\n readonly localName: string | null;\n readonly namespaceURI: string | null;\n readonly nextSibling: Node | null;\n readonly nodeName: string;\n readonly nodeType: number;\n nodeValue: string | null;\n readonly ownerDocument: Document;\n readonly parentElement: HTMLElement | null;\n readonly parentNode: Node | null;\n readonly previousSibling: Node | null;\n textContent: string | null;\n appendChild(newChild: T): T;\n cloneNode(deep?: boolean): Node;\n compareDocumentPosition(other: Node): number;\n contains(child: Node): boolean;\n hasChildNodes(): boolean;\n insertBefore(newChild: T, refChild: Node | null): T;\n isDefaultNamespace(namespaceURI: string | null): boolean;\n isEqualNode(arg: Node): boolean;\n isSameNode(other: Node): boolean;\n lookupNamespaceURI(prefix: string | null): string | null;\n lookupPrefix(namespaceURI: string | null): string | null;\n normalize(): void;\n removeChild(oldChild: T): T;\n replaceChild(newChild: Node, oldChild: T): T;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n}\n\ndeclare var Node: {\n prototype: Node;\n new(): Node;\n readonly ATTRIBUTE_NODE: number;\n readonly CDATA_SECTION_NODE: number;\n readonly COMMENT_NODE: number;\n readonly DOCUMENT_FRAGMENT_NODE: number;\n readonly DOCUMENT_NODE: number;\n readonly DOCUMENT_POSITION_CONTAINED_BY: number;\n readonly DOCUMENT_POSITION_CONTAINS: number;\n readonly DOCUMENT_POSITION_DISCONNECTED: number;\n readonly DOCUMENT_POSITION_FOLLOWING: number;\n readonly DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: number;\n readonly DOCUMENT_POSITION_PRECEDING: number;\n readonly DOCUMENT_TYPE_NODE: number;\n readonly ELEMENT_NODE: number;\n readonly ENTITY_NODE: number;\n readonly ENTITY_REFERENCE_NODE: number;\n readonly NOTATION_NODE: number;\n readonly PROCESSING_INSTRUCTION_NODE: number;\n readonly TEXT_NODE: number;\n};\n\ninterface NodeFilter {\n acceptNode(node: Node): number;\n}\n\ndeclare var NodeFilter: {\n readonly FILTER_ACCEPT: number;\n readonly FILTER_REJECT: number;\n readonly FILTER_SKIP: number;\n readonly SHOW_ALL: number;\n readonly SHOW_ATTRIBUTE: number;\n readonly SHOW_CDATA_SECTION: number;\n readonly SHOW_COMMENT: number;\n readonly SHOW_DOCUMENT: number;\n readonly SHOW_DOCUMENT_FRAGMENT: number;\n readonly SHOW_DOCUMENT_TYPE: number;\n readonly SHOW_ELEMENT: number;\n readonly SHOW_ENTITY: number;\n readonly SHOW_ENTITY_REFERENCE: number;\n readonly SHOW_NOTATION: number;\n readonly SHOW_PROCESSING_INSTRUCTION: number;\n readonly SHOW_TEXT: number;\n};\n\ninterface NodeIterator {\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n detach(): void;\n nextNode(): Node | null;\n previousNode(): Node | null;\n}\n\ndeclare var NodeIterator: {\n prototype: NodeIterator;\n new(): NodeIterator;\n};\n\ninterface NodeList {\n readonly length: number;\n item(index: number): Node;\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: Node, key: number, parent: NodeList) => void, thisArg?: any): void;\n [index: number]: Node;\n}\n\ndeclare var NodeList: {\n prototype: NodeList;\n new(): NodeList;\n};\n\ninterface NodeListOf extends NodeList {\n length: number;\n item(index: number): TNode;\n /**\n * Performs the specified action for each node in an list.\n * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.\n * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.\n */\n forEach(callbackfn: (value: TNode, key: number, parent: NodeListOf) => void, thisArg?: any): void;\n [index: number]: TNode;\n}\n\ninterface NodeSelector {\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface NotificationEventMap {\n \"click\": Event;\n \"close\": Event;\n \"error\": Event;\n \"show\": Event;\n}\n\ninterface Notification extends EventTarget {\n readonly actions: ReadonlyArray;\n readonly badge: string;\n readonly body: string;\n readonly data: any;\n readonly dir: NotificationDirection;\n readonly icon: string;\n readonly image: string;\n readonly lang: string;\n onclick: ((this: Notification, ev: Event) => any) | null;\n onclose: ((this: Notification, ev: Event) => any) | null;\n onerror: ((this: Notification, ev: Event) => any) | null;\n onshow: ((this: Notification, ev: Event) => any) | null;\n readonly renotify: boolean;\n readonly requireInteraction: boolean;\n readonly silent: boolean;\n readonly tag: string;\n readonly timestamp: number;\n readonly title: string;\n readonly vibrate: ReadonlyArray;\n close(): void;\n addEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Notification, ev: NotificationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Notification: {\n prototype: Notification;\n new(title: string, options?: NotificationOptions): Notification;\n readonly maxActions: number;\n readonly permission: NotificationPermission;\n requestPermission(deprecatedCallback?: NotificationPermissionCallback): Promise;\n};\n\ninterface OES_element_index_uint {\n}\n\ndeclare var OES_element_index_uint: {\n prototype: OES_element_index_uint;\n new(): OES_element_index_uint;\n};\n\ninterface OES_standard_derivatives {\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n}\n\ndeclare var OES_standard_derivatives: {\n prototype: OES_standard_derivatives;\n new(): OES_standard_derivatives;\n readonly FRAGMENT_SHADER_DERIVATIVE_HINT_OES: number;\n};\n\ninterface OES_texture_float {\n}\n\ndeclare var OES_texture_float: {\n prototype: OES_texture_float;\n new(): OES_texture_float;\n};\n\ninterface OES_texture_float_linear {\n}\n\ndeclare var OES_texture_float_linear: {\n prototype: OES_texture_float_linear;\n new(): OES_texture_float_linear;\n};\n\ninterface OES_texture_half_float {\n readonly HALF_FLOAT_OES: number;\n}\n\ndeclare var OES_texture_half_float: {\n prototype: OES_texture_half_float;\n new(): OES_texture_half_float;\n readonly HALF_FLOAT_OES: number;\n};\n\ninterface OES_texture_half_float_linear {\n}\n\ndeclare var OES_texture_half_float_linear: {\n prototype: OES_texture_half_float_linear;\n new(): OES_texture_half_float_linear;\n};\n\ninterface OES_vertex_array_object {\n readonly VERTEX_ARRAY_BINDING_OES: number;\n bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n createVertexArrayOES(): WebGLVertexArrayObjectOES;\n deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES): void;\n isVertexArrayOES(value: any): value is WebGLVertexArrayObjectOES;\n}\n\ninterface OfflineAudioCompletionEvent extends Event {\n readonly renderedBuffer: AudioBuffer;\n}\n\ndeclare var OfflineAudioCompletionEvent: {\n prototype: OfflineAudioCompletionEvent;\n new(type: string, eventInitDict: OfflineAudioCompletionEventInit): OfflineAudioCompletionEvent;\n};\n\ninterface OfflineAudioContextEventMap extends BaseAudioContextEventMap {\n \"complete\": OfflineAudioCompletionEvent;\n}\n\ninterface OfflineAudioContext extends BaseAudioContext {\n readonly length: number;\n oncomplete: ((this: OfflineAudioContext, ev: OfflineAudioCompletionEvent) => any) | null;\n startRendering(): Promise;\n suspend(suspendTime: number): Promise;\n addEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OfflineAudioContext, ev: OfflineAudioContextEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OfflineAudioContext: {\n prototype: OfflineAudioContext;\n new(contextOptions: OfflineAudioContextOptions): OfflineAudioContext;\n new(numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext;\n};\n\ninterface OscillatorNode extends AudioScheduledSourceNode {\n readonly detune: AudioParam;\n readonly frequency: AudioParam;\n type: OscillatorType;\n setPeriodicWave(periodicWave: PeriodicWave): void;\n addEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: OscillatorNode, ev: AudioScheduledSourceNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var OscillatorNode: {\n prototype: OscillatorNode;\n new(context: BaseAudioContext, options?: OscillatorOptions): OscillatorNode;\n};\n\ninterface OverflowEvent extends UIEvent {\n readonly horizontalOverflow: boolean;\n readonly orient: number;\n readonly verticalOverflow: boolean;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n}\n\ndeclare var OverflowEvent: {\n prototype: OverflowEvent;\n new(): OverflowEvent;\n readonly BOTH: number;\n readonly HORIZONTAL: number;\n readonly VERTICAL: number;\n};\n\ninterface PageTransitionEvent extends Event {\n readonly persisted: boolean;\n}\n\ndeclare var PageTransitionEvent: {\n prototype: PageTransitionEvent;\n new(): PageTransitionEvent;\n};\n\ninterface PannerNode extends AudioNode {\n coneInnerAngle: number;\n coneOuterAngle: number;\n coneOuterGain: number;\n distanceModel: DistanceModelType;\n maxDistance: number;\n readonly orientationX: AudioParam;\n readonly orientationY: AudioParam;\n readonly orientationZ: AudioParam;\n panningModel: PanningModelType;\n readonly positionX: AudioParam;\n readonly positionY: AudioParam;\n readonly positionZ: AudioParam;\n refDistance: number;\n rolloffFactor: number;\n /** @deprecated */\n setOrientation(x: number, y: number, z: number): void;\n /** @deprecated */\n setPosition(x: number, y: number, z: number): void;\n}\n\ndeclare var PannerNode: {\n prototype: PannerNode;\n new(context: BaseAudioContext, options?: PannerOptions): PannerNode;\n};\n\ninterface ParentNode {\n readonly childElementCount: number;\n readonly children: HTMLCollection;\n readonly firstElementChild: Element | null;\n readonly lastElementChild: Element | null;\n querySelector(selectors: K): HTMLElementTagNameMap[K] | null;\n querySelector(selectors: K): SVGElementTagNameMap[K] | null;\n querySelector(selectors: string): E | null;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: K): NodeListOf;\n querySelectorAll(selectors: string): NodeListOf;\n}\n\ninterface Path2D extends CanvasPathMethods {\n}\n\ndeclare var Path2D: {\n prototype: Path2D;\n new(d?: Path2D | string): Path2D;\n};\n\ninterface PaymentAddress {\n readonly addressLine: string[];\n readonly city: string;\n readonly country: string;\n readonly dependentLocality: string;\n readonly languageCode: string;\n readonly organization: string;\n readonly phone: string;\n readonly postalCode: string;\n readonly recipient: string;\n readonly region: string;\n readonly sortingCode: string;\n toJSON(): any;\n}\n\ndeclare var PaymentAddress: {\n prototype: PaymentAddress;\n new(): PaymentAddress;\n};\n\ninterface PaymentRequestEventMap {\n \"shippingaddresschange\": Event;\n \"shippingoptionchange\": Event;\n}\n\ninterface PaymentRequest extends EventTarget {\n readonly id: string;\n onshippingaddresschange: ((this: PaymentRequest, ev: Event) => any) | null;\n onshippingoptionchange: ((this: PaymentRequest, ev: Event) => any) | null;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n readonly shippingType: PaymentShippingType | null;\n abort(): Promise;\n canMakePayment(): Promise;\n show(): Promise;\n addEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var PaymentRequest: {\n prototype: PaymentRequest;\n new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest;\n};\n\ninterface PaymentRequestUpdateEvent extends Event {\n updateWith(detailsPromise: Promise): void;\n}\n\ndeclare var PaymentRequestUpdateEvent: {\n prototype: PaymentRequestUpdateEvent;\n new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent;\n};\n\ninterface PaymentResponse {\n readonly details: any;\n readonly methodName: string;\n readonly payerEmail: string | null;\n readonly payerName: string | null;\n readonly payerPhone: string | null;\n readonly requestId: string;\n readonly shippingAddress: PaymentAddress | null;\n readonly shippingOption: string | null;\n complete(result?: PaymentComplete): Promise;\n toJSON(): any;\n}\n\ndeclare var PaymentResponse: {\n prototype: PaymentResponse;\n new(): PaymentResponse;\n};\n\ninterface PerfWidgetExternal {\n readonly activeNetworkRequestCount: number;\n readonly averageFrameTime: number;\n readonly averagePaintTime: number;\n readonly extraInformationEnabled: boolean;\n readonly independentRenderingEnabled: boolean;\n readonly irDisablingContentString: string;\n readonly irStatusAvailable: boolean;\n readonly maxCpuSpeed: number;\n readonly paintRequestsPerSecond: number;\n readonly performanceCounter: number;\n readonly performanceCounterFrequency: number;\n addEventListener(eventType: string, callback: Function): void;\n getMemoryUsage(): number;\n getProcessCpuUsage(): number;\n getRecentCpuUsage(last: number | null): any;\n getRecentFrames(last: number | null): any;\n getRecentMemoryUsage(last: number | null): any;\n getRecentPaintRequests(last: number | null): any;\n removeEventListener(eventType: string, callback: Function): void;\n repositionWindow(x: number, y: number): void;\n resizeWindow(width: number, height: number): void;\n}\n\ndeclare var PerfWidgetExternal: {\n prototype: PerfWidgetExternal;\n new(): PerfWidgetExternal;\n};\n\ninterface PerformanceEventMap {\n \"resourcetimingbufferfull\": Event;\n}\n\ninterface Performance extends EventTarget {\n /** @deprecated */\n readonly navigation: PerformanceNavigation;\n onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null;\n readonly timeOrigin: number;\n /** @deprecated */\n readonly timing: PerformanceTiming;\n clearMarks(markName?: string): void;\n clearMeasures(measureName?: string): void;\n clearResourceTimings(): void;\n getEntries(): PerformanceEntryList;\n getEntriesByName(name: string, type?: string): PerformanceEntryList;\n getEntriesByType(type: string): PerformanceEntryList;\n mark(markName: string): void;\n measure(measureName: string, startMark?: string, endMark?: string): void;\n now(): number;\n setResourceTimingBufferSize(maxSize: number): void;\n toJSON(): any;\n addEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Performance: {\n prototype: Performance;\n new(): Performance;\n};\n\ninterface PerformanceEntry {\n readonly duration: number;\n readonly entryType: string;\n readonly name: string;\n readonly startTime: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceEntry: {\n prototype: PerformanceEntry;\n new(): PerformanceEntry;\n};\n\ninterface PerformanceMark extends PerformanceEntry {\n}\n\ndeclare var PerformanceMark: {\n prototype: PerformanceMark;\n new(): PerformanceMark;\n};\n\ninterface PerformanceMeasure extends PerformanceEntry {\n}\n\ndeclare var PerformanceMeasure: {\n prototype: PerformanceMeasure;\n new(): PerformanceMeasure;\n};\n\ninterface PerformanceNavigation {\n readonly redirectCount: number;\n readonly type: number;\n toJSON(): any;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n}\n\ndeclare var PerformanceNavigation: {\n prototype: PerformanceNavigation;\n new(): PerformanceNavigation;\n readonly TYPE_BACK_FORWARD: number;\n readonly TYPE_NAVIGATE: number;\n readonly TYPE_RELOAD: number;\n readonly TYPE_RESERVED: number;\n};\n\ninterface PerformanceNavigationTiming extends PerformanceResourceTiming {\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly redirectCount: number;\n readonly type: NavigationType;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceNavigationTiming: {\n prototype: PerformanceNavigationTiming;\n new(): PerformanceNavigationTiming;\n};\n\ninterface PerformanceObserver {\n disconnect(): void;\n observe(options: PerformanceObserverInit): void;\n takeRecords(): PerformanceEntryList;\n}\n\ndeclare var PerformanceObserver: {\n prototype: PerformanceObserver;\n new(callback: PerformanceObserverCallback): PerformanceObserver;\n};\n\ninterface PerformanceObserverEntryList {\n getEntries(): PerformanceEntryList;\n getEntriesByName(name: string, type?: string): PerformanceEntryList;\n getEntriesByType(type: string): PerformanceEntryList;\n}\n\ndeclare var PerformanceObserverEntryList: {\n prototype: PerformanceObserverEntryList;\n new(): PerformanceObserverEntryList;\n};\n\ninterface PerformanceResourceTiming extends PerformanceEntry {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly decodedBodySize: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly encodedBodySize: number;\n readonly fetchStart: number;\n readonly initiatorType: string;\n readonly nextHopProtocol: string;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly transferSize: number;\n readonly workerStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceResourceTiming: {\n prototype: PerformanceResourceTiming;\n new(): PerformanceResourceTiming;\n};\n\ninterface PerformanceTiming {\n readonly connectEnd: number;\n readonly connectStart: number;\n readonly domComplete: number;\n readonly domContentLoadedEventEnd: number;\n readonly domContentLoadedEventStart: number;\n readonly domInteractive: number;\n readonly domLoading: number;\n readonly domainLookupEnd: number;\n readonly domainLookupStart: number;\n readonly fetchStart: number;\n readonly loadEventEnd: number;\n readonly loadEventStart: number;\n readonly navigationStart: number;\n readonly redirectEnd: number;\n readonly redirectStart: number;\n readonly requestStart: number;\n readonly responseEnd: number;\n readonly responseStart: number;\n readonly secureConnectionStart: number;\n readonly unloadEventEnd: number;\n readonly unloadEventStart: number;\n toJSON(): any;\n}\n\ndeclare var PerformanceTiming: {\n prototype: PerformanceTiming;\n new(): PerformanceTiming;\n};\n\ninterface PeriodicWave {\n}\n\ndeclare var PeriodicWave: {\n prototype: PeriodicWave;\n new(context: BaseAudioContext, options?: PeriodicWaveOptions): PeriodicWave;\n};\n\ninterface PermissionRequest extends DeferredPermissionRequest {\n readonly state: MSWebViewPermissionState;\n defer(): void;\n}\n\ndeclare var PermissionRequest: {\n prototype: PermissionRequest;\n new(): PermissionRequest;\n};\n\ninterface PermissionRequestedEvent extends Event {\n readonly permissionRequest: PermissionRequest;\n}\n\ndeclare var PermissionRequestedEvent: {\n prototype: PermissionRequestedEvent;\n new(): PermissionRequestedEvent;\n};\n\ninterface Plugin {\n readonly description: string;\n readonly filename: string;\n readonly length: number;\n readonly name: string;\n readonly version: string;\n item(index: number): MimeType;\n namedItem(type: string): MimeType;\n [index: number]: MimeType;\n}\n\ndeclare var Plugin: {\n prototype: Plugin;\n new(): Plugin;\n};\n\ninterface PluginArray {\n readonly length: number;\n item(index: number): Plugin;\n namedItem(name: string): Plugin;\n refresh(reload?: boolean): void;\n [index: number]: Plugin;\n}\n\ndeclare var PluginArray: {\n prototype: PluginArray;\n new(): PluginArray;\n};\n\ninterface PointerEvent extends MouseEvent {\n readonly height: number;\n readonly isPrimary: boolean;\n readonly pointerId: number;\n readonly pointerType: string;\n readonly pressure: number;\n readonly tangentialPressure: number;\n readonly tiltX: number;\n readonly tiltY: number;\n readonly twist: number;\n readonly width: number;\n}\n\ndeclare var PointerEvent: {\n prototype: PointerEvent;\n new(type: string, eventInitDict?: PointerEventInit): PointerEvent;\n};\n\ninterface PopStateEvent extends Event {\n readonly state: any;\n}\n\ndeclare var PopStateEvent: {\n prototype: PopStateEvent;\n new(type: string, eventInitDict?: PopStateEventInit): PopStateEvent;\n};\n\ninterface Position {\n readonly coords: Coordinates;\n readonly timestamp: number;\n}\n\ninterface PositionError {\n readonly code: number;\n readonly message: string;\n readonly PERMISSION_DENIED: number;\n readonly POSITION_UNAVAILABLE: number;\n readonly TIMEOUT: number;\n}\n\ninterface ProcessingInstruction extends CharacterData {\n readonly target: string;\n}\n\ndeclare var ProcessingInstruction: {\n prototype: ProcessingInstruction;\n new(): ProcessingInstruction;\n};\n\ninterface ProgressEvent extends Event {\n readonly lengthComputable: boolean;\n readonly loaded: number;\n readonly total: number;\n}\n\ndeclare var ProgressEvent: {\n prototype: ProgressEvent;\n new(type: string, eventInitDict?: ProgressEventInit): ProgressEvent;\n};\n\ninterface PromiseRejectionEvent extends Event {\n readonly promise: PromiseLike;\n readonly reason: any;\n}\n\ndeclare var PromiseRejectionEvent: {\n prototype: PromiseRejectionEvent;\n new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent;\n};\n\ninterface PushManager {\n getSubscription(): Promise;\n permissionState(options?: PushSubscriptionOptionsInit): Promise;\n subscribe(options?: PushSubscriptionOptionsInit): Promise;\n}\n\ndeclare var PushManager: {\n prototype: PushManager;\n new(): PushManager;\n readonly supportedContentEncodings: ReadonlyArray;\n};\n\ninterface PushSubscription {\n readonly endpoint: string;\n readonly expirationTime: number | null;\n readonly options: PushSubscriptionOptions;\n getKey(name: PushEncryptionKeyName): ArrayBuffer | null;\n toJSON(): PushSubscriptionJSON;\n unsubscribe(): Promise;\n}\n\ndeclare var PushSubscription: {\n prototype: PushSubscription;\n new(): PushSubscription;\n};\n\ninterface PushSubscriptionOptions {\n readonly applicationServerKey: ArrayBuffer | null;\n readonly userVisibleOnly: boolean;\n}\n\ndeclare var PushSubscriptionOptions: {\n prototype: PushSubscriptionOptions;\n new(): PushSubscriptionOptions;\n};\n\ninterface RTCCertificate {\n readonly expires: number;\n getFingerprints(): RTCDtlsFingerprint[];\n}\n\ndeclare var RTCCertificate: {\n prototype: RTCCertificate;\n new(): RTCCertificate;\n getSupportedAlgorithms(): AlgorithmIdentifier[];\n};\n\ninterface RTCDTMFSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDTMFSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n ontonechange: ((this: RTCDTMFSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDTMFSender, ev: RTCDTMFSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDTMFSender: {\n prototype: RTCDTMFSender;\n new(): RTCDTMFSender;\n};\n\ninterface RTCDTMFToneChangeEvent extends Event {\n readonly tone: string;\n}\n\ndeclare var RTCDTMFToneChangeEvent: {\n prototype: RTCDTMFToneChangeEvent;\n new(type: string, eventInitDict: RTCDTMFToneChangeEventInit): RTCDTMFToneChangeEvent;\n};\n\ninterface RTCDataChannelEventMap {\n \"bufferedamountlow\": Event;\n \"close\": Event;\n \"error\": RTCErrorEvent;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface RTCDataChannel extends EventTarget {\n binaryType: string;\n readonly bufferedAmount: number;\n bufferedAmountLowThreshold: number;\n readonly id: number | null;\n readonly label: string;\n readonly maxPacketLifeTime: number | null;\n readonly maxRetransmits: number | null;\n readonly negotiated: boolean;\n onbufferedamountlow: ((this: RTCDataChannel, ev: Event) => any) | null;\n onclose: ((this: RTCDataChannel, ev: Event) => any) | null;\n onerror: ((this: RTCDataChannel, ev: RTCErrorEvent) => any) | null;\n onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null;\n onopen: ((this: RTCDataChannel, ev: Event) => any) | null;\n readonly ordered: boolean;\n readonly priority: RTCPriorityType;\n readonly protocol: string;\n readonly readyState: RTCDataChannelState;\n close(): void;\n send(data: string): void;\n send(data: Blob): void;\n send(data: ArrayBuffer): void;\n send(data: ArrayBufferView): void;\n addEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDataChannel, ev: RTCDataChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDataChannel: {\n prototype: RTCDataChannel;\n new(): RTCDataChannel;\n};\n\ninterface RTCDataChannelEvent extends Event {\n readonly channel: RTCDataChannel;\n}\n\ndeclare var RTCDataChannelEvent: {\n prototype: RTCDataChannelEvent;\n new(type: string, eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent;\n};\n\ninterface RTCDtlsTransportEventMap {\n \"error\": RTCErrorEvent;\n \"statechange\": Event;\n}\n\ninterface RTCDtlsTransport extends EventTarget {\n onerror: ((this: RTCDtlsTransport, ev: RTCErrorEvent) => any) | null;\n onstatechange: ((this: RTCDtlsTransport, ev: Event) => any) | null;\n readonly state: RTCDtlsTransportState;\n readonly transport: RTCIceTransport;\n getRemoteCertificates(): ArrayBuffer[];\n addEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtlsTransport, ev: RTCDtlsTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtlsTransport: {\n prototype: RTCDtlsTransport;\n new(): RTCDtlsTransport;\n};\n\ninterface RTCDtlsTransportStateChangedEvent extends Event {\n readonly state: RTCDtlsTransportState;\n}\n\ndeclare var RTCDtlsTransportStateChangedEvent: {\n prototype: RTCDtlsTransportStateChangedEvent;\n new(): RTCDtlsTransportStateChangedEvent;\n};\n\ninterface RTCDtmfSenderEventMap {\n \"tonechange\": RTCDTMFToneChangeEvent;\n}\n\ninterface RTCDtmfSender extends EventTarget {\n readonly canInsertDTMF: boolean;\n readonly duration: number;\n readonly interToneGap: number;\n ontonechange: ((this: RTCDtmfSender, ev: RTCDTMFToneChangeEvent) => any) | null;\n readonly sender: RTCRtpSender;\n readonly toneBuffer: string;\n insertDTMF(tones: string, duration?: number, interToneGap?: number): void;\n addEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCDtmfSender, ev: RTCDtmfSenderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCDtmfSender: {\n prototype: RTCDtmfSender;\n new(sender: RTCRtpSender): RTCDtmfSender;\n};\n\ninterface RTCError extends Error {\n errorDetail: string;\n httpRequestStatusCode: number;\n message: string;\n name: string;\n receivedAlert: number | null;\n sctpCauseCode: number;\n sdpLineNumber: number;\n sentAlert: number | null;\n}\n\ndeclare var RTCError: {\n prototype: RTCError;\n new(errorDetail?: string, message?: string): RTCError;\n};\n\ninterface RTCErrorEvent extends Event {\n readonly error: RTCError | null;\n}\n\ndeclare var RTCErrorEvent: {\n prototype: RTCErrorEvent;\n new(type: string, eventInitDict: RTCErrorEventInit): RTCErrorEvent;\n};\n\ninterface RTCIceCandidate {\n readonly candidate: string;\n readonly component: RTCIceComponent | null;\n readonly foundation: string | null;\n readonly ip: string | null;\n readonly port: number | null;\n readonly priority: number | null;\n readonly protocol: RTCIceProtocol | null;\n readonly relatedAddress: string | null;\n readonly relatedPort: number | null;\n readonly sdpMLineIndex: number | null;\n readonly sdpMid: string | null;\n readonly tcpType: RTCIceTcpCandidateType | null;\n readonly type: RTCIceCandidateType | null;\n readonly usernameFragment: string | null;\n toJSON(): RTCIceCandidateInit;\n}\n\ndeclare var RTCIceCandidate: {\n prototype: RTCIceCandidate;\n new(candidateInitDict?: RTCIceCandidateInit): RTCIceCandidate;\n};\n\ninterface RTCIceCandidatePairChangedEvent extends Event {\n readonly pair: RTCIceCandidatePair;\n}\n\ndeclare var RTCIceCandidatePairChangedEvent: {\n prototype: RTCIceCandidatePairChangedEvent;\n new(): RTCIceCandidatePairChangedEvent;\n};\n\ninterface RTCIceGathererEventMap {\n \"error\": Event;\n \"localcandidate\": RTCIceGathererEvent;\n}\n\ninterface RTCIceGatherer extends RTCStatsProvider {\n readonly component: RTCIceComponent;\n onerror: ((this: RTCIceGatherer, ev: Event) => any) | null;\n onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null;\n createAssociatedGatherer(): RTCIceGatherer;\n getLocalCandidates(): RTCIceCandidateDictionary[];\n getLocalParameters(): RTCIceParameters;\n addEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceGatherer, ev: RTCIceGathererEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceGatherer: {\n prototype: RTCIceGatherer;\n new(options: RTCIceGatherOptions): RTCIceGatherer;\n};\n\ninterface RTCIceGathererEvent extends Event {\n readonly candidate: RTCIceCandidateDictionary | RTCIceCandidateComplete;\n}\n\ndeclare var RTCIceGathererEvent: {\n prototype: RTCIceGathererEvent;\n new(): RTCIceGathererEvent;\n};\n\ninterface RTCIceTransportEventMap {\n \"gatheringstatechange\": Event;\n \"selectedcandidatepairchange\": Event;\n \"statechange\": Event;\n}\n\ninterface RTCIceTransport extends EventTarget {\n readonly component: RTCIceComponent;\n readonly gatheringState: RTCIceGathererState;\n ongatheringstatechange: ((this: RTCIceTransport, ev: Event) => any) | null;\n onselectedcandidatepairchange: ((this: RTCIceTransport, ev: Event) => any) | null;\n onstatechange: ((this: RTCIceTransport, ev: Event) => any) | null;\n readonly role: RTCIceRole;\n readonly state: RTCIceTransportState;\n getLocalCandidates(): RTCIceCandidate[];\n getLocalParameters(): RTCIceParameters | null;\n getRemoteCandidates(): RTCIceCandidate[];\n getRemoteParameters(): RTCIceParameters | null;\n getSelectedCandidatePair(): RTCIceCandidatePair | null;\n addEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCIceTransport: {\n prototype: RTCIceTransport;\n new(): RTCIceTransport;\n};\n\ninterface RTCIceTransportStateChangedEvent extends Event {\n readonly state: RTCIceTransportState;\n}\n\ndeclare var RTCIceTransportStateChangedEvent: {\n prototype: RTCIceTransportStateChangedEvent;\n new(): RTCIceTransportStateChangedEvent;\n};\n\ninterface RTCIdentityAssertion {\n idp: string;\n name: string;\n}\n\ndeclare var RTCIdentityAssertion: {\n prototype: RTCIdentityAssertion;\n new(idp: string, name: string): RTCIdentityAssertion;\n};\n\ninterface RTCPeerConnectionEventMap {\n \"connectionstatechange\": Event;\n \"datachannel\": RTCDataChannelEvent;\n \"icecandidate\": RTCPeerConnectionIceEvent;\n \"icecandidateerror\": RTCPeerConnectionIceErrorEvent;\n \"iceconnectionstatechange\": Event;\n \"icegatheringstatechange\": Event;\n \"negotiationneeded\": Event;\n \"signalingstatechange\": Event;\n \"statsended\": RTCStatsEvent;\n \"track\": RTCTrackEvent;\n}\n\ninterface RTCPeerConnection extends EventTarget {\n readonly canTrickleIceCandidates: boolean | null;\n readonly connectionState: RTCPeerConnectionState;\n readonly currentLocalDescription: RTCSessionDescription | null;\n readonly currentRemoteDescription: RTCSessionDescription | null;\n readonly iceConnectionState: RTCIceConnectionState;\n readonly iceGatheringState: RTCIceGatheringState;\n readonly idpErrorInfo: string | null;\n readonly idpLoginUrl: string | null;\n readonly localDescription: RTCSessionDescription | null;\n onconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n ondatachannel: ((this: RTCPeerConnection, ev: RTCDataChannelEvent) => any) | null;\n onicecandidate: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any) | null;\n onicecandidateerror: ((this: RTCPeerConnection, ev: RTCPeerConnectionIceErrorEvent) => any) | null;\n oniceconnectionstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onicegatheringstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onnegotiationneeded: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onsignalingstatechange: ((this: RTCPeerConnection, ev: Event) => any) | null;\n onstatsended: ((this: RTCPeerConnection, ev: RTCStatsEvent) => any) | null;\n ontrack: ((this: RTCPeerConnection, ev: RTCTrackEvent) => any) | null;\n readonly peerIdentity: Promise;\n readonly pendingLocalDescription: RTCSessionDescription | null;\n readonly pendingRemoteDescription: RTCSessionDescription | null;\n readonly remoteDescription: RTCSessionDescription | null;\n readonly sctp: RTCSctpTransport | null;\n readonly signalingState: RTCSignalingState;\n addIceCandidate(candidate: RTCIceCandidateInit | RTCIceCandidate): Promise;\n addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender;\n addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver;\n close(): void;\n createAnswer(options?: RTCOfferOptions): Promise;\n createDataChannel(label: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel;\n createOffer(options?: RTCOfferOptions): Promise;\n getConfiguration(): RTCConfiguration;\n getIdentityAssertion(): Promise;\n getReceivers(): RTCRtpReceiver[];\n getSenders(): RTCRtpSender[];\n getStats(selector?: MediaStreamTrack | null): Promise;\n getTransceivers(): RTCRtpTransceiver[];\n removeTrack(sender: RTCRtpSender): void;\n setConfiguration(configuration: RTCConfiguration): void;\n setIdentityProvider(provider: string, options?: RTCIdentityProviderOptions): void;\n setLocalDescription(description: RTCSessionDescriptionInit): Promise;\n setRemoteDescription(description: RTCSessionDescriptionInit): Promise;\n addEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCPeerConnection: {\n prototype: RTCPeerConnection;\n new(configuration?: RTCConfiguration): RTCPeerConnection;\n generateCertificate(keygenAlgorithm: AlgorithmIdentifier): Promise;\n getDefaultIceServers(): RTCIceServer[];\n};\n\ninterface RTCPeerConnectionIceErrorEvent extends Event {\n readonly errorCode: number;\n readonly errorText: string;\n readonly hostCandidate: string;\n readonly url: string;\n}\n\ndeclare var RTCPeerConnectionIceErrorEvent: {\n prototype: RTCPeerConnectionIceErrorEvent;\n new(type: string, eventInitDict: RTCPeerConnectionIceErrorEventInit): RTCPeerConnectionIceErrorEvent;\n};\n\ninterface RTCPeerConnectionIceEvent extends Event {\n readonly candidate: RTCIceCandidate | null;\n readonly url: string | null;\n}\n\ndeclare var RTCPeerConnectionIceEvent: {\n prototype: RTCPeerConnectionIceEvent;\n new(type: string, eventInitDict?: RTCPeerConnectionIceEventInit): RTCPeerConnectionIceEvent;\n};\n\ninterface RTCRtpReceiver {\n readonly rtcpTransport: RTCDtlsTransport | null;\n readonly track: MediaStreamTrack;\n readonly transport: RTCDtlsTransport | null;\n getContributingSources(): RTCRtpContributingSource[];\n getParameters(): RTCRtpReceiveParameters;\n getStats(): Promise;\n getSynchronizationSources(): RTCRtpSynchronizationSource[];\n}\n\ndeclare var RTCRtpReceiver: {\n prototype: RTCRtpReceiver;\n new(): RTCRtpReceiver;\n getCapabilities(kind: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpSender {\n readonly dtmf: RTCDTMFSender | null;\n readonly rtcpTransport: RTCDtlsTransport | null;\n readonly track: MediaStreamTrack | null;\n readonly transport: RTCDtlsTransport | null;\n getParameters(): RTCRtpSendParameters;\n getStats(): Promise;\n replaceTrack(withTrack: MediaStreamTrack | null): Promise;\n setParameters(parameters: RTCRtpSendParameters): Promise;\n setStreams(...streams: MediaStream[]): void;\n}\n\ndeclare var RTCRtpSender: {\n prototype: RTCRtpSender;\n new(): RTCRtpSender;\n getCapabilities(kind: string): RTCRtpCapabilities;\n};\n\ninterface RTCRtpTransceiver {\n readonly currentDirection: RTCRtpTransceiverDirection | null;\n direction: RTCRtpTransceiverDirection;\n readonly mid: string | null;\n readonly receiver: RTCRtpReceiver;\n readonly sender: RTCRtpSender;\n readonly stopped: boolean;\n setCodecPreferences(codecs: RTCRtpCodecCapability[]): void;\n stop(): void;\n}\n\ndeclare var RTCRtpTransceiver: {\n prototype: RTCRtpTransceiver;\n new(): RTCRtpTransceiver;\n};\n\ninterface RTCSctpTransportEventMap {\n \"statechange\": Event;\n}\n\ninterface RTCSctpTransport {\n readonly maxChannels: number | null;\n readonly maxMessageSize: number;\n onstatechange: ((this: RTCSctpTransport, ev: Event) => any) | null;\n readonly state: RTCSctpTransportState;\n readonly transport: RTCDtlsTransport;\n addEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSctpTransport, ev: RTCSctpTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSctpTransport: {\n prototype: RTCSctpTransport;\n new(): RTCSctpTransport;\n};\n\ninterface RTCSessionDescription {\n readonly sdp: string;\n readonly type: RTCSdpType;\n toJSON(): any;\n}\n\ndeclare var RTCSessionDescription: {\n prototype: RTCSessionDescription;\n new(descriptionInitDict: RTCSessionDescriptionInit): RTCSessionDescription;\n};\n\ninterface RTCSrtpSdesTransportEventMap {\n \"error\": Event;\n}\n\ninterface RTCSrtpSdesTransport extends EventTarget {\n onerror: ((this: RTCSrtpSdesTransport, ev: Event) => any) | null;\n readonly transport: RTCIceTransport;\n addEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: RTCSrtpSdesTransport, ev: RTCSrtpSdesTransportEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var RTCSrtpSdesTransport: {\n prototype: RTCSrtpSdesTransport;\n new(transport: RTCIceTransport, encryptParameters: RTCSrtpSdesParameters, decryptParameters: RTCSrtpSdesParameters): RTCSrtpSdesTransport;\n getLocalParameters(): RTCSrtpSdesParameters[];\n};\n\ninterface RTCSsrcConflictEvent extends Event {\n readonly ssrc: number;\n}\n\ndeclare var RTCSsrcConflictEvent: {\n prototype: RTCSsrcConflictEvent;\n new(): RTCSsrcConflictEvent;\n};\n\ninterface RTCStatsEvent extends Event {\n readonly report: RTCStatsReport;\n}\n\ndeclare var RTCStatsEvent: {\n prototype: RTCStatsEvent;\n new(type: string, eventInitDict: RTCStatsEventInit): RTCStatsEvent;\n};\n\ninterface RTCStatsProvider extends EventTarget {\n getStats(): Promise;\n msGetStats(): Promise;\n}\n\ndeclare var RTCStatsProvider: {\n prototype: RTCStatsProvider;\n new(): RTCStatsProvider;\n};\n\ninterface RTCStatsReport {\n forEach(callbackfn: (value: any, key: string, parent: RTCStatsReport) => void, thisArg?: any): void;\n}\n\ndeclare var RTCStatsReport: {\n prototype: RTCStatsReport;\n new(): RTCStatsReport;\n};\n\ninterface RTCTrackEvent extends Event {\n readonly receiver: RTCRtpReceiver;\n readonly streams: ReadonlyArray;\n readonly track: MediaStreamTrack;\n readonly transceiver: RTCRtpTransceiver;\n}\n\ndeclare var RTCTrackEvent: {\n prototype: RTCTrackEvent;\n new(type: string, eventInitDict: RTCTrackEventInit): RTCTrackEvent;\n};\n\ninterface RadioNodeList extends NodeList {\n value: string;\n}\n\ndeclare var RadioNodeList: {\n prototype: RadioNodeList;\n new(): RadioNodeList;\n};\n\ninterface RandomSource {\n getRandomValues(array: T): T;\n}\n\ndeclare var RandomSource: {\n prototype: RandomSource;\n new(): RandomSource;\n};\n\ninterface Range {\n readonly collapsed: boolean;\n readonly commonAncestorContainer: Node;\n readonly endContainer: Node;\n readonly endOffset: number;\n readonly startContainer: Node;\n readonly startOffset: number;\n cloneContents(): DocumentFragment;\n cloneRange(): Range;\n collapse(toStart?: boolean): void;\n compareBoundaryPoints(how: number, sourceRange: Range): number;\n createContextualFragment(fragment: string): DocumentFragment;\n deleteContents(): void;\n detach(): void;\n expand(Unit: ExpandGranularity): boolean;\n extractContents(): DocumentFragment;\n getBoundingClientRect(): ClientRect | DOMRect;\n getClientRects(): ClientRectList | DOMRectList;\n insertNode(node: Node): void;\n isPointInRange(node: Node, offset: number): boolean;\n selectNode(node: Node): void;\n selectNodeContents(node: Node): void;\n setEnd(node: Node, offset: number): void;\n setEndAfter(node: Node): void;\n setEndBefore(node: Node): void;\n setStart(node: Node, offset: number): void;\n setStartAfter(node: Node): void;\n setStartBefore(node: Node): void;\n surroundContents(newParent: Node): void;\n toString(): string;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n}\n\ndeclare var Range: {\n prototype: Range;\n new(): Range;\n readonly END_TO_END: number;\n readonly END_TO_START: number;\n readonly START_TO_END: number;\n readonly START_TO_START: number;\n};\n\ninterface ReadableStream {\n readonly locked: boolean;\n cancel(): Promise;\n getReader(): ReadableStreamReader;\n}\n\ndeclare var ReadableStream: {\n prototype: ReadableStream;\n new(): ReadableStream;\n};\n\ninterface ReadableStreamReader {\n cancel(): Promise;\n read(): Promise;\n releaseLock(): void;\n}\n\ndeclare var ReadableStreamReader: {\n prototype: ReadableStreamReader;\n new(): ReadableStreamReader;\n};\n\ninterface Request extends Body {\n /**\n * Returns the cache mode associated with request, which is a string indicating\n * how the the request will interact with the browser's cache when fetching.\n */\n readonly cache: RequestCache;\n /**\n * Returns the credentials mode associated with request, which is a string\n * indicating whether credentials will be sent with the request always, never, or only when sent to a\n * same-origin URL.\n */\n readonly credentials: RequestCredentials;\n /**\n * Returns the kind of resource requested by request, e.g., \"document\" or\n * \"script\".\n */\n readonly destination: RequestDestination;\n /**\n * Returns a Headers object consisting of the headers associated with request.\n * Note that headers added in the network layer by the user agent will not be accounted for in this\n * object, e.g., the \"Host\" header.\n */\n readonly headers: Headers;\n /**\n * Returns request's subresource integrity metadata, which is a cryptographic hash of\n * the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]\n */\n readonly integrity: string;\n /**\n * Returns a boolean indicating whether or not request is for a history\n * navigation (a.k.a. back-foward navigation).\n */\n readonly isHistoryNavigation: boolean;\n /**\n * Returns a boolean indicating whether or not request is for a reload navigation.\n */\n readonly isReloadNavigation: boolean;\n /**\n * Returns a boolean indicating whether or not request can outlive the global in which\n * it was created.\n */\n readonly keepalive: boolean;\n /**\n * Returns request's HTTP method, which is \"GET\" by default.\n */\n readonly method: string;\n /**\n * Returns the mode associated with request, which is a string indicating\n * whether the request will use CORS, or will be restricted to same-origin URLs.\n */\n readonly mode: RequestMode;\n /**\n * Returns the redirect mode associated with request, which is a string\n * indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.\n */\n readonly redirect: RequestRedirect;\n /**\n * Returns the referrer of request. Its value can be a same-origin URL if\n * explicitly set in init, the empty string to indicate no referrer, and\n * \"about:client\" when defaulting to the global's default. This is used during\n * fetching to determine the value of the `Referer` header of the request being made.\n */\n readonly referrer: string;\n /**\n * Returns the referrer policy associated with request. This is used during\n * fetching to compute the value of the request's referrer.\n */\n readonly referrerPolicy: ReferrerPolicy;\n /**\n * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort\n * event handler.\n */\n readonly signal: AbortSignal;\n /**\n * Returns the URL of request as a string.\n */\n readonly url: string;\n clone(): Request;\n}\n\ndeclare var Request: {\n prototype: Request;\n new(input: RequestInfo, init?: RequestInit): Request;\n};\n\ninterface Response extends Body {\n readonly headers: Headers;\n readonly ok: boolean;\n readonly redirected: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly trailer: Promise;\n readonly type: ResponseType;\n readonly url: string;\n clone(): Response;\n}\n\ndeclare var Response: {\n prototype: Response;\n new(body?: BodyInit | null, init?: ResponseInit): Response;\n error(): Response;\n redirect(url: string, status?: number): Response;\n};\n\ninterface SVGAElement extends SVGGraphicsElement, SVGURIReference {\n readonly target: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGAElement: {\n prototype: SVGAElement;\n new(): SVGAElement;\n};\n\ninterface SVGAngle {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n}\n\ndeclare var SVGAngle: {\n prototype: SVGAngle;\n new(): SVGAngle;\n readonly SVG_ANGLETYPE_DEG: number;\n readonly SVG_ANGLETYPE_GRAD: number;\n readonly SVG_ANGLETYPE_RAD: number;\n readonly SVG_ANGLETYPE_UNKNOWN: number;\n readonly SVG_ANGLETYPE_UNSPECIFIED: number;\n};\n\ninterface SVGAnimatedAngle {\n readonly animVal: SVGAngle;\n readonly baseVal: SVGAngle;\n}\n\ndeclare var SVGAnimatedAngle: {\n prototype: SVGAnimatedAngle;\n new(): SVGAnimatedAngle;\n};\n\ninterface SVGAnimatedBoolean {\n readonly animVal: boolean;\n baseVal: boolean;\n}\n\ndeclare var SVGAnimatedBoolean: {\n prototype: SVGAnimatedBoolean;\n new(): SVGAnimatedBoolean;\n};\n\ninterface SVGAnimatedEnumeration {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedEnumeration: {\n prototype: SVGAnimatedEnumeration;\n new(): SVGAnimatedEnumeration;\n};\n\ninterface SVGAnimatedInteger {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedInteger: {\n prototype: SVGAnimatedInteger;\n new(): SVGAnimatedInteger;\n};\n\ninterface SVGAnimatedLength {\n readonly animVal: SVGLength;\n readonly baseVal: SVGLength;\n}\n\ndeclare var SVGAnimatedLength: {\n prototype: SVGAnimatedLength;\n new(): SVGAnimatedLength;\n};\n\ninterface SVGAnimatedLengthList {\n readonly animVal: SVGLengthList;\n readonly baseVal: SVGLengthList;\n}\n\ndeclare var SVGAnimatedLengthList: {\n prototype: SVGAnimatedLengthList;\n new(): SVGAnimatedLengthList;\n};\n\ninterface SVGAnimatedNumber {\n readonly animVal: number;\n baseVal: number;\n}\n\ndeclare var SVGAnimatedNumber: {\n prototype: SVGAnimatedNumber;\n new(): SVGAnimatedNumber;\n};\n\ninterface SVGAnimatedNumberList {\n readonly animVal: SVGNumberList;\n readonly baseVal: SVGNumberList;\n}\n\ndeclare var SVGAnimatedNumberList: {\n prototype: SVGAnimatedNumberList;\n new(): SVGAnimatedNumberList;\n};\n\ninterface SVGAnimatedPoints {\n readonly animatedPoints: SVGPointList;\n readonly points: SVGPointList;\n}\n\ninterface SVGAnimatedPreserveAspectRatio {\n readonly animVal: SVGPreserveAspectRatio;\n readonly baseVal: SVGPreserveAspectRatio;\n}\n\ndeclare var SVGAnimatedPreserveAspectRatio: {\n prototype: SVGAnimatedPreserveAspectRatio;\n new(): SVGAnimatedPreserveAspectRatio;\n};\n\ninterface SVGAnimatedRect {\n readonly animVal: SVGRect;\n readonly baseVal: SVGRect;\n}\n\ndeclare var SVGAnimatedRect: {\n prototype: SVGAnimatedRect;\n new(): SVGAnimatedRect;\n};\n\ninterface SVGAnimatedString {\n readonly animVal: string;\n baseVal: string;\n}\n\ndeclare var SVGAnimatedString: {\n prototype: SVGAnimatedString;\n new(): SVGAnimatedString;\n};\n\ninterface SVGAnimatedTransformList {\n readonly animVal: SVGTransformList;\n readonly baseVal: SVGTransformList;\n}\n\ndeclare var SVGAnimatedTransformList: {\n prototype: SVGAnimatedTransformList;\n new(): SVGAnimatedTransformList;\n};\n\ninterface SVGCircleElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGCircleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGCircleElement: {\n prototype: SVGCircleElement;\n new(): SVGCircleElement;\n};\n\ninterface SVGClipPathElement extends SVGGraphicsElement, SVGUnitTypes {\n readonly clipPathUnits: SVGAnimatedEnumeration;\n addEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGClipPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGClipPathElement: {\n prototype: SVGClipPathElement;\n new(): SVGClipPathElement;\n};\n\ninterface SVGComponentTransferFunctionElement extends SVGElement {\n readonly amplitude: SVGAnimatedNumber;\n readonly exponent: SVGAnimatedNumber;\n readonly intercept: SVGAnimatedNumber;\n readonly offset: SVGAnimatedNumber;\n readonly slope: SVGAnimatedNumber;\n readonly tableValues: SVGAnimatedNumberList;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGComponentTransferFunctionElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGComponentTransferFunctionElement: {\n prototype: SVGComponentTransferFunctionElement;\n new(): SVGComponentTransferFunctionElement;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_GAMMA: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_LINEAR: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_TABLE: number;\n readonly SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN: number;\n};\n\ninterface SVGDefsElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDefsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDefsElement: {\n prototype: SVGDefsElement;\n new(): SVGDefsElement;\n};\n\ninterface SVGDescElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGDescElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGDescElement: {\n prototype: SVGDescElement;\n new(): SVGDescElement;\n};\n\ninterface SVGElementEventMap extends ElementEventMap {\n \"click\": MouseEvent;\n \"dblclick\": MouseEvent;\n \"focusin\": FocusEvent;\n \"focusout\": FocusEvent;\n \"load\": Event;\n \"mousedown\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n}\n\ninterface SVGElement extends Element, ElementCSSInlineStyle {\n readonly className: any;\n onclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n ondblclick: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onfocusin: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onfocusout: ((this: SVGElement, ev: FocusEvent) => any) | null;\n onload: ((this: SVGElement, ev: Event) => any) | null;\n onmousedown: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmousemove: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseout: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseover: ((this: SVGElement, ev: MouseEvent) => any) | null;\n onmouseup: ((this: SVGElement, ev: MouseEvent) => any) | null;\n readonly ownerSVGElement: SVGSVGElement | null;\n readonly viewportElement: SVGElement | null;\n /** @deprecated */\n xmlbase: string;\n addEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGElement: {\n prototype: SVGElement;\n new(): SVGElement;\n};\n\ninterface SVGElementInstance extends EventTarget {\n readonly childNodes: SVGElementInstanceList;\n readonly correspondingElement: SVGElement;\n readonly correspondingUseElement: SVGUseElement;\n readonly firstChild: SVGElementInstance;\n readonly lastChild: SVGElementInstance;\n readonly nextSibling: SVGElementInstance;\n readonly parentNode: SVGElementInstance;\n readonly previousSibling: SVGElementInstance;\n}\n\ndeclare var SVGElementInstance: {\n prototype: SVGElementInstance;\n new(): SVGElementInstance;\n};\n\ninterface SVGElementInstanceList {\n /** @deprecated */\n readonly length: number;\n /** @deprecated */\n item(index: number): SVGElementInstance;\n}\n\ndeclare var SVGElementInstanceList: {\n prototype: SVGElementInstanceList;\n new(): SVGElementInstanceList;\n};\n\ninterface SVGEllipseElement extends SVGGraphicsElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGEllipseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGEllipseElement: {\n prototype: SVGEllipseElement;\n new(): SVGEllipseElement;\n};\n\ninterface SVGFEBlendElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly mode: SVGAnimatedEnumeration;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEBlendElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEBlendElement: {\n prototype: SVGFEBlendElement;\n new(): SVGFEBlendElement;\n readonly SVG_FEBLEND_MODE_COLOR: number;\n readonly SVG_FEBLEND_MODE_COLOR_BURN: number;\n readonly SVG_FEBLEND_MODE_COLOR_DODGE: number;\n readonly SVG_FEBLEND_MODE_DARKEN: number;\n readonly SVG_FEBLEND_MODE_DIFFERENCE: number;\n readonly SVG_FEBLEND_MODE_EXCLUSION: number;\n readonly SVG_FEBLEND_MODE_HARD_LIGHT: number;\n readonly SVG_FEBLEND_MODE_HUE: number;\n readonly SVG_FEBLEND_MODE_LIGHTEN: number;\n readonly SVG_FEBLEND_MODE_LUMINOSITY: number;\n readonly SVG_FEBLEND_MODE_MULTIPLY: number;\n readonly SVG_FEBLEND_MODE_NORMAL: number;\n readonly SVG_FEBLEND_MODE_OVERLAY: number;\n readonly SVG_FEBLEND_MODE_SATURATION: number;\n readonly SVG_FEBLEND_MODE_SCREEN: number;\n readonly SVG_FEBLEND_MODE_SOFT_LIGHT: number;\n readonly SVG_FEBLEND_MODE_UNKNOWN: number;\n};\n\ninterface SVGFEColorMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly type: SVGAnimatedEnumeration;\n readonly values: SVGAnimatedNumberList;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEColorMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEColorMatrixElement: {\n prototype: SVGFEColorMatrixElement;\n new(): SVGFEColorMatrixElement;\n readonly SVG_FECOLORMATRIX_TYPE_HUEROTATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA: number;\n readonly SVG_FECOLORMATRIX_TYPE_MATRIX: number;\n readonly SVG_FECOLORMATRIX_TYPE_SATURATE: number;\n readonly SVG_FECOLORMATRIX_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFEComponentTransferElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEComponentTransferElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEComponentTransferElement: {\n prototype: SVGFEComponentTransferElement;\n new(): SVGFEComponentTransferElement;\n};\n\ninterface SVGFECompositeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly k1: SVGAnimatedNumber;\n readonly k2: SVGAnimatedNumber;\n readonly k3: SVGAnimatedNumber;\n readonly k4: SVGAnimatedNumber;\n readonly operator: SVGAnimatedEnumeration;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n addEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFECompositeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFECompositeElement: {\n prototype: SVGFECompositeElement;\n new(): SVGFECompositeElement;\n readonly SVG_FECOMPOSITE_OPERATOR_ARITHMETIC: number;\n readonly SVG_FECOMPOSITE_OPERATOR_ATOP: number;\n readonly SVG_FECOMPOSITE_OPERATOR_IN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OUT: number;\n readonly SVG_FECOMPOSITE_OPERATOR_OVER: number;\n readonly SVG_FECOMPOSITE_OPERATOR_UNKNOWN: number;\n readonly SVG_FECOMPOSITE_OPERATOR_XOR: number;\n};\n\ninterface SVGFEConvolveMatrixElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly bias: SVGAnimatedNumber;\n readonly divisor: SVGAnimatedNumber;\n readonly edgeMode: SVGAnimatedEnumeration;\n readonly in1: SVGAnimatedString;\n readonly kernelMatrix: SVGAnimatedNumberList;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly orderX: SVGAnimatedInteger;\n readonly orderY: SVGAnimatedInteger;\n readonly preserveAlpha: SVGAnimatedBoolean;\n readonly targetX: SVGAnimatedInteger;\n readonly targetY: SVGAnimatedInteger;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n addEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEConvolveMatrixElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEConvolveMatrixElement: {\n prototype: SVGFEConvolveMatrixElement;\n new(): SVGFEConvolveMatrixElement;\n readonly SVG_EDGEMODE_DUPLICATE: number;\n readonly SVG_EDGEMODE_NONE: number;\n readonly SVG_EDGEMODE_UNKNOWN: number;\n readonly SVG_EDGEMODE_WRAP: number;\n};\n\ninterface SVGFEDiffuseLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly diffuseConstant: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDiffuseLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDiffuseLightingElement: {\n prototype: SVGFEDiffuseLightingElement;\n new(): SVGFEDiffuseLightingElement;\n};\n\ninterface SVGFEDisplacementMapElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly in2: SVGAnimatedString;\n readonly scale: SVGAnimatedNumber;\n readonly xChannelSelector: SVGAnimatedEnumeration;\n readonly yChannelSelector: SVGAnimatedEnumeration;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDisplacementMapElement: {\n prototype: SVGFEDisplacementMapElement;\n new(): SVGFEDisplacementMapElement;\n readonly SVG_CHANNEL_A: number;\n readonly SVG_CHANNEL_B: number;\n readonly SVG_CHANNEL_G: number;\n readonly SVG_CHANNEL_R: number;\n readonly SVG_CHANNEL_UNKNOWN: number;\n};\n\ninterface SVGFEDistantLightElement extends SVGElement {\n readonly azimuth: SVGAnimatedNumber;\n readonly elevation: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEDistantLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEDistantLightElement: {\n prototype: SVGFEDistantLightElement;\n new(): SVGFEDistantLightElement;\n};\n\ninterface SVGFEFloodElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFloodElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFloodElement: {\n prototype: SVGFEFloodElement;\n new(): SVGFEFloodElement;\n};\n\ninterface SVGFEFuncAElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncAElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncAElement: {\n prototype: SVGFEFuncAElement;\n new(): SVGFEFuncAElement;\n};\n\ninterface SVGFEFuncBElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncBElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncBElement: {\n prototype: SVGFEFuncBElement;\n new(): SVGFEFuncBElement;\n};\n\ninterface SVGFEFuncGElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncGElement: {\n prototype: SVGFEFuncGElement;\n new(): SVGFEFuncGElement;\n};\n\ninterface SVGFEFuncRElement extends SVGComponentTransferFunctionElement {\n addEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEFuncRElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEFuncRElement: {\n prototype: SVGFEFuncRElement;\n new(): SVGFEFuncRElement;\n};\n\ninterface SVGFEGaussianBlurElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly stdDeviationX: SVGAnimatedNumber;\n readonly stdDeviationY: SVGAnimatedNumber;\n setStdDeviation(stdDeviationX: number, stdDeviationY: number): void;\n addEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEGaussianBlurElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEGaussianBlurElement: {\n prototype: SVGFEGaussianBlurElement;\n new(): SVGFEGaussianBlurElement;\n};\n\ninterface SVGFEImageElement extends SVGElement, SVGFilterPrimitiveStandardAttributes, SVGURIReference {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n addEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEImageElement: {\n prototype: SVGFEImageElement;\n new(): SVGFEImageElement;\n};\n\ninterface SVGFEMergeElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n addEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeElement: {\n prototype: SVGFEMergeElement;\n new(): SVGFEMergeElement;\n};\n\ninterface SVGFEMergeNodeElement extends SVGElement {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMergeNodeElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMergeNodeElement: {\n prototype: SVGFEMergeNodeElement;\n new(): SVGFEMergeNodeElement;\n};\n\ninterface SVGFEMorphologyElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly operator: SVGAnimatedEnumeration;\n readonly radiusX: SVGAnimatedNumber;\n readonly radiusY: SVGAnimatedNumber;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEMorphologyElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEMorphologyElement: {\n prototype: SVGFEMorphologyElement;\n new(): SVGFEMorphologyElement;\n readonly SVG_MORPHOLOGY_OPERATOR_DILATE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_ERODE: number;\n readonly SVG_MORPHOLOGY_OPERATOR_UNKNOWN: number;\n};\n\ninterface SVGFEOffsetElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly dx: SVGAnimatedNumber;\n readonly dy: SVGAnimatedNumber;\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEOffsetElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEOffsetElement: {\n prototype: SVGFEOffsetElement;\n new(): SVGFEOffsetElement;\n};\n\ninterface SVGFEPointLightElement extends SVGElement {\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFEPointLightElement: {\n prototype: SVGFEPointLightElement;\n new(): SVGFEPointLightElement;\n};\n\ninterface SVGFESpecularLightingElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n readonly kernelUnitLengthX: SVGAnimatedNumber;\n readonly kernelUnitLengthY: SVGAnimatedNumber;\n readonly specularConstant: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly surfaceScale: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpecularLightingElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpecularLightingElement: {\n prototype: SVGFESpecularLightingElement;\n new(): SVGFESpecularLightingElement;\n};\n\ninterface SVGFESpotLightElement extends SVGElement {\n readonly limitingConeAngle: SVGAnimatedNumber;\n readonly pointsAtX: SVGAnimatedNumber;\n readonly pointsAtY: SVGAnimatedNumber;\n readonly pointsAtZ: SVGAnimatedNumber;\n readonly specularExponent: SVGAnimatedNumber;\n readonly x: SVGAnimatedNumber;\n readonly y: SVGAnimatedNumber;\n readonly z: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFESpotLightElement: {\n prototype: SVGFESpotLightElement;\n new(): SVGFESpotLightElement;\n};\n\ninterface SVGFETileElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly in1: SVGAnimatedString;\n addEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETileElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETileElement: {\n prototype: SVGFETileElement;\n new(): SVGFETileElement;\n};\n\ninterface SVGFETurbulenceElement extends SVGElement, SVGFilterPrimitiveStandardAttributes {\n readonly baseFrequencyX: SVGAnimatedNumber;\n readonly baseFrequencyY: SVGAnimatedNumber;\n readonly numOctaves: SVGAnimatedInteger;\n readonly seed: SVGAnimatedNumber;\n readonly stitchTiles: SVGAnimatedEnumeration;\n readonly type: SVGAnimatedEnumeration;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFETurbulenceElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFETurbulenceElement: {\n prototype: SVGFETurbulenceElement;\n new(): SVGFETurbulenceElement;\n readonly SVG_STITCHTYPE_NOSTITCH: number;\n readonly SVG_STITCHTYPE_STITCH: number;\n readonly SVG_STITCHTYPE_UNKNOWN: number;\n readonly SVG_TURBULENCE_TYPE_FRACTALNOISE: number;\n readonly SVG_TURBULENCE_TYPE_TURBULENCE: number;\n readonly SVG_TURBULENCE_TYPE_UNKNOWN: number;\n};\n\ninterface SVGFilterElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n /** @deprecated */\n readonly filterResX: SVGAnimatedInteger;\n /** @deprecated */\n readonly filterResY: SVGAnimatedInteger;\n readonly filterUnits: SVGAnimatedEnumeration;\n readonly height: SVGAnimatedLength;\n readonly primitiveUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n /** @deprecated */\n setFilterRes(filterResX: number, filterResY: number): void;\n addEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGFilterElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGFilterElement: {\n prototype: SVGFilterElement;\n new(): SVGFilterElement;\n};\n\ninterface SVGFilterPrimitiveStandardAttributes {\n readonly height: SVGAnimatedLength;\n readonly result: SVGAnimatedString;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n}\n\ninterface SVGFitToViewBox {\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly viewBox: SVGAnimatedRect;\n}\n\ninterface SVGForeignObjectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGForeignObjectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGForeignObjectElement: {\n prototype: SVGForeignObjectElement;\n new(): SVGForeignObjectElement;\n};\n\ninterface SVGGElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGElement: {\n prototype: SVGGElement;\n new(): SVGGElement;\n};\n\ninterface SVGGradientElement extends SVGElement, SVGUnitTypes, SVGURIReference {\n readonly gradientTransform: SVGAnimatedTransformList;\n readonly gradientUnits: SVGAnimatedEnumeration;\n readonly spreadMethod: SVGAnimatedEnumeration;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGradientElement: {\n prototype: SVGGradientElement;\n new(): SVGGradientElement;\n readonly SVG_SPREADMETHOD_PAD: number;\n readonly SVG_SPREADMETHOD_REFLECT: number;\n readonly SVG_SPREADMETHOD_REPEAT: number;\n readonly SVG_SPREADMETHOD_UNKNOWN: number;\n};\n\ninterface SVGGraphicsElement extends SVGElement, SVGTests {\n /** @deprecated */\n readonly farthestViewportElement: SVGElement | null;\n /** @deprecated */\n readonly nearestViewportElement: SVGElement | null;\n readonly transform: SVGAnimatedTransformList;\n getBBox(): SVGRect;\n getCTM(): SVGMatrix | null;\n getScreenCTM(): SVGMatrix | null;\n /** @deprecated */\n getTransformToElement(element: SVGElement): SVGMatrix;\n addEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGGraphicsElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGGraphicsElement: {\n prototype: SVGGraphicsElement;\n new(): SVGGraphicsElement;\n};\n\ninterface SVGImageElement extends SVGGraphicsElement, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly preserveAspectRatio: SVGAnimatedPreserveAspectRatio;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGImageElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGImageElement: {\n prototype: SVGImageElement;\n new(): SVGImageElement;\n};\n\ninterface SVGLength {\n readonly unitType: number;\n value: number;\n valueAsString: string;\n valueInSpecifiedUnits: number;\n convertToSpecifiedUnits(unitType: number): void;\n newValueSpecifiedUnits(unitType: number, valueInSpecifiedUnits: number): void;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n}\n\ndeclare var SVGLength: {\n prototype: SVGLength;\n new(): SVGLength;\n readonly SVG_LENGTHTYPE_CM: number;\n readonly SVG_LENGTHTYPE_EMS: number;\n readonly SVG_LENGTHTYPE_EXS: number;\n readonly SVG_LENGTHTYPE_IN: number;\n readonly SVG_LENGTHTYPE_MM: number;\n readonly SVG_LENGTHTYPE_NUMBER: number;\n readonly SVG_LENGTHTYPE_PC: number;\n readonly SVG_LENGTHTYPE_PERCENTAGE: number;\n readonly SVG_LENGTHTYPE_PT: number;\n readonly SVG_LENGTHTYPE_PX: number;\n readonly SVG_LENGTHTYPE_UNKNOWN: number;\n};\n\ninterface SVGLengthList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGLength): SVGLength;\n clear(): void;\n getItem(index: number): SVGLength;\n initialize(newItem: SVGLength): SVGLength;\n insertItemBefore(newItem: SVGLength, index: number): SVGLength;\n removeItem(index: number): SVGLength;\n replaceItem(newItem: SVGLength, index: number): SVGLength;\n}\n\ndeclare var SVGLengthList: {\n prototype: SVGLengthList;\n new(): SVGLengthList;\n};\n\ninterface SVGLineElement extends SVGGraphicsElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLineElement: {\n prototype: SVGLineElement;\n new(): SVGLineElement;\n};\n\ninterface SVGLinearGradientElement extends SVGGradientElement {\n readonly x1: SVGAnimatedLength;\n readonly x2: SVGAnimatedLength;\n readonly y1: SVGAnimatedLength;\n readonly y2: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGLinearGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGLinearGradientElement: {\n prototype: SVGLinearGradientElement;\n new(): SVGLinearGradientElement;\n};\n\ninterface SVGMarkerElement extends SVGElement, SVGFitToViewBox {\n readonly markerHeight: SVGAnimatedLength;\n readonly markerUnits: SVGAnimatedEnumeration;\n readonly markerWidth: SVGAnimatedLength;\n readonly orientAngle: SVGAnimatedAngle;\n readonly orientType: SVGAnimatedEnumeration;\n readonly refX: SVGAnimatedLength;\n readonly refY: SVGAnimatedLength;\n setOrientToAngle(angle: SVGAngle): void;\n setOrientToAuto(): void;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMarkerElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMarkerElement: {\n prototype: SVGMarkerElement;\n new(): SVGMarkerElement;\n readonly SVG_MARKERUNITS_STROKEWIDTH: number;\n readonly SVG_MARKERUNITS_UNKNOWN: number;\n readonly SVG_MARKERUNITS_USERSPACEONUSE: number;\n readonly SVG_MARKER_ORIENT_ANGLE: number;\n readonly SVG_MARKER_ORIENT_AUTO: number;\n readonly SVG_MARKER_ORIENT_UNKNOWN: number;\n};\n\ninterface SVGMaskElement extends SVGElement, SVGTests, SVGUnitTypes {\n readonly height: SVGAnimatedLength;\n readonly maskContentUnits: SVGAnimatedEnumeration;\n readonly maskUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMaskElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMaskElement: {\n prototype: SVGMaskElement;\n new(): SVGMaskElement;\n};\n\ninterface SVGMetadataElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGMetadataElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGMetadataElement: {\n prototype: SVGMetadataElement;\n new(): SVGMetadataElement;\n};\n\ninterface SVGNumber {\n value: number;\n}\n\ndeclare var SVGNumber: {\n prototype: SVGNumber;\n new(): SVGNumber;\n};\n\ninterface SVGNumberList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGNumber): SVGNumber;\n clear(): void;\n getItem(index: number): SVGNumber;\n initialize(newItem: SVGNumber): SVGNumber;\n insertItemBefore(newItem: SVGNumber, index: number): SVGNumber;\n removeItem(index: number): SVGNumber;\n replaceItem(newItem: SVGNumber, index: number): SVGNumber;\n}\n\ndeclare var SVGNumberList: {\n prototype: SVGNumberList;\n new(): SVGNumberList;\n};\n\ninterface SVGPathElement extends SVGGraphicsElement {\n /** @deprecated */\n readonly pathSegList: SVGPathSegList;\n /** @deprecated */\n createSVGPathSegArcAbs(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcAbs;\n /** @deprecated */\n createSVGPathSegArcRel(x: number, y: number, r1: number, r2: number, angle: number, largeArcFlag: boolean, sweepFlag: boolean): SVGPathSegArcRel;\n /** @deprecated */\n createSVGPathSegClosePath(): SVGPathSegClosePath;\n /** @deprecated */\n createSVGPathSegCurvetoCubicAbs(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicRel(x: number, y: number, x1: number, y1: number, x2: number, y2: number): SVGPathSegCurvetoCubicRel;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothAbs(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoCubicSmoothRel(x: number, y: number, x2: number, y2: number): SVGPathSegCurvetoCubicSmoothRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticAbs(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticRel(x: number, y: number, x1: number, y1: number): SVGPathSegCurvetoQuadraticRel;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothAbs(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothAbs;\n /** @deprecated */\n createSVGPathSegCurvetoQuadraticSmoothRel(x: number, y: number): SVGPathSegCurvetoQuadraticSmoothRel;\n /** @deprecated */\n createSVGPathSegLinetoAbs(x: number, y: number): SVGPathSegLinetoAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalAbs(x: number): SVGPathSegLinetoHorizontalAbs;\n /** @deprecated */\n createSVGPathSegLinetoHorizontalRel(x: number): SVGPathSegLinetoHorizontalRel;\n /** @deprecated */\n createSVGPathSegLinetoRel(x: number, y: number): SVGPathSegLinetoRel;\n /** @deprecated */\n createSVGPathSegLinetoVerticalAbs(y: number): SVGPathSegLinetoVerticalAbs;\n /** @deprecated */\n createSVGPathSegLinetoVerticalRel(y: number): SVGPathSegLinetoVerticalRel;\n /** @deprecated */\n createSVGPathSegMovetoAbs(x: number, y: number): SVGPathSegMovetoAbs;\n /** @deprecated */\n createSVGPathSegMovetoRel(x: number, y: number): SVGPathSegMovetoRel;\n /** @deprecated */\n getPathSegAtLength(distance: number): number;\n getPointAtLength(distance: number): SVGPoint;\n getTotalLength(): number;\n addEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPathElement: {\n prototype: SVGPathElement;\n new(): SVGPathElement;\n};\n\ninterface SVGPathSeg {\n readonly pathSegType: number;\n readonly pathSegTypeAsLetter: string;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n}\n\ndeclare var SVGPathSeg: {\n prototype: SVGPathSeg;\n new(): SVGPathSeg;\n readonly PATHSEG_ARC_ABS: number;\n readonly PATHSEG_ARC_REL: number;\n readonly PATHSEG_CLOSEPATH: number;\n readonly PATHSEG_CURVETO_CUBIC_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_REL: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_CUBIC_SMOOTH_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_REL: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: number;\n readonly PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: number;\n readonly PATHSEG_LINETO_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_ABS: number;\n readonly PATHSEG_LINETO_HORIZONTAL_REL: number;\n readonly PATHSEG_LINETO_REL: number;\n readonly PATHSEG_LINETO_VERTICAL_ABS: number;\n readonly PATHSEG_LINETO_VERTICAL_REL: number;\n readonly PATHSEG_MOVETO_ABS: number;\n readonly PATHSEG_MOVETO_REL: number;\n readonly PATHSEG_UNKNOWN: number;\n};\n\ninterface SVGPathSegArcAbs extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcAbs: {\n prototype: SVGPathSegArcAbs;\n new(): SVGPathSegArcAbs;\n};\n\ninterface SVGPathSegArcRel extends SVGPathSeg {\n angle: number;\n largeArcFlag: boolean;\n r1: number;\n r2: number;\n sweepFlag: boolean;\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegArcRel: {\n prototype: SVGPathSegArcRel;\n new(): SVGPathSegArcRel;\n};\n\ninterface SVGPathSegClosePath extends SVGPathSeg {\n}\n\ndeclare var SVGPathSegClosePath: {\n prototype: SVGPathSegClosePath;\n new(): SVGPathSegClosePath;\n};\n\ninterface SVGPathSegCurvetoCubicAbs extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicAbs: {\n prototype: SVGPathSegCurvetoCubicAbs;\n new(): SVGPathSegCurvetoCubicAbs;\n};\n\ninterface SVGPathSegCurvetoCubicRel extends SVGPathSeg {\n x: number;\n x1: number;\n x2: number;\n y: number;\n y1: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicRel: {\n prototype: SVGPathSegCurvetoCubicRel;\n new(): SVGPathSegCurvetoCubicRel;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothAbs extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothAbs: {\n prototype: SVGPathSegCurvetoCubicSmoothAbs;\n new(): SVGPathSegCurvetoCubicSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoCubicSmoothRel extends SVGPathSeg {\n x: number;\n x2: number;\n y: number;\n y2: number;\n}\n\ndeclare var SVGPathSegCurvetoCubicSmoothRel: {\n prototype: SVGPathSegCurvetoCubicSmoothRel;\n new(): SVGPathSegCurvetoCubicSmoothRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticAbs extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticAbs: {\n prototype: SVGPathSegCurvetoQuadraticAbs;\n new(): SVGPathSegCurvetoQuadraticAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticRel extends SVGPathSeg {\n x: number;\n x1: number;\n y: number;\n y1: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticRel: {\n prototype: SVGPathSegCurvetoQuadraticRel;\n new(): SVGPathSegCurvetoQuadraticRel;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothAbs: {\n prototype: SVGPathSegCurvetoQuadraticSmoothAbs;\n new(): SVGPathSegCurvetoQuadraticSmoothAbs;\n};\n\ninterface SVGPathSegCurvetoQuadraticSmoothRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegCurvetoQuadraticSmoothRel: {\n prototype: SVGPathSegCurvetoQuadraticSmoothRel;\n new(): SVGPathSegCurvetoQuadraticSmoothRel;\n};\n\ninterface SVGPathSegLinetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoAbs: {\n prototype: SVGPathSegLinetoAbs;\n new(): SVGPathSegLinetoAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalAbs extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalAbs: {\n prototype: SVGPathSegLinetoHorizontalAbs;\n new(): SVGPathSegLinetoHorizontalAbs;\n};\n\ninterface SVGPathSegLinetoHorizontalRel extends SVGPathSeg {\n x: number;\n}\n\ndeclare var SVGPathSegLinetoHorizontalRel: {\n prototype: SVGPathSegLinetoHorizontalRel;\n new(): SVGPathSegLinetoHorizontalRel;\n};\n\ninterface SVGPathSegLinetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegLinetoRel: {\n prototype: SVGPathSegLinetoRel;\n new(): SVGPathSegLinetoRel;\n};\n\ninterface SVGPathSegLinetoVerticalAbs extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalAbs: {\n prototype: SVGPathSegLinetoVerticalAbs;\n new(): SVGPathSegLinetoVerticalAbs;\n};\n\ninterface SVGPathSegLinetoVerticalRel extends SVGPathSeg {\n y: number;\n}\n\ndeclare var SVGPathSegLinetoVerticalRel: {\n prototype: SVGPathSegLinetoVerticalRel;\n new(): SVGPathSegLinetoVerticalRel;\n};\n\ninterface SVGPathSegList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPathSeg): SVGPathSeg;\n clear(): void;\n getItem(index: number): SVGPathSeg;\n initialize(newItem: SVGPathSeg): SVGPathSeg;\n insertItemBefore(newItem: SVGPathSeg, index: number): SVGPathSeg;\n removeItem(index: number): SVGPathSeg;\n replaceItem(newItem: SVGPathSeg, index: number): SVGPathSeg;\n}\n\ndeclare var SVGPathSegList: {\n prototype: SVGPathSegList;\n new(): SVGPathSegList;\n};\n\ninterface SVGPathSegMovetoAbs extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoAbs: {\n prototype: SVGPathSegMovetoAbs;\n new(): SVGPathSegMovetoAbs;\n};\n\ninterface SVGPathSegMovetoRel extends SVGPathSeg {\n x: number;\n y: number;\n}\n\ndeclare var SVGPathSegMovetoRel: {\n prototype: SVGPathSegMovetoRel;\n new(): SVGPathSegMovetoRel;\n};\n\ninterface SVGPatternElement extends SVGElement, SVGTests, SVGUnitTypes, SVGFitToViewBox, SVGURIReference {\n readonly height: SVGAnimatedLength;\n readonly patternContentUnits: SVGAnimatedEnumeration;\n readonly patternTransform: SVGAnimatedTransformList;\n readonly patternUnits: SVGAnimatedEnumeration;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPatternElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPatternElement: {\n prototype: SVGPatternElement;\n new(): SVGPatternElement;\n};\n\ninterface SVGPointList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGPoint): SVGPoint;\n clear(): void;\n getItem(index: number): SVGPoint;\n initialize(newItem: SVGPoint): SVGPoint;\n insertItemBefore(newItem: SVGPoint, index: number): SVGPoint;\n removeItem(index: number): SVGPoint;\n replaceItem(newItem: SVGPoint, index: number): SVGPoint;\n}\n\ndeclare var SVGPointList: {\n prototype: SVGPointList;\n new(): SVGPointList;\n};\n\ninterface SVGPolygonElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolygonElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolygonElement: {\n prototype: SVGPolygonElement;\n new(): SVGPolygonElement;\n};\n\ninterface SVGPolylineElement extends SVGGraphicsElement, SVGAnimatedPoints {\n addEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGPolylineElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGPolylineElement: {\n prototype: SVGPolylineElement;\n new(): SVGPolylineElement;\n};\n\ninterface SVGPreserveAspectRatio {\n align: number;\n meetOrSlice: number;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n}\n\ndeclare var SVGPreserveAspectRatio: {\n prototype: SVGPreserveAspectRatio;\n new(): SVGPreserveAspectRatio;\n readonly SVG_MEETORSLICE_MEET: number;\n readonly SVG_MEETORSLICE_SLICE: number;\n readonly SVG_MEETORSLICE_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_NONE: number;\n readonly SVG_PRESERVEASPECTRATIO_UNKNOWN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMAXYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMIDYMIN: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMAX: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMID: number;\n readonly SVG_PRESERVEASPECTRATIO_XMINYMIN: number;\n};\n\ninterface SVGRadialGradientElement extends SVGGradientElement {\n readonly cx: SVGAnimatedLength;\n readonly cy: SVGAnimatedLength;\n readonly fx: SVGAnimatedLength;\n readonly fy: SVGAnimatedLength;\n readonly r: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRadialGradientElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRadialGradientElement: {\n prototype: SVGRadialGradientElement;\n new(): SVGRadialGradientElement;\n};\n\ninterface SVGRectElement extends SVGGraphicsElement {\n readonly height: SVGAnimatedLength;\n readonly rx: SVGAnimatedLength;\n readonly ry: SVGAnimatedLength;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGRectElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGRectElement: {\n prototype: SVGRectElement;\n new(): SVGRectElement;\n};\n\ninterface SVGSVGElementEventMap extends SVGElementEventMap {\n \"SVGAbort\": Event;\n \"SVGError\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"SVGUnload\": Event;\n \"SVGZoom\": SVGZoomEvent;\n}\n\ninterface SVGSVGElement extends SVGGraphicsElement, DocumentEvent, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n contentScriptType: string;\n /** @deprecated */\n contentStyleType: string;\n currentScale: number;\n readonly currentTranslate: SVGPoint;\n readonly height: SVGAnimatedLength;\n onabort: ((this: SVGSVGElement, ev: Event) => any) | null;\n onerror: ((this: SVGSVGElement, ev: Event) => any) | null;\n onresize: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onscroll: ((this: SVGSVGElement, ev: UIEvent) => any) | null;\n onunload: ((this: SVGSVGElement, ev: Event) => any) | null;\n onzoom: ((this: SVGSVGElement, ev: SVGZoomEvent) => any) | null;\n /** @deprecated */\n readonly pixelUnitToMillimeterX: number;\n /** @deprecated */\n readonly pixelUnitToMillimeterY: number;\n /** @deprecated */\n readonly screenPixelToMillimeterX: number;\n /** @deprecated */\n readonly screenPixelToMillimeterY: number;\n /** @deprecated */\n readonly viewport: SVGRect;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n checkEnclosure(element: SVGElement, rect: SVGRect): boolean;\n checkIntersection(element: SVGElement, rect: SVGRect): boolean;\n createSVGAngle(): SVGAngle;\n createSVGLength(): SVGLength;\n createSVGMatrix(): SVGMatrix;\n createSVGNumber(): SVGNumber;\n createSVGPoint(): SVGPoint;\n createSVGRect(): SVGRect;\n createSVGTransform(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n deselectAll(): void;\n /** @deprecated */\n forceRedraw(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n /** @deprecated */\n getCurrentTime(): number;\n getElementById(elementId: string): Element;\n getEnclosureList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n getIntersectionList(rect: SVGRect, referenceElement: SVGElement): NodeListOf;\n /** @deprecated */\n pauseAnimations(): void;\n /** @deprecated */\n setCurrentTime(seconds: number): void;\n /** @deprecated */\n suspendRedraw(maxWaitMilliseconds: number): number;\n /** @deprecated */\n unpauseAnimations(): void;\n /** @deprecated */\n unsuspendRedraw(suspendHandleID: number): void;\n /** @deprecated */\n unsuspendRedrawAll(): void;\n addEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSVGElement, ev: SVGSVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSVGElement: {\n prototype: SVGSVGElement;\n new(): SVGSVGElement;\n};\n\ninterface SVGScriptElement extends SVGElement, SVGURIReference {\n type: string;\n addEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGScriptElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGScriptElement: {\n prototype: SVGScriptElement;\n new(): SVGScriptElement;\n};\n\ninterface SVGStopElement extends SVGElement {\n readonly offset: SVGAnimatedNumber;\n addEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStopElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStopElement: {\n prototype: SVGStopElement;\n new(): SVGStopElement;\n};\n\ninterface SVGStringList {\n readonly numberOfItems: number;\n appendItem(newItem: string): string;\n clear(): void;\n getItem(index: number): string;\n initialize(newItem: string): string;\n insertItemBefore(newItem: string, index: number): string;\n removeItem(index: number): string;\n replaceItem(newItem: string, index: number): string;\n}\n\ndeclare var SVGStringList: {\n prototype: SVGStringList;\n new(): SVGStringList;\n};\n\ninterface SVGStyleElement extends SVGElement {\n disabled: boolean;\n media: string;\n title: string;\n type: string;\n addEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGStyleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGStyleElement: {\n prototype: SVGStyleElement;\n new(): SVGStyleElement;\n};\n\ninterface SVGSwitchElement extends SVGGraphicsElement {\n addEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSwitchElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSwitchElement: {\n prototype: SVGSwitchElement;\n new(): SVGSwitchElement;\n};\n\ninterface SVGSymbolElement extends SVGElement, SVGFitToViewBox {\n addEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGSymbolElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGSymbolElement: {\n prototype: SVGSymbolElement;\n new(): SVGSymbolElement;\n};\n\ninterface SVGTSpanElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTSpanElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTSpanElement: {\n prototype: SVGTSpanElement;\n new(): SVGTSpanElement;\n};\n\ninterface SVGTests {\n readonly requiredExtensions: SVGStringList;\n /** @deprecated */\n readonly requiredFeatures: SVGStringList;\n readonly systemLanguage: SVGStringList;\n /** @deprecated */\n hasExtension(extension: string): boolean;\n}\n\ninterface SVGTextContentElement extends SVGGraphicsElement {\n readonly lengthAdjust: SVGAnimatedEnumeration;\n readonly textLength: SVGAnimatedLength;\n getCharNumAtPosition(point: SVGPoint): number;\n getComputedTextLength(): number;\n getEndPositionOfChar(charnum: number): SVGPoint;\n getExtentOfChar(charnum: number): SVGRect;\n getNumberOfChars(): number;\n getRotationOfChar(charnum: number): number;\n getStartPositionOfChar(charnum: number): SVGPoint;\n getSubStringLength(charnum: number, nchars: number): number;\n selectSubString(charnum: number, nchars: number): void;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextContentElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextContentElement: {\n prototype: SVGTextContentElement;\n new(): SVGTextContentElement;\n readonly LENGTHADJUST_SPACING: number;\n readonly LENGTHADJUST_SPACINGANDGLYPHS: number;\n readonly LENGTHADJUST_UNKNOWN: number;\n};\n\ninterface SVGTextElement extends SVGTextPositioningElement {\n addEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextElement: {\n prototype: SVGTextElement;\n new(): SVGTextElement;\n};\n\ninterface SVGTextPathElement extends SVGTextContentElement, SVGURIReference {\n readonly method: SVGAnimatedEnumeration;\n readonly spacing: SVGAnimatedEnumeration;\n readonly startOffset: SVGAnimatedLength;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n addEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPathElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPathElement: {\n prototype: SVGTextPathElement;\n new(): SVGTextPathElement;\n readonly TEXTPATH_METHODTYPE_ALIGN: number;\n readonly TEXTPATH_METHODTYPE_STRETCH: number;\n readonly TEXTPATH_METHODTYPE_UNKNOWN: number;\n readonly TEXTPATH_SPACINGTYPE_AUTO: number;\n readonly TEXTPATH_SPACINGTYPE_EXACT: number;\n readonly TEXTPATH_SPACINGTYPE_UNKNOWN: number;\n};\n\ninterface SVGTextPositioningElement extends SVGTextContentElement {\n readonly dx: SVGAnimatedLengthList;\n readonly dy: SVGAnimatedLengthList;\n readonly rotate: SVGAnimatedNumberList;\n readonly x: SVGAnimatedLengthList;\n readonly y: SVGAnimatedLengthList;\n addEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTextPositioningElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTextPositioningElement: {\n prototype: SVGTextPositioningElement;\n new(): SVGTextPositioningElement;\n};\n\ninterface SVGTitleElement extends SVGElement {\n addEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGTitleElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGTitleElement: {\n prototype: SVGTitleElement;\n new(): SVGTitleElement;\n};\n\ninterface SVGTransform {\n readonly angle: number;\n readonly matrix: SVGMatrix;\n readonly type: number;\n setMatrix(matrix: SVGMatrix): void;\n setRotate(angle: number, cx: number, cy: number): void;\n setScale(sx: number, sy: number): void;\n setSkewX(angle: number): void;\n setSkewY(angle: number): void;\n setTranslate(tx: number, ty: number): void;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n}\n\ndeclare var SVGTransform: {\n prototype: SVGTransform;\n new(): SVGTransform;\n readonly SVG_TRANSFORM_MATRIX: number;\n readonly SVG_TRANSFORM_ROTATE: number;\n readonly SVG_TRANSFORM_SCALE: number;\n readonly SVG_TRANSFORM_SKEWX: number;\n readonly SVG_TRANSFORM_SKEWY: number;\n readonly SVG_TRANSFORM_TRANSLATE: number;\n readonly SVG_TRANSFORM_UNKNOWN: number;\n};\n\ninterface SVGTransformList {\n readonly numberOfItems: number;\n appendItem(newItem: SVGTransform): SVGTransform;\n clear(): void;\n consolidate(): SVGTransform;\n createSVGTransformFromMatrix(matrix: SVGMatrix): SVGTransform;\n getItem(index: number): SVGTransform;\n initialize(newItem: SVGTransform): SVGTransform;\n insertItemBefore(newItem: SVGTransform, index: number): SVGTransform;\n removeItem(index: number): SVGTransform;\n replaceItem(newItem: SVGTransform, index: number): SVGTransform;\n}\n\ndeclare var SVGTransformList: {\n prototype: SVGTransformList;\n new(): SVGTransformList;\n};\n\ninterface SVGURIReference {\n readonly href: SVGAnimatedString;\n}\n\ninterface SVGUnitTypes {\n readonly SVG_UNIT_TYPE_OBJECTBOUNDINGBOX: number;\n readonly SVG_UNIT_TYPE_UNKNOWN: number;\n readonly SVG_UNIT_TYPE_USERSPACEONUSE: number;\n}\ndeclare var SVGUnitTypes: SVGUnitTypes;\n\ninterface SVGUseElement extends SVGGraphicsElement, SVGURIReference {\n readonly animatedInstanceRoot: SVGElementInstance | null;\n readonly height: SVGAnimatedLength;\n readonly instanceRoot: SVGElementInstance | null;\n readonly width: SVGAnimatedLength;\n readonly x: SVGAnimatedLength;\n readonly y: SVGAnimatedLength;\n addEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGUseElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGUseElement: {\n prototype: SVGUseElement;\n new(): SVGUseElement;\n};\n\ninterface SVGViewElement extends SVGElement, SVGFitToViewBox, SVGZoomAndPan {\n /** @deprecated */\n readonly viewTarget: SVGStringList;\n addEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SVGViewElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SVGViewElement: {\n prototype: SVGViewElement;\n new(): SVGViewElement;\n};\n\ninterface SVGZoomAndPan {\n readonly zoomAndPan: number;\n}\n\ndeclare var SVGZoomAndPan: {\n readonly SVG_ZOOMANDPAN_DISABLE: number;\n readonly SVG_ZOOMANDPAN_MAGNIFY: number;\n readonly SVG_ZOOMANDPAN_UNKNOWN: number;\n};\n\ninterface SVGZoomEvent extends UIEvent {\n readonly newScale: number;\n readonly newTranslate: SVGPoint;\n readonly previousScale: number;\n readonly previousTranslate: SVGPoint;\n readonly zoomRectScreen: SVGRect;\n}\n\ndeclare var SVGZoomEvent: {\n prototype: SVGZoomEvent;\n new(): SVGZoomEvent;\n};\n\ninterface ScopedCredential {\n readonly id: ArrayBuffer;\n readonly type: ScopedCredentialType;\n}\n\ndeclare var ScopedCredential: {\n prototype: ScopedCredential;\n new(): ScopedCredential;\n};\n\ninterface ScopedCredentialInfo {\n readonly credential: ScopedCredential;\n readonly publicKey: CryptoKey;\n}\n\ndeclare var ScopedCredentialInfo: {\n prototype: ScopedCredentialInfo;\n new(): ScopedCredentialInfo;\n};\n\ninterface ScreenEventMap {\n \"MSOrientationChange\": Event;\n}\n\ninterface Screen extends EventTarget {\n readonly availHeight: number;\n readonly availWidth: number;\n /** @deprecated */\n bufferDepth: number;\n readonly colorDepth: number;\n readonly deviceXDPI: number;\n readonly deviceYDPI: number;\n readonly fontSmoothingEnabled: boolean;\n readonly height: number;\n readonly logicalXDPI: number;\n readonly logicalYDPI: number;\n readonly msOrientation: string;\n onmsorientationchange: ((this: Screen, ev: Event) => any) | null;\n readonly pixelDepth: number;\n readonly systemXDPI: number;\n readonly systemYDPI: number;\n readonly width: number;\n lockOrientation(orientations: OrientationLockType | OrientationLockType[]): boolean;\n msLockOrientation(orientations: string | string[]): boolean;\n msUnlockOrientation(): void;\n unlockOrientation(): void;\n addEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Screen, ev: ScreenEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Screen: {\n prototype: Screen;\n new(): Screen;\n};\n\ninterface ScriptProcessorNodeEventMap {\n \"audioprocess\": AudioProcessingEvent;\n}\n\ninterface ScriptProcessorNode extends AudioNode {\n /** @deprecated */\n readonly bufferSize: number;\n /** @deprecated */\n onaudioprocess: ((this: ScriptProcessorNode, ev: AudioProcessingEvent) => any) | null;\n addEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ScriptProcessorNode, ev: ScriptProcessorNodeEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ScriptProcessorNode: {\n prototype: ScriptProcessorNode;\n new(): ScriptProcessorNode;\n};\n\ninterface SecurityPolicyViolationEvent extends Event {\n readonly blockedURI: string;\n readonly columnNumber: number;\n readonly documentURI: string;\n readonly effectiveDirective: string;\n readonly lineNumber: number;\n readonly originalPolicy: string;\n readonly referrer: string;\n readonly sourceFile: string;\n readonly statusCode: number;\n readonly violatedDirective: string;\n}\n\ndeclare var SecurityPolicyViolationEvent: {\n prototype: SecurityPolicyViolationEvent;\n new(type: string, eventInitDict?: SecurityPolicyViolationEventInit): SecurityPolicyViolationEvent;\n};\n\ninterface Selection {\n readonly anchorNode: Node;\n readonly anchorOffset: number;\n readonly baseNode: Node;\n readonly baseOffset: number;\n readonly extentNode: Node;\n readonly extentOffset: number;\n readonly focusNode: Node;\n readonly focusOffset: number;\n readonly isCollapsed: boolean;\n readonly rangeCount: number;\n readonly type: string;\n addRange(range: Range): void;\n collapse(parentNode: Node, offset: number): void;\n collapseToEnd(): void;\n collapseToStart(): void;\n containsNode(node: Node, partlyContained: boolean): boolean;\n deleteFromDocument(): void;\n empty(): void;\n extend(newNode: Node, offset: number): void;\n getRangeAt(index: number): Range;\n removeAllRanges(): void;\n removeRange(range: Range): void;\n selectAllChildren(parentNode: Node): void;\n setBaseAndExtent(baseNode: Node, baseOffset: number, extentNode: Node, extentOffset: number): void;\n setPosition(parentNode: Node, offset: number): void;\n toString(): string;\n}\n\ndeclare var Selection: {\n prototype: Selection;\n new(): Selection;\n};\n\ninterface ServiceUIFrameContext {\n getCachedFrameMessage(key: string): string;\n postFrameMessage(key: string, data: string): void;\n}\ndeclare var ServiceUIFrameContext: ServiceUIFrameContext;\n\ninterface ServiceWorkerEventMap extends AbstractWorkerEventMap {\n \"statechange\": Event;\n}\n\ninterface ServiceWorker extends EventTarget, AbstractWorker {\n onstatechange: ((this: ServiceWorker, ev: Event) => any) | null;\n readonly scriptURL: string;\n readonly state: ServiceWorkerState;\n postMessage(message: any, transfer?: any[]): void;\n addEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorker: {\n prototype: ServiceWorker;\n new(): ServiceWorker;\n};\n\ninterface ServiceWorkerContainerEventMap {\n \"controllerchange\": Event;\n \"message\": MessageEvent;\n \"messageerror\": MessageEvent;\n}\n\ninterface ServiceWorkerContainer extends EventTarget {\n readonly controller: ServiceWorker | null;\n oncontrollerchange: ((this: ServiceWorkerContainer, ev: Event) => any) | null;\n onmessage: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n onmessageerror: ((this: ServiceWorkerContainer, ev: MessageEvent) => any) | null;\n readonly ready: Promise;\n getRegistration(clientURL?: string): Promise;\n getRegistrations(): Promise>;\n register(scriptURL: string, options?: RegistrationOptions): Promise;\n startMessages(): void;\n addEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerContainer, ev: ServiceWorkerContainerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerContainer: {\n prototype: ServiceWorkerContainer;\n new(): ServiceWorkerContainer;\n};\n\ninterface ServiceWorkerMessageEvent extends Event {\n readonly data: any;\n readonly lastEventId: string;\n readonly origin: string;\n readonly ports: ReadonlyArray | null;\n readonly source: ServiceWorker | MessagePort | null;\n}\n\ndeclare var ServiceWorkerMessageEvent: {\n prototype: ServiceWorkerMessageEvent;\n new(type: string, eventInitDict?: ServiceWorkerMessageEventInit): ServiceWorkerMessageEvent;\n};\n\ninterface ServiceWorkerRegistrationEventMap {\n \"updatefound\": Event;\n}\n\ninterface ServiceWorkerRegistration extends EventTarget {\n readonly active: ServiceWorker | null;\n readonly installing: ServiceWorker | null;\n readonly navigationPreload: NavigationPreloadManager;\n onupdatefound: ((this: ServiceWorkerRegistration, ev: Event) => any) | null;\n readonly pushManager: PushManager;\n readonly scope: string;\n readonly sync: SyncManager;\n readonly updateViaCache: ServiceWorkerUpdateViaCache;\n readonly waiting: ServiceWorker | null;\n getNotifications(filter?: GetNotificationOptions): Promise;\n showNotification(title: string, options?: NotificationOptions): Promise;\n unregister(): Promise;\n update(): Promise;\n addEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: ServiceWorkerRegistration, ev: ServiceWorkerRegistrationEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var ServiceWorkerRegistration: {\n prototype: ServiceWorkerRegistration;\n new(): ServiceWorkerRegistration;\n};\n\ninterface ShadowRoot extends DocumentOrShadowRoot, DocumentFragment {\n readonly host: Element;\n innerHTML: string;\n}\n\ninterface ShadowRootInit {\n delegatesFocus?: boolean;\n mode: \"open\" | \"closed\";\n}\n\ninterface SourceBuffer extends EventTarget {\n appendWindowEnd: number;\n appendWindowStart: number;\n readonly audioTracks: AudioTrackList;\n readonly buffered: TimeRanges;\n mode: AppendMode;\n readonly textTracks: TextTrackList;\n timestampOffset: number;\n readonly updating: boolean;\n readonly videoTracks: VideoTrackList;\n abort(): void;\n appendBuffer(data: ArrayBuffer | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n appendStream(stream: MSStream, maxSize?: number): void;\n remove(start: number, end: number): void;\n}\n\ndeclare var SourceBuffer: {\n prototype: SourceBuffer;\n new(): SourceBuffer;\n};\n\ninterface SourceBufferList extends EventTarget {\n readonly length: number;\n item(index: number): SourceBuffer;\n [index: number]: SourceBuffer;\n}\n\ndeclare var SourceBufferList: {\n prototype: SourceBufferList;\n new(): SourceBufferList;\n};\n\ninterface SpeechSynthesisEventMap {\n \"voiceschanged\": Event;\n}\n\ninterface SpeechSynthesis extends EventTarget {\n onvoiceschanged: ((this: SpeechSynthesis, ev: Event) => any) | null;\n readonly paused: boolean;\n readonly pending: boolean;\n readonly speaking: boolean;\n cancel(): void;\n getVoices(): SpeechSynthesisVoice[];\n pause(): void;\n resume(): void;\n speak(utterance: SpeechSynthesisUtterance): void;\n addEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesis, ev: SpeechSynthesisEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesis: {\n prototype: SpeechSynthesis;\n new(): SpeechSynthesis;\n};\n\ninterface SpeechSynthesisEvent extends Event {\n readonly charIndex: number;\n readonly charLength: number;\n readonly elapsedTime: number;\n readonly name: string;\n readonly utterance: SpeechSynthesisUtterance;\n}\n\ndeclare var SpeechSynthesisEvent: {\n prototype: SpeechSynthesisEvent;\n new(type: string, eventInitDict?: SpeechSynthesisEventInit): SpeechSynthesisEvent;\n};\n\ninterface SpeechSynthesisUtteranceEventMap {\n \"boundary\": Event;\n \"end\": Event;\n \"error\": Event;\n \"mark\": Event;\n \"pause\": Event;\n \"resume\": Event;\n \"start\": Event;\n}\n\ninterface SpeechSynthesisUtterance extends EventTarget {\n lang: string;\n onboundary: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onend: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onerror: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onmark: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onpause: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onresume: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n onstart: ((this: SpeechSynthesisUtterance, ev: Event) => any) | null;\n pitch: number;\n rate: number;\n text: string;\n voice: SpeechSynthesisVoice;\n volume: number;\n addEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: SpeechSynthesisUtterance, ev: SpeechSynthesisUtteranceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var SpeechSynthesisUtterance: {\n prototype: SpeechSynthesisUtterance;\n new(): SpeechSynthesisUtterance;\n new(text: string): SpeechSynthesisUtterance;\n};\n\ninterface SpeechSynthesisVoice {\n readonly default: boolean;\n readonly lang: string;\n readonly localService: boolean;\n readonly name: string;\n readonly voiceURI: string;\n}\n\ndeclare var SpeechSynthesisVoice: {\n prototype: SpeechSynthesisVoice;\n new(): SpeechSynthesisVoice;\n};\n\ninterface StereoPannerNode extends AudioNode {\n readonly pan: AudioParam;\n}\n\ndeclare var StereoPannerNode: {\n prototype: StereoPannerNode;\n new(context: BaseAudioContext, options?: StereoPannerOptions): StereoPannerNode;\n};\n\ninterface Storage {\n /**\n * Returns the number of key/value pairs currently present in the list associated with the\n * object.\n */\n readonly length: number;\n /**\n * Empties the list associated with the object of all key/value pairs, if there are any.\n */\n clear(): void;\n /**\n * value = storage[key]\n */\n getItem(key: string): string | null;\n /**\n * Returns the name of the nth key in the list, or null if n is greater\n * than or equal to the number of key/value pairs in the object.\n */\n key(index: number): string | null;\n /**\n * delete storage[key]\n */\n removeItem(key: string): void;\n /**\n * storage[key] = value\n */\n setItem(key: string, value: string): void;\n}\n\ndeclare var Storage: {\n prototype: Storage;\n new(): Storage;\n};\n\ninterface StorageEvent extends Event {\n /**\n * Returns the key of the storage item being changed.\n */\n readonly key: string | null;\n /**\n * Returns the new value of the key of the storage item whose value is being changed.\n */\n readonly newValue: string | null;\n /**\n * Returns the old value of the key of the storage item whose value is being changed.\n */\n readonly oldValue: string | null;\n /**\n * Returns the Storage object that was affected.\n */\n readonly storageArea: Storage | null;\n /**\n * Returns the URL of the document whose storage item changed.\n */\n readonly url: string;\n}\n\ndeclare var StorageEvent: {\n prototype: StorageEvent;\n new(type: string, eventInitDict?: StorageEventInit): StorageEvent;\n};\n\ninterface StorageManager {\n estimate(): Promise;\n persist(): Promise;\n persisted(): Promise;\n}\n\ndeclare var StorageManager: {\n prototype: StorageManager;\n new(): StorageManager;\n};\n\ninterface StyleMedia {\n readonly type: string;\n matchMedium(mediaquery: string): boolean;\n}\n\ndeclare var StyleMedia: {\n prototype: StyleMedia;\n new(): StyleMedia;\n};\n\ninterface StyleSheet {\n disabled: boolean;\n readonly href: string | null;\n readonly media: MediaList;\n readonly ownerNode: Node;\n readonly parentStyleSheet: StyleSheet | null;\n readonly title: string | null;\n readonly type: string;\n}\n\ndeclare var StyleSheet: {\n prototype: StyleSheet;\n new(): StyleSheet;\n};\n\ninterface StyleSheetList {\n readonly length: number;\n item(index: number): StyleSheet | null;\n [index: number]: StyleSheet;\n}\n\ndeclare var StyleSheetList: {\n prototype: StyleSheetList;\n new(): StyleSheetList;\n};\n\ninterface SubtleCrypto {\n decrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n deriveBits(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, length: number): PromiseLike;\n deriveKey(algorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n digest(algorithm: string | Algorithm, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n encrypt(algorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n exportKey(format: \"jwk\", key: CryptoKey): PromiseLike;\n exportKey(format: \"raw\" | \"pkcs8\" | \"spki\", key: CryptoKey): PromiseLike;\n exportKey(format: string, key: CryptoKey): PromiseLike;\n generateKey(algorithm: string, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams | DhKeyGenParams, extractable: boolean, keyUsages: string[]): PromiseLike;\n generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"jwk\", keyData: JsonWebKey, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: \"raw\" | \"pkcs8\" | \"spki\", keyData: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n importKey(format: string, keyData: JsonWebKey | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, algorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n sign(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n unwrapKey(format: string, wrappedKey: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, unwrappingKey: CryptoKey, unwrapAlgorithm: string | Algorithm, unwrappedKeyAlgorithm: string | Algorithm, extractable: boolean, keyUsages: string[]): PromiseLike;\n verify(algorithm: string | RsaPssParams | EcdsaParams | AesCmacParams, key: CryptoKey, signature: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer): PromiseLike;\n wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | Algorithm): PromiseLike;\n}\n\ndeclare var SubtleCrypto: {\n prototype: SubtleCrypto;\n new(): SubtleCrypto;\n};\n\ninterface SyncManager {\n getTags(): Promise;\n register(tag: string): Promise;\n}\n\ndeclare var SyncManager: {\n prototype: SyncManager;\n new(): SyncManager;\n};\n\ninterface Text extends CharacterData {\n readonly assignedSlot: HTMLSlotElement | null;\n readonly wholeText: string;\n splitText(offset: number): Text;\n}\n\ndeclare var Text: {\n prototype: Text;\n new(data?: string): Text;\n};\n\ninterface TextDecoder {\n /**\n * Returns encoding's name, lowercased.\n */\n readonly encoding: string;\n /**\n * Returns true if error mode is \"fatal\", and false\n * otherwise.\n */\n readonly fatal: boolean;\n /**\n * Returns true if ignore BOM flag is set, and false otherwise.\n */\n readonly ignoreBOM: boolean;\n /**\n * Returns the result of running encoding's decoder. The\n * method can be invoked zero or more times with options's stream set to\n * true, and then once without options's stream (or set to false), to process\n * a fragmented stream. If the invocation without options's stream (or set to\n * false) has no input, it's clearest to omit both arguments.\n * var string = \"\", decoder = new TextDecoder(encoding), buffer;\n * while(buffer = next_chunk()) {\n * string += decoder.decode(buffer, {stream:true});\n * }\n * string += decoder.decode(); // end-of-stream\n * If the error mode is \"fatal\" and encoding's decoder returns error, throws a TypeError.\n */\n decode(input?: BufferSource, options?: TextDecodeOptions): string;\n}\n\ndeclare var TextDecoder: {\n prototype: TextDecoder;\n new(label?: string, options?: TextDecoderOptions): TextDecoder;\n};\n\ninterface TextEncoder {\n /**\n * Returns \"utf-8\".\n */\n readonly encoding: string;\n /**\n * Returns the result of running UTF-8's encoder.\n */\n encode(input?: string): Uint8Array;\n}\n\ndeclare var TextEncoder: {\n prototype: TextEncoder;\n new(): TextEncoder;\n};\n\ninterface TextEvent extends UIEvent {\n readonly data: string;\n initTextEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, dataArg: string, inputMethod: number, locale: string): void;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n}\n\ndeclare var TextEvent: {\n prototype: TextEvent;\n new(): TextEvent;\n readonly DOM_INPUT_METHOD_DROP: number;\n readonly DOM_INPUT_METHOD_HANDWRITING: number;\n readonly DOM_INPUT_METHOD_IME: number;\n readonly DOM_INPUT_METHOD_KEYBOARD: number;\n readonly DOM_INPUT_METHOD_MULTIMODAL: number;\n readonly DOM_INPUT_METHOD_OPTION: number;\n readonly DOM_INPUT_METHOD_PASTE: number;\n readonly DOM_INPUT_METHOD_SCRIPT: number;\n readonly DOM_INPUT_METHOD_UNKNOWN: number;\n readonly DOM_INPUT_METHOD_VOICE: number;\n};\n\ninterface TextMetrics {\n readonly width: number;\n}\n\ndeclare var TextMetrics: {\n prototype: TextMetrics;\n new(): TextMetrics;\n};\n\ninterface TextTrackEventMap {\n \"cuechange\": Event;\n \"error\": Event;\n \"load\": Event;\n}\n\ninterface TextTrack extends EventTarget {\n readonly activeCues: TextTrackCueList;\n readonly cues: TextTrackCueList;\n readonly inBandMetadataTrackDispatchType: string;\n readonly kind: string;\n readonly label: string;\n readonly language: string;\n mode: TextTrackMode | number;\n oncuechange: ((this: TextTrack, ev: Event) => any) | null;\n onerror: ((this: TextTrack, ev: Event) => any) | null;\n onload: ((this: TextTrack, ev: Event) => any) | null;\n readonly readyState: number;\n addCue(cue: TextTrackCue): void;\n removeCue(cue: TextTrackCue): void;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n addEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrack, ev: TextTrackEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrack: {\n prototype: TextTrack;\n new(): TextTrack;\n readonly DISABLED: number;\n readonly ERROR: number;\n readonly HIDDEN: number;\n readonly LOADED: number;\n readonly LOADING: number;\n readonly NONE: number;\n readonly SHOWING: number;\n};\n\ninterface TextTrackCueEventMap {\n \"enter\": Event;\n \"exit\": Event;\n}\n\ninterface TextTrackCue extends EventTarget {\n endTime: number;\n id: string;\n onenter: ((this: TextTrackCue, ev: Event) => any) | null;\n onexit: ((this: TextTrackCue, ev: Event) => any) | null;\n pauseOnExit: boolean;\n startTime: number;\n text: string;\n readonly track: TextTrack;\n getCueAsHTML(): DocumentFragment;\n addEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackCue, ev: TextTrackCueEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var TextTrackCue: {\n prototype: TextTrackCue;\n new(startTime: number, endTime: number, text: string): TextTrackCue;\n};\n\ninterface TextTrackCueList {\n readonly length: number;\n getCueById(id: string): TextTrackCue;\n item(index: number): TextTrackCue;\n [index: number]: TextTrackCue;\n}\n\ndeclare var TextTrackCueList: {\n prototype: TextTrackCueList;\n new(): TextTrackCueList;\n};\n\ninterface TextTrackListEventMap {\n \"addtrack\": TrackEvent;\n}\n\ninterface TextTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null;\n item(index: number): TextTrack;\n addEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: TextTrackList, ev: TextTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: TextTrack;\n}\n\ndeclare var TextTrackList: {\n prototype: TextTrackList;\n new(): TextTrackList;\n};\n\ninterface TimeRanges {\n readonly length: number;\n end(index: number): number;\n start(index: number): number;\n}\n\ndeclare var TimeRanges: {\n prototype: TimeRanges;\n new(): TimeRanges;\n};\n\ninterface Touch {\n readonly altitudeAngle: number;\n readonly azimuthAngle: number;\n readonly clientX: number;\n readonly clientY: number;\n readonly force: number;\n readonly identifier: number;\n readonly pageX: number;\n readonly pageY: number;\n readonly radiusX: number;\n readonly radiusY: number;\n readonly rotationAngle: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly target: EventTarget;\n readonly touchType: TouchType;\n}\n\ndeclare var Touch: {\n prototype: Touch;\n new(touchInitDict: TouchInit): Touch;\n};\n\ninterface TouchEvent extends UIEvent {\n readonly altKey: boolean;\n readonly changedTouches: TouchList;\n readonly ctrlKey: boolean;\n readonly metaKey: boolean;\n readonly shiftKey: boolean;\n readonly targetTouches: TouchList;\n readonly touches: TouchList;\n}\n\ndeclare var TouchEvent: {\n prototype: TouchEvent;\n new(type: string, eventInitDict?: TouchEventInit): TouchEvent;\n};\n\ninterface TouchList {\n readonly length: number;\n item(index: number): Touch | null;\n [index: number]: Touch;\n}\n\ndeclare var TouchList: {\n prototype: TouchList;\n new(): TouchList;\n};\n\ninterface TrackEvent extends Event {\n readonly track: VideoTrack | AudioTrack | TextTrack | null;\n}\n\ndeclare var TrackEvent: {\n prototype: TrackEvent;\n new(typeArg: string, eventInitDict?: TrackEventInit): TrackEvent;\n};\n\ninterface TransitionEvent extends Event {\n readonly elapsedTime: number;\n readonly propertyName: string;\n readonly pseudoElement: string;\n}\n\ndeclare var TransitionEvent: {\n prototype: TransitionEvent;\n new(type: string, transitionEventInitDict?: TransitionEventInit): TransitionEvent;\n};\n\ninterface TreeWalker {\n currentNode: Node;\n /** @deprecated */\n readonly expandEntityReferences: boolean;\n readonly filter: NodeFilter | null;\n readonly root: Node;\n readonly whatToShow: number;\n firstChild(): Node | null;\n lastChild(): Node | null;\n nextNode(): Node | null;\n nextSibling(): Node | null;\n parentNode(): Node | null;\n previousNode(): Node | null;\n previousSibling(): Node | null;\n}\n\ndeclare var TreeWalker: {\n prototype: TreeWalker;\n new(): TreeWalker;\n};\n\ninterface UIEvent extends Event {\n readonly detail: number;\n readonly view: Window;\n initUIEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number): void;\n}\n\ndeclare var UIEvent: {\n prototype: UIEvent;\n new(typeArg: string, eventInitDict?: UIEventInit): UIEvent;\n};\n\ninterface URL {\n hash: string;\n host: string;\n hostname: string;\n href: string;\n readonly origin: string;\n password: string;\n pathname: string;\n port: string;\n protocol: string;\n search: string;\n readonly searchParams: URLSearchParams;\n username: string;\n toJSON(): string;\n}\n\ndeclare var URL: {\n prototype: URL;\n new(url: string, base?: string | URL): URL;\n createObjectURL(object: any): string;\n revokeObjectURL(url: string): void;\n};\n\ntype webkitURL = URL;\ndeclare var webkitURL: typeof URL;\n\ninterface URLSearchParams {\n /**\n * Appends a specified key/value pair as a new search parameter.\n */\n append(name: string, value: string): void;\n /**\n * Deletes the given search parameter, and its associated value, from the list of all search parameters.\n */\n delete(name: string): void;\n /**\n * Returns the first value associated to the given search parameter.\n */\n get(name: string): string | null;\n /**\n * Returns all the values association with a given search parameter.\n */\n getAll(name: string): string[];\n /**\n * Returns a Boolean indicating if such a search parameter exists.\n */\n has(name: string): boolean;\n /**\n * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.\n */\n set(name: string, value: string): void;\n sort(): void;\n forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void;\n}\n\ndeclare var URLSearchParams: {\n prototype: URLSearchParams;\n new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams;\n};\n\ninterface VRDisplay extends EventTarget {\n readonly capabilities: VRDisplayCapabilities;\n depthFar: number;\n depthNear: number;\n readonly displayId: number;\n readonly displayName: string;\n readonly isConnected: boolean;\n readonly isPresenting: boolean;\n readonly stageParameters: VRStageParameters | null;\n cancelAnimationFrame(handle: number): void;\n exitPresent(): Promise;\n getEyeParameters(whichEye: string): VREyeParameters;\n getFrameData(frameData: VRFrameData): boolean;\n getLayers(): VRLayer[];\n /** @deprecated */\n getPose(): VRPose;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n requestPresent(layers: VRLayer[]): Promise;\n resetPose(): void;\n submitFrame(pose?: VRPose): void;\n}\n\ndeclare var VRDisplay: {\n prototype: VRDisplay;\n new(): VRDisplay;\n};\n\ninterface VRDisplayCapabilities {\n readonly canPresent: boolean;\n readonly hasExternalDisplay: boolean;\n readonly hasOrientation: boolean;\n readonly hasPosition: boolean;\n readonly maxLayers: number;\n}\n\ndeclare var VRDisplayCapabilities: {\n prototype: VRDisplayCapabilities;\n new(): VRDisplayCapabilities;\n};\n\ninterface VRDisplayEvent extends Event {\n readonly display: VRDisplay;\n readonly reason: VRDisplayEventReason | null;\n}\n\ndeclare var VRDisplayEvent: {\n prototype: VRDisplayEvent;\n new(type: string, eventInitDict: VRDisplayEventInit): VRDisplayEvent;\n};\n\ninterface VREyeParameters {\n /** @deprecated */\n readonly fieldOfView: VRFieldOfView;\n readonly offset: Float32Array;\n readonly renderHeight: number;\n readonly renderWidth: number;\n}\n\ndeclare var VREyeParameters: {\n prototype: VREyeParameters;\n new(): VREyeParameters;\n};\n\ninterface VRFieldOfView {\n readonly downDegrees: number;\n readonly leftDegrees: number;\n readonly rightDegrees: number;\n readonly upDegrees: number;\n}\n\ndeclare var VRFieldOfView: {\n prototype: VRFieldOfView;\n new(): VRFieldOfView;\n};\n\ninterface VRFrameData {\n readonly leftProjectionMatrix: Float32Array;\n readonly leftViewMatrix: Float32Array;\n readonly pose: VRPose;\n readonly rightProjectionMatrix: Float32Array;\n readonly rightViewMatrix: Float32Array;\n readonly timestamp: number;\n}\n\ndeclare var VRFrameData: {\n prototype: VRFrameData;\n new(): VRFrameData;\n};\n\ninterface VRPose {\n readonly angularAcceleration: Float32Array | null;\n readonly angularVelocity: Float32Array | null;\n readonly linearAcceleration: Float32Array | null;\n readonly linearVelocity: Float32Array | null;\n readonly orientation: Float32Array | null;\n readonly position: Float32Array | null;\n readonly timestamp: number;\n}\n\ndeclare var VRPose: {\n prototype: VRPose;\n new(): VRPose;\n};\n\ninterface ValidityState {\n readonly badInput: boolean;\n readonly customError: boolean;\n readonly patternMismatch: boolean;\n readonly rangeOverflow: boolean;\n readonly rangeUnderflow: boolean;\n readonly stepMismatch: boolean;\n readonly tooLong: boolean;\n readonly tooShort: boolean;\n readonly typeMismatch: boolean;\n readonly valid: boolean;\n readonly valueMissing: boolean;\n}\n\ndeclare var ValidityState: {\n prototype: ValidityState;\n new(): ValidityState;\n};\n\ninterface VideoPlaybackQuality {\n readonly corruptedVideoFrames: number;\n readonly creationTime: number;\n readonly droppedVideoFrames: number;\n readonly totalFrameDelay: number;\n readonly totalVideoFrames: number;\n}\n\ndeclare var VideoPlaybackQuality: {\n prototype: VideoPlaybackQuality;\n new(): VideoPlaybackQuality;\n};\n\ninterface VideoTrack {\n readonly id: string;\n kind: string;\n readonly label: string;\n language: string;\n selected: boolean;\n readonly sourceBuffer: SourceBuffer;\n}\n\ndeclare var VideoTrack: {\n prototype: VideoTrack;\n new(): VideoTrack;\n};\n\ninterface VideoTrackListEventMap {\n \"addtrack\": TrackEvent;\n \"change\": Event;\n \"removetrack\": TrackEvent;\n}\n\ninterface VideoTrackList extends EventTarget {\n readonly length: number;\n onaddtrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n onchange: ((this: VideoTrackList, ev: Event) => any) | null;\n onremovetrack: ((this: VideoTrackList, ev: TrackEvent) => any) | null;\n readonly selectedIndex: number;\n getTrackById(id: string): VideoTrack | null;\n item(index: number): VideoTrack;\n addEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: VideoTrackList, ev: VideoTrackListEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n [index: number]: VideoTrack;\n}\n\ndeclare var VideoTrackList: {\n prototype: VideoTrackList;\n new(): VideoTrackList;\n};\n\ninterface WEBGL_color_buffer_float {\n readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;\n readonly RGB32F_EXT: number;\n readonly RGBA32F_EXT: number;\n readonly UNSIGNED_NORMALIZED_EXT: number;\n}\n\ninterface WEBGL_compressed_texture_astc {\n readonly COMPRESSED_RGBA_ASTC_10x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_10x8_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x10_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_12x12_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_4x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x4_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_5x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_6x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x5_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x6_KHR: number;\n readonly COMPRESSED_RGBA_ASTC_8x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: number;\n readonly COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: number;\n getSupportedProfiles(): string[];\n}\n\ninterface WEBGL_compressed_texture_s3tc {\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n}\n\ndeclare var WEBGL_compressed_texture_s3tc: {\n prototype: WEBGL_compressed_texture_s3tc;\n new(): WEBGL_compressed_texture_s3tc;\n readonly COMPRESSED_RGBA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_RGBA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_RGB_S3TC_DXT1_EXT: number;\n};\n\ninterface WEBGL_compressed_texture_s3tc_srgb {\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: number;\n readonly COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: number;\n readonly COMPRESSED_SRGB_S3TC_DXT1_EXT: number;\n}\n\ninterface WEBGL_debug_renderer_info {\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n}\n\ndeclare var WEBGL_debug_renderer_info: {\n prototype: WEBGL_debug_renderer_info;\n new(): WEBGL_debug_renderer_info;\n readonly UNMASKED_RENDERER_WEBGL: number;\n readonly UNMASKED_VENDOR_WEBGL: number;\n};\n\ninterface WEBGL_debug_shaders {\n getTranslatedShaderSource(shader: WebGLShader): string;\n}\n\ninterface WEBGL_depth_texture {\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n}\n\ndeclare var WEBGL_depth_texture: {\n prototype: WEBGL_depth_texture;\n new(): WEBGL_depth_texture;\n readonly UNSIGNED_INT_24_8_WEBGL: number;\n};\n\ninterface WEBGL_draw_buffers {\n readonly COLOR_ATTACHMENT0_WEBGL: number;\n readonly COLOR_ATTACHMENT10_WEBGL: number;\n readonly COLOR_ATTACHMENT11_WEBGL: number;\n readonly COLOR_ATTACHMENT12_WEBGL: number;\n readonly COLOR_ATTACHMENT13_WEBGL: number;\n readonly COLOR_ATTACHMENT14_WEBGL: number;\n readonly COLOR_ATTACHMENT15_WEBGL: number;\n readonly COLOR_ATTACHMENT1_WEBGL: number;\n readonly COLOR_ATTACHMENT2_WEBGL: number;\n readonly COLOR_ATTACHMENT3_WEBGL: number;\n readonly COLOR_ATTACHMENT4_WEBGL: number;\n readonly COLOR_ATTACHMENT5_WEBGL: number;\n readonly COLOR_ATTACHMENT6_WEBGL: number;\n readonly COLOR_ATTACHMENT7_WEBGL: number;\n readonly COLOR_ATTACHMENT8_WEBGL: number;\n readonly COLOR_ATTACHMENT9_WEBGL: number;\n readonly DRAW_BUFFER0_WEBGL: number;\n readonly DRAW_BUFFER10_WEBGL: number;\n readonly DRAW_BUFFER11_WEBGL: number;\n readonly DRAW_BUFFER12_WEBGL: number;\n readonly DRAW_BUFFER13_WEBGL: number;\n readonly DRAW_BUFFER14_WEBGL: number;\n readonly DRAW_BUFFER15_WEBGL: number;\n readonly DRAW_BUFFER1_WEBGL: number;\n readonly DRAW_BUFFER2_WEBGL: number;\n readonly DRAW_BUFFER3_WEBGL: number;\n readonly DRAW_BUFFER4_WEBGL: number;\n readonly DRAW_BUFFER5_WEBGL: number;\n readonly DRAW_BUFFER6_WEBGL: number;\n readonly DRAW_BUFFER7_WEBGL: number;\n readonly DRAW_BUFFER8_WEBGL: number;\n readonly DRAW_BUFFER9_WEBGL: number;\n readonly MAX_COLOR_ATTACHMENTS_WEBGL: number;\n readonly MAX_DRAW_BUFFERS_WEBGL: number;\n drawBuffersWEBGL(buffers: number[]): void;\n}\n\ninterface WEBGL_lose_context {\n loseContext(): void;\n restoreContext(): void;\n}\n\ninterface WaveShaperNode extends AudioNode {\n curve: Float32Array | null;\n oversample: OverSampleType;\n}\n\ndeclare var WaveShaperNode: {\n prototype: WaveShaperNode;\n new(context: BaseAudioContext, options?: WaveShaperOptions): WaveShaperNode;\n};\n\ninterface WebAuthentication {\n getAssertion(assertionChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: AssertionOptions): Promise;\n makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, options?: ScopedCredentialOptions): Promise;\n}\n\ndeclare var WebAuthentication: {\n prototype: WebAuthentication;\n new(): WebAuthentication;\n};\n\ninterface WebAuthnAssertion {\n readonly authenticatorData: ArrayBuffer;\n readonly clientData: ArrayBuffer;\n readonly credential: ScopedCredential;\n readonly signature: ArrayBuffer;\n}\n\ndeclare var WebAuthnAssertion: {\n prototype: WebAuthnAssertion;\n new(): WebAuthnAssertion;\n};\n\ninterface WebGLActiveInfo {\n readonly name: string;\n readonly size: number;\n readonly type: number;\n}\n\ndeclare var WebGLActiveInfo: {\n prototype: WebGLActiveInfo;\n new(): WebGLActiveInfo;\n};\n\ninterface WebGLBuffer extends WebGLObject {\n}\n\ndeclare var WebGLBuffer: {\n prototype: WebGLBuffer;\n new(): WebGLBuffer;\n};\n\ninterface WebGLContextEvent extends Event {\n readonly statusMessage: string;\n}\n\ndeclare var WebGLContextEvent: {\n prototype: WebGLContextEvent;\n new(typeArg: string, eventInitDict?: WebGLContextEventInit): WebGLContextEvent;\n};\n\ninterface WebGLFramebuffer extends WebGLObject {\n}\n\ndeclare var WebGLFramebuffer: {\n prototype: WebGLFramebuffer;\n new(): WebGLFramebuffer;\n};\n\ninterface WebGLObject {\n}\n\ndeclare var WebGLObject: {\n prototype: WebGLObject;\n new(): WebGLObject;\n};\n\ninterface WebGLProgram extends WebGLObject {\n}\n\ndeclare var WebGLProgram: {\n prototype: WebGLProgram;\n new(): WebGLProgram;\n};\n\ninterface WebGLRenderbuffer extends WebGLObject {\n}\n\ndeclare var WebGLRenderbuffer: {\n prototype: WebGLRenderbuffer;\n new(): WebGLRenderbuffer;\n};\n\ninterface WebGLRenderingContext {\n readonly canvas: HTMLCanvasElement;\n readonly drawingBufferHeight: number;\n readonly drawingBufferWidth: number;\n activeTexture(texture: number): void;\n attachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n bindAttribLocation(program: WebGLProgram | null, index: number, name: string): void;\n bindBuffer(target: number, buffer: WebGLBuffer | null): void;\n bindFramebuffer(target: number, framebuffer: WebGLFramebuffer | null): void;\n bindRenderbuffer(target: number, renderbuffer: WebGLRenderbuffer | null): void;\n bindTexture(target: number, texture: WebGLTexture | null): void;\n blendColor(red: number, green: number, blue: number, alpha: number): void;\n blendEquation(mode: number): void;\n blendEquationSeparate(modeRGB: number, modeAlpha: number): void;\n blendFunc(sfactor: number, dfactor: number): void;\n blendFuncSeparate(srcRGB: number, dstRGB: number, srcAlpha: number, dstAlpha: number): void;\n bufferData(target: number, size: number | Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, usage: number): void;\n bufferSubData(target: number, offset: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null): void;\n checkFramebufferStatus(target: number): number;\n clear(mask: number): void;\n clearColor(red: number, green: number, blue: number, alpha: number): void;\n clearDepth(depth: number): void;\n clearStencil(s: number): void;\n colorMask(red: boolean, green: boolean, blue: boolean, alpha: boolean): void;\n compileShader(shader: WebGLShader | null): void;\n compressedTexImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n compressedTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, data: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n copyTexImage2D(target: number, level: number, internalformat: number, x: number, y: number, width: number, height: number, border: number): void;\n copyTexSubImage2D(target: number, level: number, xoffset: number, yoffset: number, x: number, y: number, width: number, height: number): void;\n createBuffer(): WebGLBuffer | null;\n createFramebuffer(): WebGLFramebuffer | null;\n createProgram(): WebGLProgram | null;\n createRenderbuffer(): WebGLRenderbuffer | null;\n createShader(type: number): WebGLShader | null;\n createTexture(): WebGLTexture | null;\n cullFace(mode: number): void;\n deleteBuffer(buffer: WebGLBuffer | null): void;\n deleteFramebuffer(framebuffer: WebGLFramebuffer | null): void;\n deleteProgram(program: WebGLProgram | null): void;\n deleteRenderbuffer(renderbuffer: WebGLRenderbuffer | null): void;\n deleteShader(shader: WebGLShader | null): void;\n deleteTexture(texture: WebGLTexture | null): void;\n depthFunc(func: number): void;\n depthMask(flag: boolean): void;\n depthRange(zNear: number, zFar: number): void;\n detachShader(program: WebGLProgram | null, shader: WebGLShader | null): void;\n disable(cap: number): void;\n disableVertexAttribArray(index: number): void;\n drawArrays(mode: number, first: number, count: number): void;\n drawElements(mode: number, count: number, type: number, offset: number): void;\n enable(cap: number): void;\n enableVertexAttribArray(index: number): void;\n finish(): void;\n flush(): void;\n framebufferRenderbuffer(target: number, attachment: number, renderbuffertarget: number, renderbuffer: WebGLRenderbuffer | null): void;\n framebufferTexture2D(target: number, attachment: number, textarget: number, texture: WebGLTexture | null, level: number): void;\n frontFace(mode: number): void;\n generateMipmap(target: number): void;\n getActiveAttrib(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getActiveUniform(program: WebGLProgram | null, index: number): WebGLActiveInfo | null;\n getAttachedShaders(program: WebGLProgram | null): WebGLShader[] | null;\n getAttribLocation(program: WebGLProgram | null, name: string): number;\n getBufferParameter(target: number, pname: number): any;\n getContextAttributes(): WebGLContextAttributes;\n getError(): number;\n getExtension(extensionName: \"EXT_blend_minmax\"): EXT_blend_minmax | null;\n getExtension(extensionName: \"EXT_texture_filter_anisotropic\"): EXT_texture_filter_anisotropic | null;\n getExtension(extensionName: \"EXT_frag_depth\"): EXT_frag_depth | null;\n getExtension(extensionName: \"EXT_shader_texture_lod\"): EXT_shader_texture_lod | null;\n getExtension(extensionName: \"EXT_sRGB\"): EXT_sRGB | null;\n getExtension(extensionName: \"OES_vertex_array_object\"): OES_vertex_array_object | null;\n getExtension(extensionName: \"WEBGL_color_buffer_float\"): WEBGL_color_buffer_float | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_astc\"): WEBGL_compressed_texture_astc | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc_srgb\"): WEBGL_compressed_texture_s3tc_srgb | null;\n getExtension(extensionName: \"WEBGL_debug_shaders\"): WEBGL_debug_shaders | null;\n getExtension(extensionName: \"WEBGL_draw_buffers\"): WEBGL_draw_buffers | null;\n getExtension(extensionName: \"WEBGL_lose_context\"): WEBGL_lose_context | null;\n getExtension(extensionName: \"WEBGL_depth_texture\"): WEBGL_depth_texture | null;\n getExtension(extensionName: \"WEBGL_debug_renderer_info\"): WEBGL_debug_renderer_info | null;\n getExtension(extensionName: \"WEBGL_compressed_texture_s3tc\"): WEBGL_compressed_texture_s3tc | null;\n getExtension(extensionName: \"OES_texture_half_float_linear\"): OES_texture_half_float_linear | null;\n getExtension(extensionName: \"OES_texture_half_float\"): OES_texture_half_float | null;\n getExtension(extensionName: \"OES_texture_float_linear\"): OES_texture_float_linear | null;\n getExtension(extensionName: \"OES_texture_float\"): OES_texture_float | null;\n getExtension(extensionName: \"OES_standard_derivatives\"): OES_standard_derivatives | null;\n getExtension(extensionName: \"OES_element_index_uint\"): OES_element_index_uint | null;\n getExtension(extensionName: \"ANGLE_instanced_arrays\"): ANGLE_instanced_arrays | null;\n getExtension(extensionName: string): any;\n getFramebufferAttachmentParameter(target: number, attachment: number, pname: number): any;\n getParameter(pname: number): any;\n getProgramInfoLog(program: WebGLProgram | null): string | null;\n getProgramParameter(program: WebGLProgram | null, pname: number): any;\n getRenderbufferParameter(target: number, pname: number): any;\n getShaderInfoLog(shader: WebGLShader | null): string | null;\n getShaderParameter(shader: WebGLShader | null, pname: number): any;\n getShaderPrecisionFormat(shadertype: number, precisiontype: number): WebGLShaderPrecisionFormat | null;\n getShaderSource(shader: WebGLShader | null): string | null;\n getSupportedExtensions(): string[] | null;\n getTexParameter(target: number, pname: number): any;\n getUniform(program: WebGLProgram | null, location: WebGLUniformLocation | null): any;\n getUniformLocation(program: WebGLProgram | null, name: string): WebGLUniformLocation | null;\n getVertexAttrib(index: number, pname: number): any;\n getVertexAttribOffset(index: number, pname: number): number;\n hint(target: number, mode: number): void;\n isBuffer(buffer: WebGLBuffer | null): boolean;\n isContextLost(): boolean;\n isEnabled(cap: number): boolean;\n isFramebuffer(framebuffer: WebGLFramebuffer | null): boolean;\n isProgram(program: WebGLProgram | null): boolean;\n isRenderbuffer(renderbuffer: WebGLRenderbuffer | null): boolean;\n isShader(shader: WebGLShader | null): boolean;\n isTexture(texture: WebGLTexture | null): boolean;\n lineWidth(width: number): void;\n linkProgram(program: WebGLProgram | null): void;\n pixelStorei(pname: number, param: number | boolean): void;\n polygonOffset(factor: number, units: number): void;\n readPixels(x: number, y: number, width: number, height: number, format: number, type: number, pixels: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null): void;\n renderbufferStorage(target: number, internalformat: number, width: number, height: number): void;\n sampleCoverage(value: number, invert: boolean): void;\n scissor(x: number, y: number, width: number, height: number): void;\n shaderSource(shader: WebGLShader | null, source: string): void;\n stencilFunc(func: number, ref: number, mask: number): void;\n stencilFuncSeparate(face: number, func: number, ref: number, mask: number): void;\n stencilMask(mask: number): void;\n stencilMaskSeparate(face: number, mask: number): void;\n stencilOp(fail: number, zfail: number, zpass: number): void;\n stencilOpSeparate(face: number, fail: number, zfail: number, zpass: number): void;\n texImage2D(target: number, level: number, internalformat: number, width: number, height: number, border: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texImage2D(target: number, level: number, internalformat: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n texParameterf(target: number, pname: number, param: number): void;\n texParameteri(target: number, pname: number, param: number): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, width: number, height: number, format: number, type: number, pixels: ArrayBufferView | null): void;\n texSubImage2D(target: number, level: number, xoffset: number, yoffset: number, format: number, type: number, pixels: ImageBitmap | ImageData | HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): void;\n uniform1f(location: WebGLUniformLocation | null, x: number): void;\n uniform1fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform1i(location: WebGLUniformLocation | null, x: number): void;\n uniform1iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform2f(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform2i(location: WebGLUniformLocation | null, x: number, y: number): void;\n uniform2iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform3f(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform3i(location: WebGLUniformLocation | null, x: number, y: number, z: number): void;\n uniform3iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniform4f(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4fv(location: WebGLUniformLocation | null, v: Float32Array | ArrayLike): void;\n uniform4i(location: WebGLUniformLocation | null, x: number, y: number, z: number, w: number): void;\n uniform4iv(location: WebGLUniformLocation | null, v: Int32Array | ArrayLike): void;\n uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: boolean, value: Float32Array | ArrayLike): void;\n useProgram(program: WebGLProgram | null): void;\n validateProgram(program: WebGLProgram | null): void;\n vertexAttrib1f(indx: number, x: number): void;\n vertexAttrib1fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib2f(indx: number, x: number, y: number): void;\n vertexAttrib2fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib3f(indx: number, x: number, y: number, z: number): void;\n vertexAttrib3fv(indx: number, values: Float32Array | number[]): void;\n vertexAttrib4f(indx: number, x: number, y: number, z: number, w: number): void;\n vertexAttrib4fv(indx: number, values: Float32Array | number[]): void;\n vertexAttribPointer(indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void;\n viewport(x: number, y: number, width: number, height: number): void;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n}\n\ndeclare var WebGLRenderingContext: {\n prototype: WebGLRenderingContext;\n new(): WebGLRenderingContext;\n readonly ACTIVE_ATTRIBUTES: number;\n readonly ACTIVE_TEXTURE: number;\n readonly ACTIVE_UNIFORMS: number;\n readonly ALIASED_LINE_WIDTH_RANGE: number;\n readonly ALIASED_POINT_SIZE_RANGE: number;\n readonly ALPHA: number;\n readonly ALPHA_BITS: number;\n readonly ALWAYS: number;\n readonly ARRAY_BUFFER: number;\n readonly ARRAY_BUFFER_BINDING: number;\n readonly ATTACHED_SHADERS: number;\n readonly BACK: number;\n readonly BLEND: number;\n readonly BLEND_COLOR: number;\n readonly BLEND_DST_ALPHA: number;\n readonly BLEND_DST_RGB: number;\n readonly BLEND_EQUATION: number;\n readonly BLEND_EQUATION_ALPHA: number;\n readonly BLEND_EQUATION_RGB: number;\n readonly BLEND_SRC_ALPHA: number;\n readonly BLEND_SRC_RGB: number;\n readonly BLUE_BITS: number;\n readonly BOOL: number;\n readonly BOOL_VEC2: number;\n readonly BOOL_VEC3: number;\n readonly BOOL_VEC4: number;\n readonly BROWSER_DEFAULT_WEBGL: number;\n readonly BUFFER_SIZE: number;\n readonly BUFFER_USAGE: number;\n readonly BYTE: number;\n readonly CCW: number;\n readonly CLAMP_TO_EDGE: number;\n readonly COLOR_ATTACHMENT0: number;\n readonly COLOR_BUFFER_BIT: number;\n readonly COLOR_CLEAR_VALUE: number;\n readonly COLOR_WRITEMASK: number;\n readonly COMPILE_STATUS: number;\n readonly COMPRESSED_TEXTURE_FORMATS: number;\n readonly CONSTANT_ALPHA: number;\n readonly CONSTANT_COLOR: number;\n readonly CONTEXT_LOST_WEBGL: number;\n readonly CULL_FACE: number;\n readonly CULL_FACE_MODE: number;\n readonly CURRENT_PROGRAM: number;\n readonly CURRENT_VERTEX_ATTRIB: number;\n readonly CW: number;\n readonly DECR: number;\n readonly DECR_WRAP: number;\n readonly DELETE_STATUS: number;\n readonly DEPTH_ATTACHMENT: number;\n readonly DEPTH_BITS: number;\n readonly DEPTH_BUFFER_BIT: number;\n readonly DEPTH_CLEAR_VALUE: number;\n readonly DEPTH_COMPONENT: number;\n readonly DEPTH_COMPONENT16: number;\n readonly DEPTH_FUNC: number;\n readonly DEPTH_RANGE: number;\n readonly DEPTH_STENCIL: number;\n readonly DEPTH_STENCIL_ATTACHMENT: number;\n readonly DEPTH_TEST: number;\n readonly DEPTH_WRITEMASK: number;\n readonly DITHER: number;\n readonly DONT_CARE: number;\n readonly DST_ALPHA: number;\n readonly DST_COLOR: number;\n readonly DYNAMIC_DRAW: number;\n readonly ELEMENT_ARRAY_BUFFER: number;\n readonly ELEMENT_ARRAY_BUFFER_BINDING: number;\n readonly EQUAL: number;\n readonly FASTEST: number;\n readonly FLOAT: number;\n readonly FLOAT_MAT2: number;\n readonly FLOAT_MAT3: number;\n readonly FLOAT_MAT4: number;\n readonly FLOAT_VEC2: number;\n readonly FLOAT_VEC3: number;\n readonly FLOAT_VEC4: number;\n readonly FRAGMENT_SHADER: number;\n readonly FRAMEBUFFER: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number;\n readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number;\n readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number;\n readonly FRAMEBUFFER_BINDING: number;\n readonly FRAMEBUFFER_COMPLETE: number;\n readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number;\n readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number;\n readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number;\n readonly FRAMEBUFFER_UNSUPPORTED: number;\n readonly FRONT: number;\n readonly FRONT_AND_BACK: number;\n readonly FRONT_FACE: number;\n readonly FUNC_ADD: number;\n readonly FUNC_REVERSE_SUBTRACT: number;\n readonly FUNC_SUBTRACT: number;\n readonly GENERATE_MIPMAP_HINT: number;\n readonly GEQUAL: number;\n readonly GREATER: number;\n readonly GREEN_BITS: number;\n readonly HIGH_FLOAT: number;\n readonly HIGH_INT: number;\n readonly IMPLEMENTATION_COLOR_READ_FORMAT: number;\n readonly IMPLEMENTATION_COLOR_READ_TYPE: number;\n readonly INCR: number;\n readonly INCR_WRAP: number;\n readonly INT: number;\n readonly INT_VEC2: number;\n readonly INT_VEC3: number;\n readonly INT_VEC4: number;\n readonly INVALID_ENUM: number;\n readonly INVALID_FRAMEBUFFER_OPERATION: number;\n readonly INVALID_OPERATION: number;\n readonly INVALID_VALUE: number;\n readonly INVERT: number;\n readonly KEEP: number;\n readonly LEQUAL: number;\n readonly LESS: number;\n readonly LINEAR: number;\n readonly LINEAR_MIPMAP_LINEAR: number;\n readonly LINEAR_MIPMAP_NEAREST: number;\n readonly LINES: number;\n readonly LINE_LOOP: number;\n readonly LINE_STRIP: number;\n readonly LINE_WIDTH: number;\n readonly LINK_STATUS: number;\n readonly LOW_FLOAT: number;\n readonly LOW_INT: number;\n readonly LUMINANCE: number;\n readonly LUMINANCE_ALPHA: number;\n readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_CUBE_MAP_TEXTURE_SIZE: number;\n readonly MAX_FRAGMENT_UNIFORM_VECTORS: number;\n readonly MAX_RENDERBUFFER_SIZE: number;\n readonly MAX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_TEXTURE_SIZE: number;\n readonly MAX_VARYING_VECTORS: number;\n readonly MAX_VERTEX_ATTRIBS: number;\n readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number;\n readonly MAX_VERTEX_UNIFORM_VECTORS: number;\n readonly MAX_VIEWPORT_DIMS: number;\n readonly MEDIUM_FLOAT: number;\n readonly MEDIUM_INT: number;\n readonly MIRRORED_REPEAT: number;\n readonly NEAREST: number;\n readonly NEAREST_MIPMAP_LINEAR: number;\n readonly NEAREST_MIPMAP_NEAREST: number;\n readonly NEVER: number;\n readonly NICEST: number;\n readonly NONE: number;\n readonly NOTEQUAL: number;\n readonly NO_ERROR: number;\n readonly ONE: number;\n readonly ONE_MINUS_CONSTANT_ALPHA: number;\n readonly ONE_MINUS_CONSTANT_COLOR: number;\n readonly ONE_MINUS_DST_ALPHA: number;\n readonly ONE_MINUS_DST_COLOR: number;\n readonly ONE_MINUS_SRC_ALPHA: number;\n readonly ONE_MINUS_SRC_COLOR: number;\n readonly OUT_OF_MEMORY: number;\n readonly PACK_ALIGNMENT: number;\n readonly POINTS: number;\n readonly POLYGON_OFFSET_FACTOR: number;\n readonly POLYGON_OFFSET_FILL: number;\n readonly POLYGON_OFFSET_UNITS: number;\n readonly RED_BITS: number;\n readonly RENDERBUFFER: number;\n readonly RENDERBUFFER_ALPHA_SIZE: number;\n readonly RENDERBUFFER_BINDING: number;\n readonly RENDERBUFFER_BLUE_SIZE: number;\n readonly RENDERBUFFER_DEPTH_SIZE: number;\n readonly RENDERBUFFER_GREEN_SIZE: number;\n readonly RENDERBUFFER_HEIGHT: number;\n readonly RENDERBUFFER_INTERNAL_FORMAT: number;\n readonly RENDERBUFFER_RED_SIZE: number;\n readonly RENDERBUFFER_STENCIL_SIZE: number;\n readonly RENDERBUFFER_WIDTH: number;\n readonly RENDERER: number;\n readonly REPEAT: number;\n readonly REPLACE: number;\n readonly RGB: number;\n readonly RGB565: number;\n readonly RGB5_A1: number;\n readonly RGBA: number;\n readonly RGBA4: number;\n readonly SAMPLER_2D: number;\n readonly SAMPLER_CUBE: number;\n readonly SAMPLES: number;\n readonly SAMPLE_ALPHA_TO_COVERAGE: number;\n readonly SAMPLE_BUFFERS: number;\n readonly SAMPLE_COVERAGE: number;\n readonly SAMPLE_COVERAGE_INVERT: number;\n readonly SAMPLE_COVERAGE_VALUE: number;\n readonly SCISSOR_BOX: number;\n readonly SCISSOR_TEST: number;\n readonly SHADER_TYPE: number;\n readonly SHADING_LANGUAGE_VERSION: number;\n readonly SHORT: number;\n readonly SRC_ALPHA: number;\n readonly SRC_ALPHA_SATURATE: number;\n readonly SRC_COLOR: number;\n readonly STATIC_DRAW: number;\n readonly STENCIL_ATTACHMENT: number;\n readonly STENCIL_BACK_FAIL: number;\n readonly STENCIL_BACK_FUNC: number;\n readonly STENCIL_BACK_PASS_DEPTH_FAIL: number;\n readonly STENCIL_BACK_PASS_DEPTH_PASS: number;\n readonly STENCIL_BACK_REF: number;\n readonly STENCIL_BACK_VALUE_MASK: number;\n readonly STENCIL_BACK_WRITEMASK: number;\n readonly STENCIL_BITS: number;\n readonly STENCIL_BUFFER_BIT: number;\n readonly STENCIL_CLEAR_VALUE: number;\n readonly STENCIL_FAIL: number;\n readonly STENCIL_FUNC: number;\n readonly STENCIL_INDEX: number;\n readonly STENCIL_INDEX8: number;\n readonly STENCIL_PASS_DEPTH_FAIL: number;\n readonly STENCIL_PASS_DEPTH_PASS: number;\n readonly STENCIL_REF: number;\n readonly STENCIL_TEST: number;\n readonly STENCIL_VALUE_MASK: number;\n readonly STENCIL_WRITEMASK: number;\n readonly STREAM_DRAW: number;\n readonly SUBPIXEL_BITS: number;\n readonly TEXTURE: number;\n readonly TEXTURE0: number;\n readonly TEXTURE1: number;\n readonly TEXTURE10: number;\n readonly TEXTURE11: number;\n readonly TEXTURE12: number;\n readonly TEXTURE13: number;\n readonly TEXTURE14: number;\n readonly TEXTURE15: number;\n readonly TEXTURE16: number;\n readonly TEXTURE17: number;\n readonly TEXTURE18: number;\n readonly TEXTURE19: number;\n readonly TEXTURE2: number;\n readonly TEXTURE20: number;\n readonly TEXTURE21: number;\n readonly TEXTURE22: number;\n readonly TEXTURE23: number;\n readonly TEXTURE24: number;\n readonly TEXTURE25: number;\n readonly TEXTURE26: number;\n readonly TEXTURE27: number;\n readonly TEXTURE28: number;\n readonly TEXTURE29: number;\n readonly TEXTURE3: number;\n readonly TEXTURE30: number;\n readonly TEXTURE31: number;\n readonly TEXTURE4: number;\n readonly TEXTURE5: number;\n readonly TEXTURE6: number;\n readonly TEXTURE7: number;\n readonly TEXTURE8: number;\n readonly TEXTURE9: number;\n readonly TEXTURE_2D: number;\n readonly TEXTURE_BINDING_2D: number;\n readonly TEXTURE_BINDING_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_X: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number;\n readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number;\n readonly TEXTURE_MAG_FILTER: number;\n readonly TEXTURE_MIN_FILTER: number;\n readonly TEXTURE_WRAP_S: number;\n readonly TEXTURE_WRAP_T: number;\n readonly TRIANGLES: number;\n readonly TRIANGLE_FAN: number;\n readonly TRIANGLE_STRIP: number;\n readonly UNPACK_ALIGNMENT: number;\n readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number;\n readonly UNPACK_FLIP_Y_WEBGL: number;\n readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number;\n readonly UNSIGNED_BYTE: number;\n readonly UNSIGNED_INT: number;\n readonly UNSIGNED_SHORT: number;\n readonly UNSIGNED_SHORT_4_4_4_4: number;\n readonly UNSIGNED_SHORT_5_5_5_1: number;\n readonly UNSIGNED_SHORT_5_6_5: number;\n readonly VALIDATE_STATUS: number;\n readonly VENDOR: number;\n readonly VERSION: number;\n readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number;\n readonly VERTEX_ATTRIB_ARRAY_ENABLED: number;\n readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number;\n readonly VERTEX_ATTRIB_ARRAY_POINTER: number;\n readonly VERTEX_ATTRIB_ARRAY_SIZE: number;\n readonly VERTEX_ATTRIB_ARRAY_STRIDE: number;\n readonly VERTEX_ATTRIB_ARRAY_TYPE: number;\n readonly VERTEX_SHADER: number;\n readonly VIEWPORT: number;\n readonly ZERO: number;\n};\n\ninterface WebGLShader extends WebGLObject {\n}\n\ndeclare var WebGLShader: {\n prototype: WebGLShader;\n new(): WebGLShader;\n};\n\ninterface WebGLShaderPrecisionFormat {\n readonly precision: number;\n readonly rangeMax: number;\n readonly rangeMin: number;\n}\n\ndeclare var WebGLShaderPrecisionFormat: {\n prototype: WebGLShaderPrecisionFormat;\n new(): WebGLShaderPrecisionFormat;\n};\n\ninterface WebGLTexture extends WebGLObject {\n}\n\ndeclare var WebGLTexture: {\n prototype: WebGLTexture;\n new(): WebGLTexture;\n};\n\ninterface WebGLUniformLocation {\n}\n\ndeclare var WebGLUniformLocation: {\n prototype: WebGLUniformLocation;\n new(): WebGLUniformLocation;\n};\n\ninterface WebGLVertexArrayObjectOES {\n}\n\ninterface WebKitPoint {\n x: number;\n y: number;\n}\n\ndeclare var WebKitPoint: {\n prototype: WebKitPoint;\n new(x?: number, y?: number): WebKitPoint;\n};\n\ninterface WebSocketEventMap {\n \"close\": CloseEvent;\n \"error\": Event;\n \"message\": MessageEvent;\n \"open\": Event;\n}\n\ninterface WebSocket extends EventTarget {\n binaryType: BinaryType;\n readonly bufferedAmount: number;\n readonly extensions: string;\n onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;\n onerror: ((this: WebSocket, ev: Event) => any) | null;\n onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;\n onopen: ((this: WebSocket, ev: Event) => any) | null;\n readonly protocol: string;\n readonly readyState: number;\n readonly url: string;\n close(code?: number, reason?: string): void;\n send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n addEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var WebSocket: {\n prototype: WebSocket;\n new(url: string, protocols?: string | string[]): WebSocket;\n readonly CLOSED: number;\n readonly CLOSING: number;\n readonly CONNECTING: number;\n readonly OPEN: number;\n};\n\ninterface WheelEvent extends MouseEvent {\n readonly deltaMode: number;\n readonly deltaX: number;\n readonly deltaY: number;\n readonly deltaZ: number;\n readonly wheelDelta: number;\n readonly wheelDeltaX: number;\n readonly wheelDeltaY: number;\n getCurrentPoint(element: Element): void;\n initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n}\n\ndeclare var WheelEvent: {\n prototype: WheelEvent;\n new(typeArg: string, eventInitDict?: WheelEventInit): WheelEvent;\n readonly DOM_DELTA_LINE: number;\n readonly DOM_DELTA_PAGE: number;\n readonly DOM_DELTA_PIXEL: number;\n};\n\ninterface WindowEventMap extends GlobalEventHandlersEventMap {\n \"abort\": UIEvent;\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"blur\": FocusEvent;\n \"canplay\": Event;\n \"canplaythrough\": Event;\n \"change\": Event;\n \"click\": MouseEvent;\n \"compassneedscalibration\": Event;\n \"contextmenu\": PointerEvent;\n \"dblclick\": MouseEvent;\n \"devicelight\": DeviceLightEvent;\n \"devicemotion\": DeviceMotionEvent;\n \"deviceorientation\": DeviceOrientationEvent;\n \"drag\": DragEvent;\n \"dragend\": DragEvent;\n \"dragenter\": DragEvent;\n \"dragleave\": DragEvent;\n \"dragover\": DragEvent;\n \"dragstart\": DragEvent;\n \"drop\": DragEvent;\n \"durationchange\": Event;\n \"emptied\": Event;\n \"ended\": Event;\n \"error\": ErrorEvent;\n \"focus\": FocusEvent;\n \"hashchange\": HashChangeEvent;\n \"input\": Event;\n \"invalid\": Event;\n \"keydown\": KeyboardEvent;\n \"keypress\": KeyboardEvent;\n \"keyup\": KeyboardEvent;\n \"load\": Event;\n \"loadeddata\": Event;\n \"loadedmetadata\": Event;\n \"loadstart\": Event;\n \"message\": MessageEvent;\n \"mousedown\": MouseEvent;\n \"mouseenter\": MouseEvent;\n \"mouseleave\": MouseEvent;\n \"mousemove\": MouseEvent;\n \"mouseout\": MouseEvent;\n \"mouseover\": MouseEvent;\n \"mouseup\": MouseEvent;\n \"mousewheel\": WheelEvent;\n \"MSGestureChange\": Event;\n \"MSGestureDoubleTap\": Event;\n \"MSGestureEnd\": Event;\n \"MSGestureHold\": Event;\n \"MSGestureStart\": Event;\n \"MSGestureTap\": Event;\n \"MSInertiaStart\": Event;\n \"MSPointerCancel\": Event;\n \"MSPointerDown\": Event;\n \"MSPointerEnter\": Event;\n \"MSPointerLeave\": Event;\n \"MSPointerMove\": Event;\n \"MSPointerOut\": Event;\n \"MSPointerOver\": Event;\n \"MSPointerUp\": Event;\n \"offline\": Event;\n \"online\": Event;\n \"orientationchange\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"pause\": Event;\n \"play\": Event;\n \"playing\": Event;\n \"popstate\": PopStateEvent;\n \"progress\": ProgressEvent;\n \"ratechange\": Event;\n \"readystatechange\": ProgressEvent;\n \"reset\": Event;\n \"resize\": UIEvent;\n \"scroll\": UIEvent;\n \"seeked\": Event;\n \"seeking\": Event;\n \"select\": UIEvent;\n \"stalled\": Event;\n \"storage\": StorageEvent;\n \"submit\": Event;\n \"suspend\": Event;\n \"timeupdate\": Event;\n \"unload\": Event;\n \"volumechange\": Event;\n \"vrdisplayactivate\": Event;\n \"vrdisplayblur\": Event;\n \"vrdisplayconnect\": Event;\n \"vrdisplaydeactivate\": Event;\n \"vrdisplaydisconnect\": Event;\n \"vrdisplayfocus\": Event;\n \"vrdisplaypointerrestricted\": Event;\n \"vrdisplaypointerunrestricted\": Event;\n \"vrdisplaypresentchange\": Event;\n \"waiting\": Event;\n}\n\ninterface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {\n Blob: typeof Blob;\n URL: typeof URL;\n URLSearchParams: typeof URLSearchParams;\n readonly applicationCache: ApplicationCache;\n readonly caches: CacheStorage;\n readonly clientInformation: Navigator;\n readonly closed: boolean;\n readonly crypto: Crypto;\n customElements: CustomElementRegistry;\n defaultStatus: string;\n readonly devicePixelRatio: number;\n readonly doNotTrack: string;\n readonly document: Document;\n event: Event | undefined;\n /** @deprecated */\n readonly external: External;\n readonly frameElement: Element;\n readonly frames: Window;\n readonly history: History;\n readonly innerHeight: number;\n readonly innerWidth: number;\n readonly isSecureContext: boolean;\n readonly length: number;\n location: Location;\n readonly locationbar: BarProp;\n readonly menubar: BarProp;\n readonly msContentScript: ExtensionScriptApis;\n readonly msCredentials: MSCredentials;\n name: string;\n readonly navigator: Navigator;\n offscreenBuffering: string | boolean;\n onabort: ((this: Window, ev: UIEvent) => any) | null;\n onafterprint: ((this: Window, ev: Event) => any) | null;\n onbeforeprint: ((this: Window, ev: Event) => any) | null;\n onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\n onblur: ((this: Window, ev: FocusEvent) => any) | null;\n oncanplay: ((this: Window, ev: Event) => any) | null;\n oncanplaythrough: ((this: Window, ev: Event) => any) | null;\n onchange: ((this: Window, ev: Event) => any) | null;\n onclick: ((this: Window, ev: MouseEvent) => any) | null;\n oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\n oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\n ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\n ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\n ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\n ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\n ondrag: ((this: Window, ev: DragEvent) => any) | null;\n ondragend: ((this: Window, ev: DragEvent) => any) | null;\n ondragenter: ((this: Window, ev: DragEvent) => any) | null;\n ondragleave: ((this: Window, ev: DragEvent) => any) | null;\n ondragover: ((this: Window, ev: DragEvent) => any) | null;\n ondragstart: ((this: Window, ev: DragEvent) => any) | null;\n ondrop: ((this: Window, ev: DragEvent) => any) | null;\n ondurationchange: ((this: Window, ev: Event) => any) | null;\n onemptied: ((this: Window, ev: Event) => any) | null;\n onended: ((this: Window, ev: Event) => any) | null;\n onerror: ErrorEventHandler;\n onfocus: ((this: Window, ev: FocusEvent) => any) | null;\n onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\n oninput: ((this: Window, ev: Event) => any) | null;\n oninvalid: ((this: Window, ev: Event) => any) | null;\n onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\n onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\n onload: ((this: Window, ev: Event) => any) | null;\n onloadeddata: ((this: Window, ev: Event) => any) | null;\n onloadedmetadata: ((this: Window, ev: Event) => any) | null;\n onloadstart: ((this: Window, ev: Event) => any) | null;\n onmessage: ((this: Window, ev: MessageEvent) => any) | null;\n onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\n onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\n onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\n onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\n onmsgesturechange: ((this: Window, ev: Event) => any) | null;\n onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\n onmsgestureend: ((this: Window, ev: Event) => any) | null;\n onmsgesturehold: ((this: Window, ev: Event) => any) | null;\n onmsgesturestart: ((this: Window, ev: Event) => any) | null;\n onmsgesturetap: ((this: Window, ev: Event) => any) | null;\n onmsinertiastart: ((this: Window, ev: Event) => any) | null;\n onmspointercancel: ((this: Window, ev: Event) => any) | null;\n onmspointerdown: ((this: Window, ev: Event) => any) | null;\n onmspointerenter: ((this: Window, ev: Event) => any) | null;\n onmspointerleave: ((this: Window, ev: Event) => any) | null;\n onmspointermove: ((this: Window, ev: Event) => any) | null;\n onmspointerout: ((this: Window, ev: Event) => any) | null;\n onmspointerover: ((this: Window, ev: Event) => any) | null;\n onmspointerup: ((this: Window, ev: Event) => any) | null;\n onoffline: ((this: Window, ev: Event) => any) | null;\n ononline: ((this: Window, ev: Event) => any) | null;\n onorientationchange: ((this: Window, ev: Event) => any) | null;\n onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\n onpause: ((this: Window, ev: Event) => any) | null;\n onplay: ((this: Window, ev: Event) => any) | null;\n onplaying: ((this: Window, ev: Event) => any) | null;\n onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\n onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\n onratechange: ((this: Window, ev: Event) => any) | null;\n onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\n onreset: ((this: Window, ev: Event) => any) | null;\n onresize: ((this: Window, ev: UIEvent) => any) | null;\n onscroll: ((this: Window, ev: UIEvent) => any) | null;\n onseeked: ((this: Window, ev: Event) => any) | null;\n onseeking: ((this: Window, ev: Event) => any) | null;\n onselect: ((this: Window, ev: UIEvent) => any) | null;\n onstalled: ((this: Window, ev: Event) => any) | null;\n onstorage: ((this: Window, ev: StorageEvent) => any) | null;\n onsubmit: ((this: Window, ev: Event) => any) | null;\n onsuspend: ((this: Window, ev: Event) => any) | null;\n ontimeupdate: ((this: Window, ev: Event) => any) | null;\n onunload: ((this: Window, ev: Event) => any) | null;\n onvolumechange: ((this: Window, ev: Event) => any) | null;\n onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\n onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\n onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\n onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\n onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\n onwaiting: ((this: Window, ev: Event) => any) | null;\n opener: any;\n readonly orientation: string | number;\n readonly outerHeight: number;\n readonly outerWidth: number;\n readonly pageXOffset: number;\n readonly pageYOffset: number;\n readonly parent: Window;\n readonly performance: Performance;\n readonly personalbar: BarProp;\n readonly screen: Screen;\n readonly screenLeft: number;\n readonly screenTop: number;\n readonly screenX: number;\n readonly screenY: number;\n readonly scrollX: number;\n readonly scrollY: number;\n readonly scrollbars: BarProp;\n readonly self: Window;\n readonly speechSynthesis: SpeechSynthesis;\n status: string;\n readonly statusbar: BarProp;\n readonly styleMedia: StyleMedia;\n readonly toolbar: BarProp;\n readonly top: Window;\n readonly window: Window;\n alert(message?: any): void;\n blur(): void;\n cancelAnimationFrame(handle: number): void;\n /** @deprecated */\n captureEvents(): void;\n close(): void;\n confirm(message?: string): boolean;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\n createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\n departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\n focus(): void;\n getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\n getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\n getSelection(): Selection;\n matchMedia(mediaQuery: string): MediaQueryList;\n moveBy(x?: number, y?: number): void;\n moveTo(x?: number, y?: number): void;\n msWriteProfilerMark(profilerMarkName: string): void;\n open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\n postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\n print(): void;\n prompt(message?: string, _default?: string): string | null;\n /** @deprecated */\n releaseEvents(): void;\n requestAnimationFrame(callback: FrameRequestCallback): number;\n resizeBy(x?: number, y?: number): void;\n resizeTo(x?: number, y?: number): void;\n scroll(options?: ScrollToOptions): void;\n scroll(x?: number, y?: number): void;\n scrollBy(options?: ScrollToOptions): void;\n scrollBy(x?: number, y?: number): void;\n scrollTo(options?: ScrollToOptions): void;\n scrollTo(x?: number, y?: number): void;\n stop(): void;\n webkitCancelAnimationFrame(handle: number): void;\n webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\n webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\n addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Window: {\n prototype: Window;\n new(): Window;\n};\n\ninterface WindowBase64 {\n atob(encodedString: string): string;\n btoa(rawString: string): string;\n}\n\ninterface WindowConsole {\n readonly console: Console;\n}\n\ninterface WindowEventHandlersEventMap {\n \"afterprint\": Event;\n \"beforeprint\": Event;\n \"beforeunload\": BeforeUnloadEvent;\n \"hashchange\": HashChangeEvent;\n \"message\": MessageEvent;\n \"offline\": Event;\n \"online\": Event;\n \"pagehide\": PageTransitionEvent;\n \"pageshow\": PageTransitionEvent;\n \"popstate\": PopStateEvent;\n \"storage\": StorageEvent;\n \"unload\": Event;\n}\n\ninterface WindowEventHandlers {\n onafterprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeprint: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onbeforeunload: ((this: WindowEventHandlers, ev: BeforeUnloadEvent) => any) | null;\n onhashchange: ((this: WindowEventHandlers, ev: HashChangeEvent) => any) | null;\n onmessage: ((this: WindowEventHandlers, ev: MessageEvent) => any) | null;\n onoffline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n ononline: ((this: WindowEventHandlers, ev: Event) => any) | null;\n onpagehide: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpageshow: ((this: WindowEventHandlers, ev: PageTransitionEvent) => any) | null;\n onpopstate: ((this: WindowEventHandlers, ev: PopStateEvent) => any) | null;\n onstorage: ((this: WindowEventHandlers, ev: StorageEvent) => any) | null;\n onunload: ((this: WindowEventHandlers, ev: Event) => any) | null;\n addEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: WindowEventHandlers, ev: WindowEventHandlersEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ninterface WindowLocalStorage {\n readonly localStorage: Storage;\n}\n\ninterface WindowOrWorkerGlobalScope {\n readonly caches: CacheStorage;\n readonly indexedDB: IDBFactory;\n readonly performance: Performance;\n fetch(input: RequestInfo, init?: RequestInit): Promise;\n}\n\ninterface WindowSessionStorage {\n readonly sessionStorage: Storage;\n}\n\ninterface WindowTimers extends WindowTimersExtension {\n clearInterval(handle?: number): void;\n clearTimeout(handle?: number): void;\n setInterval(handler: (...args: any[]) => void, timeout: number): number;\n setInterval(handler: any, timeout?: any, ...args: any[]): number;\n setTimeout(handler: (...args: any[]) => void, timeout: number): number;\n setTimeout(handler: any, timeout?: any, ...args: any[]): number;\n}\n\ninterface WindowTimersExtension {\n clearImmediate(handle: number): void;\n setImmediate(handler: (...args: any[]) => void): number;\n setImmediate(handler: any, ...args: any[]): number;\n}\n\ninterface WorkerEventMap extends AbstractWorkerEventMap {\n \"message\": MessageEvent;\n}\n\ninterface Worker extends EventTarget, AbstractWorker {\n onmessage: ((this: Worker, ev: MessageEvent) => any) | null;\n postMessage(message: any, transfer?: any[]): void;\n terminate(): void;\n addEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var Worker: {\n prototype: Worker;\n new(stringUrl: string): Worker;\n};\n\ninterface Worklet {\n addModule(moduleURL: string, options?: WorkletOptions): Promise;\n}\n\ndeclare var Worklet: {\n prototype: Worklet;\n new(): Worklet;\n};\n\ninterface WritableStream {\n readonly locked: boolean;\n abort(reason?: any): Promise;\n getWriter(): WritableStreamDefaultWriter;\n}\n\ndeclare var WritableStream: {\n prototype: WritableStream;\n new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream;\n};\n\ninterface WritableStreamDefaultController {\n error(error?: any): void;\n}\n\ndeclare var WritableStreamDefaultController: {\n prototype: WritableStreamDefaultController;\n new(): WritableStreamDefaultController;\n};\n\ninterface WritableStreamDefaultWriter {\n readonly closed: Promise;\n readonly desiredSize: number;\n readonly ready: Promise;\n abort(reason?: any): Promise;\n close(): Promise;\n releaseLock(): void;\n write(chunk?: any): Promise;\n}\n\ndeclare var WritableStreamDefaultWriter: {\n prototype: WritableStreamDefaultWriter;\n new(): WritableStreamDefaultWriter;\n};\n\ninterface XMLDocument extends Document {\n addEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLDocument, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLDocument: {\n prototype: XMLDocument;\n new(): XMLDocument;\n};\n\ninterface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap {\n \"readystatechange\": Event;\n}\n\ninterface XMLHttpRequest extends XMLHttpRequestEventTarget {\n onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null;\n /**\n * Returns client's state.\n */\n readonly readyState: number;\n /**\n * Returns the response's body.\n */\n readonly response: any;\n /**\n * Returns the text response.\n * Throws an \"InvalidStateError\" DOMException if responseType is not the empty string or \"text\".\n */\n readonly responseText: string;\n /**\n * Returns the response type.\n * Can be set to change the response type. Values are:\n * the empty string (default),\n * \"arraybuffer\",\n * \"blob\",\n * \"document\",\n * \"json\", and\n * \"text\".\n * When set: setting to \"document\" is ignored if current global object is not a Window object.\n * When set: throws an \"InvalidStateError\" DOMException if state is loading or done.\n * When set: throws an \"InvalidAccessError\" DOMException if the synchronous flag is set and current global object is a Window object.\n */\n responseType: XMLHttpRequestResponseType;\n readonly responseURL: string;\n /**\n * Returns the document response.\n * Throws an \"InvalidStateError\" DOMException if responseType is not the empty string or \"document\".\n */\n readonly responseXML: Document | null;\n readonly status: number;\n readonly statusText: string;\n /**\n * Can be set to a time in milliseconds. When set to a non-zero value will cause fetching to terminate after the given time has passed. When the time has passed, the\n * request has not yet completed, and the synchronous flag is unset, a timeout event will then be dispatched, or a\n * \"TimeoutError\" DOMException will be thrown otherwise (for the send() method).\n * When set: throws an \"InvalidAccessError\" DOMException if the synchronous flag is set and current global object is a Window object.\n */\n timeout: number;\n /**\n * Returns the associated XMLHttpRequestUpload object. It can be used to gather transmission information when data is\n * transferred to a server.\n */\n readonly upload: XMLHttpRequestUpload;\n /**\n * True when credentials are to be included in a cross-origin request. False when they are\n * to be excluded in a cross-origin request and when cookies are to be ignored in its response.\n * Initially false.\n * When set: throws an \"InvalidStateError\" DOMException if state is not unsent or opened, or if the send() flag is set.\n */\n withCredentials: boolean;\n /**\n * Cancels any network activity.\n */\n abort(): void;\n getAllResponseHeaders(): string;\n getResponseHeader(name: string): string | null;\n /**\n * Sets the request method, request URL, and synchronous flag.\n * Throws a \"SyntaxError\" DOMException if either method is not a\n * valid HTTP method or url cannot be parsed.\n * Throws a \"SecurityError\" DOMException if method is a\n * case-insensitive match for `CONNECT`, `TRACE`, or `TRACK`.\n * Throws an \"InvalidAccessError\" DOMException if async is false, current global object is a Window object, and the timeout attribute is not zero or the responseType attribute is not the empty string.\n */\n open(method: string, url: string): void;\n open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void;\n /**\n * Acts as if the `Content-Type` header value for response is mime.\n * (It does not actually change the header though.)\n * Throws an \"InvalidStateError\" DOMException if state is loading or done.\n */\n overrideMimeType(mime: string): void;\n /**\n * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.\n * Throws an \"InvalidStateError\" DOMException if either state is not opened or the send() flag is set.\n */\n send(body?: Document | BodyInit): void;\n /**\n * Combines a header in author request headers.\n * Throws an \"InvalidStateError\" DOMException if either state is not opened or the send() flag is set.\n * Throws a \"SyntaxError\" DOMException if name is not a header name\n * or if value is not a header value.\n */\n setRequestHeader(name: string, value: string): void;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequest: {\n prototype: XMLHttpRequest;\n new(): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\n\ninterface XMLHttpRequestEventTargetEventMap {\n \"abort\": ProgressEvent;\n \"error\": ProgressEvent;\n \"load\": ProgressEvent;\n \"loadend\": ProgressEvent;\n \"loadstart\": ProgressEvent;\n \"progress\": ProgressEvent;\n \"timeout\": ProgressEvent;\n}\n\ninterface XMLHttpRequestEventTarget extends EventTarget {\n onabort: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onerror: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onload: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadend: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onloadstart: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n onprogress: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n ontimeout: ((this: XMLHttpRequest, ev: ProgressEvent) => any) | null;\n addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestEventTarget: {\n prototype: XMLHttpRequestEventTarget;\n new(): XMLHttpRequestEventTarget;\n};\n\ninterface XMLHttpRequestUpload extends XMLHttpRequestEventTarget {\n addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var XMLHttpRequestUpload: {\n prototype: XMLHttpRequestUpload;\n new(): XMLHttpRequestUpload;\n};\n\ninterface XMLSerializer {\n serializeToString(target: Node): string;\n}\n\ndeclare var XMLSerializer: {\n prototype: XMLSerializer;\n new(): XMLSerializer;\n};\n\ninterface XPathEvaluator {\n createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;\n createNSResolver(nodeResolver?: Node): XPathNSResolver;\n evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathEvaluator: {\n prototype: XPathEvaluator;\n new(): XPathEvaluator;\n};\n\ninterface XPathExpression {\n evaluate(contextNode: Node, type: number, result: XPathResult | null): XPathResult;\n}\n\ndeclare var XPathExpression: {\n prototype: XPathExpression;\n new(): XPathExpression;\n};\n\ninterface XPathNSResolver {\n lookupNamespaceURI(prefix: string): string;\n}\n\ndeclare var XPathNSResolver: {\n prototype: XPathNSResolver;\n new(): XPathNSResolver;\n};\n\ninterface XPathResult {\n readonly booleanValue: boolean;\n readonly invalidIteratorState: boolean;\n readonly numberValue: number;\n readonly resultType: number;\n readonly singleNodeValue: Node;\n readonly snapshotLength: number;\n readonly stringValue: string;\n iterateNext(): Node;\n snapshotItem(index: number): Node;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n}\n\ndeclare var XPathResult: {\n prototype: XPathResult;\n new(): XPathResult;\n readonly ANY_TYPE: number;\n readonly ANY_UNORDERED_NODE_TYPE: number;\n readonly BOOLEAN_TYPE: number;\n readonly FIRST_ORDERED_NODE_TYPE: number;\n readonly NUMBER_TYPE: number;\n readonly ORDERED_NODE_ITERATOR_TYPE: number;\n readonly ORDERED_NODE_SNAPSHOT_TYPE: number;\n readonly STRING_TYPE: number;\n readonly UNORDERED_NODE_ITERATOR_TYPE: number;\n readonly UNORDERED_NODE_SNAPSHOT_TYPE: number;\n};\n\ninterface XSLTProcessor {\n clearParameters(): void;\n getParameter(namespaceURI: string, localName: string): any;\n importStylesheet(style: Node): void;\n removeParameter(namespaceURI: string, localName: string): void;\n reset(): void;\n setParameter(namespaceURI: string, localName: string, value: any): void;\n transformToDocument(source: Node): Document;\n transformToFragment(source: Node, document: Document): DocumentFragment;\n}\n\ndeclare var XSLTProcessor: {\n prototype: XSLTProcessor;\n new(): XSLTProcessor;\n};\n\ninterface webkitRTCPeerConnection extends RTCPeerConnection {\n addEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n removeEventListener(type: K, listener: (this: webkitRTCPeerConnection, ev: RTCPeerConnectionEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\n removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare var webkitRTCPeerConnection: {\n prototype: webkitRTCPeerConnection;\n new(configuration: RTCConfiguration): webkitRTCPeerConnection;\n};\n\ndeclare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;\n\ninterface DecodeErrorCallback {\n (error: DOMException): void;\n}\n\ninterface DecodeSuccessCallback {\n (decodedData: AudioBuffer): void;\n}\n\ninterface ErrorEventHandler {\n (event: Event | string, source?: string, fileno?: number, columnNumber?: number, error?: Error): void;\n}\n\ninterface EventHandlerNonNull {\n (event: Event): any;\n}\n\ninterface ForEachCallback {\n (keyId: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer | null, status: MediaKeyStatus): void;\n}\n\ninterface FrameRequestCallback {\n (time: number): void;\n}\n\ninterface FunctionStringCallback {\n (data: string): void;\n}\n\ninterface GenerateAssertionCallback {\n (contents: string, origin: string, options: RTCIdentityProviderOptions): Promise;\n}\n\ninterface IntersectionObserverCallback {\n (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;\n}\n\ninterface MSLaunchUriCallback {\n (): void;\n}\n\ninterface MediaQueryListListener {\n (mql: MediaQueryList): void;\n}\n\ninterface MutationCallback {\n (mutations: MutationRecord[], observer: MutationObserver): void;\n}\n\ninterface NavigatorUserMediaErrorCallback {\n (error: MediaStreamError): void;\n}\n\ninterface NavigatorUserMediaSuccessCallback {\n (stream: MediaStream): void;\n}\n\ninterface NotificationPermissionCallback {\n (permission: NotificationPermission): void;\n}\n\ninterface PerformanceObserverCallback {\n (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void;\n}\n\ninterface PositionCallback {\n (position: Position): void;\n}\n\ninterface PositionErrorCallback {\n (positionError: PositionError): void;\n}\n\ninterface RTCPeerConnectionErrorCallback {\n (error: DOMException): void;\n}\n\ninterface RTCSessionDescriptionCallback {\n (description: RTCSessionDescriptionInit): void;\n}\n\ninterface RTCStatsCallback {\n (report: RTCStatsReport): void;\n}\n\ninterface ValidateAssertionCallback {\n (assertion: string, origin: string): Promise;\n}\n\ninterface VoidFunction {\n (): void;\n}\n\ninterface WritableStreamChunkCallback {\n (chunk: any, controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamDefaultControllerCallback {\n (controller: WritableStreamDefaultController): void;\n}\n\ninterface WritableStreamErrorCallback {\n (reason: string): void;\n}\n\ninterface HTMLElementTagNameMap {\n \"a\": HTMLAnchorElement;\n \"abbr\": HTMLElement;\n \"acronym\": HTMLElement;\n \"address\": HTMLElement;\n \"applet\": HTMLAppletElement;\n \"area\": HTMLAreaElement;\n \"article\": HTMLElement;\n \"aside\": HTMLElement;\n \"audio\": HTMLAudioElement;\n \"b\": HTMLElement;\n \"base\": HTMLBaseElement;\n \"basefont\": HTMLBaseFontElement;\n \"bdo\": HTMLElement;\n \"big\": HTMLElement;\n \"blockquote\": HTMLQuoteElement;\n \"body\": HTMLBodyElement;\n \"br\": HTMLBRElement;\n \"button\": HTMLButtonElement;\n \"canvas\": HTMLCanvasElement;\n \"caption\": HTMLTableCaptionElement;\n \"center\": HTMLElement;\n \"cite\": HTMLElement;\n \"code\": HTMLElement;\n \"col\": HTMLTableColElement;\n \"colgroup\": HTMLTableColElement;\n \"data\": HTMLDataElement;\n \"datalist\": HTMLDataListElement;\n \"dd\": HTMLElement;\n \"del\": HTMLModElement;\n \"dfn\": HTMLElement;\n \"dir\": HTMLDirectoryElement;\n \"div\": HTMLDivElement;\n \"dl\": HTMLDListElement;\n \"dt\": HTMLElement;\n \"em\": HTMLElement;\n \"embed\": HTMLEmbedElement;\n \"fieldset\": HTMLFieldSetElement;\n \"figcaption\": HTMLElement;\n \"figure\": HTMLElement;\n \"font\": HTMLFontElement;\n \"footer\": HTMLElement;\n \"form\": HTMLFormElement;\n \"frame\": HTMLFrameElement;\n \"frameset\": HTMLFrameSetElement;\n \"h1\": HTMLHeadingElement;\n \"h2\": HTMLHeadingElement;\n \"h3\": HTMLHeadingElement;\n \"h4\": HTMLHeadingElement;\n \"h5\": HTMLHeadingElement;\n \"h6\": HTMLHeadingElement;\n \"head\": HTMLHeadElement;\n \"header\": HTMLElement;\n \"hgroup\": HTMLElement;\n \"hr\": HTMLHRElement;\n \"html\": HTMLHtmlElement;\n \"i\": HTMLElement;\n \"iframe\": HTMLIFrameElement;\n \"img\": HTMLImageElement;\n \"input\": HTMLInputElement;\n \"ins\": HTMLModElement;\n \"isindex\": HTMLUnknownElement;\n \"kbd\": HTMLElement;\n \"keygen\": HTMLElement;\n \"label\": HTMLLabelElement;\n \"legend\": HTMLLegendElement;\n \"li\": HTMLLIElement;\n \"link\": HTMLLinkElement;\n \"listing\": HTMLPreElement;\n \"map\": HTMLMapElement;\n \"mark\": HTMLElement;\n \"marquee\": HTMLMarqueeElement;\n \"menu\": HTMLMenuElement;\n \"meta\": HTMLMetaElement;\n \"meter\": HTMLMeterElement;\n \"nav\": HTMLElement;\n \"nextid\": HTMLUnknownElement;\n \"nobr\": HTMLElement;\n \"noframes\": HTMLElement;\n \"noscript\": HTMLElement;\n \"object\": HTMLObjectElement;\n \"ol\": HTMLOListElement;\n \"optgroup\": HTMLOptGroupElement;\n \"option\": HTMLOptionElement;\n \"output\": HTMLOutputElement;\n \"p\": HTMLParagraphElement;\n \"param\": HTMLParamElement;\n \"picture\": HTMLPictureElement;\n \"plaintext\": HTMLElement;\n \"pre\": HTMLPreElement;\n \"progress\": HTMLProgressElement;\n \"q\": HTMLQuoteElement;\n \"rt\": HTMLElement;\n \"ruby\": HTMLElement;\n \"s\": HTMLElement;\n \"samp\": HTMLElement;\n \"script\": HTMLScriptElement;\n \"section\": HTMLElement;\n \"select\": HTMLSelectElement;\n \"slot\": HTMLSlotElement;\n \"small\": HTMLElement;\n \"source\": HTMLSourceElement;\n \"span\": HTMLSpanElement;\n \"strike\": HTMLElement;\n \"strong\": HTMLElement;\n \"style\": HTMLStyleElement;\n \"sub\": HTMLElement;\n \"sup\": HTMLElement;\n \"table\": HTMLTableElement;\n \"tbody\": HTMLTableSectionElement;\n \"td\": HTMLTableDataCellElement;\n \"template\": HTMLTemplateElement;\n \"textarea\": HTMLTextAreaElement;\n \"tfoot\": HTMLTableSectionElement;\n \"th\": HTMLTableHeaderCellElement;\n \"thead\": HTMLTableSectionElement;\n \"time\": HTMLTimeElement;\n \"title\": HTMLTitleElement;\n \"tr\": HTMLTableRowElement;\n \"track\": HTMLTrackElement;\n \"tt\": HTMLElement;\n \"u\": HTMLElement;\n \"ul\": HTMLUListElement;\n \"var\": HTMLElement;\n \"video\": HTMLVideoElement;\n \"wbr\": HTMLElement;\n \"xmp\": HTMLPreElement;\n}\n\ninterface SVGElementTagNameMap {\n \"circle\": SVGCircleElement;\n \"clipPath\": SVGClipPathElement;\n \"defs\": SVGDefsElement;\n \"desc\": SVGDescElement;\n \"ellipse\": SVGEllipseElement;\n \"feBlend\": SVGFEBlendElement;\n \"feColorMatrix\": SVGFEColorMatrixElement;\n \"feComponentTransfer\": SVGFEComponentTransferElement;\n \"feComposite\": SVGFECompositeElement;\n \"feConvolveMatrix\": SVGFEConvolveMatrixElement;\n \"feDiffuseLighting\": SVGFEDiffuseLightingElement;\n \"feDisplacementMap\": SVGFEDisplacementMapElement;\n \"feDistantLight\": SVGFEDistantLightElement;\n \"feFlood\": SVGFEFloodElement;\n \"feFuncA\": SVGFEFuncAElement;\n \"feFuncB\": SVGFEFuncBElement;\n \"feFuncG\": SVGFEFuncGElement;\n \"feFuncR\": SVGFEFuncRElement;\n \"feGaussianBlur\": SVGFEGaussianBlurElement;\n \"feImage\": SVGFEImageElement;\n \"feMerge\": SVGFEMergeElement;\n \"feMergeNode\": SVGFEMergeNodeElement;\n \"feMorphology\": SVGFEMorphologyElement;\n \"feOffset\": SVGFEOffsetElement;\n \"fePointLight\": SVGFEPointLightElement;\n \"feSpecularLighting\": SVGFESpecularLightingElement;\n \"feSpotLight\": SVGFESpotLightElement;\n \"feTile\": SVGFETileElement;\n \"feTurbulence\": SVGFETurbulenceElement;\n \"filter\": SVGFilterElement;\n \"foreignObject\": SVGForeignObjectElement;\n \"g\": SVGGElement;\n \"image\": SVGImageElement;\n \"line\": SVGLineElement;\n \"linearGradient\": SVGLinearGradientElement;\n \"marker\": SVGMarkerElement;\n \"mask\": SVGMaskElement;\n \"metadata\": SVGMetadataElement;\n \"path\": SVGPathElement;\n \"pattern\": SVGPatternElement;\n \"polygon\": SVGPolygonElement;\n \"polyline\": SVGPolylineElement;\n \"radialGradient\": SVGRadialGradientElement;\n \"rect\": SVGRectElement;\n \"stop\": SVGStopElement;\n \"svg\": SVGSVGElement;\n \"switch\": SVGSwitchElement;\n \"symbol\": SVGSymbolElement;\n \"text\": SVGTextElement;\n \"textPath\": SVGTextPathElement;\n \"tspan\": SVGTSpanElement;\n \"use\": SVGUseElement;\n \"view\": SVGViewElement;\n}\n\n/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */\ninterface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { }\n\ndeclare var Audio: {\n new(src?: string): HTMLAudioElement;\n};\ndeclare var Image: {\n new(width?: number, height?: number): HTMLImageElement;\n};\ndeclare var Option: {\n new(text?: string, value?: string, defaultSelected?: boolean, selected?: boolean): HTMLOptionElement;\n};\ndeclare var Blob: typeof Blob;\ndeclare var URL: typeof URL;\ndeclare var URLSearchParams: typeof URLSearchParams;\ndeclare var applicationCache: ApplicationCache;\ndeclare var caches: CacheStorage;\ndeclare var clientInformation: Navigator;\ndeclare var closed: boolean;\ndeclare var crypto: Crypto;\ndeclare var customElements: CustomElementRegistry;\ndeclare var defaultStatus: string;\ndeclare var devicePixelRatio: number;\ndeclare var doNotTrack: string;\ndeclare var document: Document;\ndeclare var event: Event | undefined;\n/** @deprecated */\ndeclare var external: External;\ndeclare var frameElement: Element;\ndeclare var frames: Window;\ndeclare var history: History;\ndeclare var innerHeight: number;\ndeclare var innerWidth: number;\ndeclare var isSecureContext: boolean;\ndeclare var length: number;\ndeclare var location: Location;\ndeclare var locationbar: BarProp;\ndeclare var menubar: BarProp;\ndeclare var msContentScript: ExtensionScriptApis;\ndeclare var msCredentials: MSCredentials;\ndeclare const name: never;\ndeclare var navigator: Navigator;\ndeclare var offscreenBuffering: string | boolean;\ndeclare var onabort: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onafterprint: ((this: Window, ev: Event) => any) | null;\ndeclare var onbeforeprint: ((this: Window, ev: Event) => any) | null;\ndeclare var onbeforeunload: ((this: Window, ev: BeforeUnloadEvent) => any) | null;\ndeclare var onblur: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var oncanplay: ((this: Window, ev: Event) => any) | null;\ndeclare var oncanplaythrough: ((this: Window, ev: Event) => any) | null;\ndeclare var onchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var oncompassneedscalibration: ((this: Window, ev: Event) => any) | null;\ndeclare var oncontextmenu: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ondblclick: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var ondevicelight: ((this: Window, ev: DeviceLightEvent) => any) | null;\ndeclare var ondevicemotion: ((this: Window, ev: DeviceMotionEvent) => any) | null;\ndeclare var ondeviceorientation: ((this: Window, ev: DeviceOrientationEvent) => any) | null;\ndeclare var ondrag: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragend: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragenter: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragleave: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragover: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondragstart: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondrop: ((this: Window, ev: DragEvent) => any) | null;\ndeclare var ondurationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onemptied: ((this: Window, ev: Event) => any) | null;\ndeclare var onended: ((this: Window, ev: Event) => any) | null;\ndeclare var onerror: ErrorEventHandler;\ndeclare var onfocus: ((this: Window, ev: FocusEvent) => any) | null;\ndeclare var onhashchange: ((this: Window, ev: HashChangeEvent) => any) | null;\ndeclare var oninput: ((this: Window, ev: Event) => any) | null;\ndeclare var oninvalid: ((this: Window, ev: Event) => any) | null;\ndeclare var onkeydown: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeypress: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onkeyup: ((this: Window, ev: KeyboardEvent) => any) | null;\ndeclare var onload: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadeddata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadedmetadata: ((this: Window, ev: Event) => any) | null;\ndeclare var onloadstart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;\ndeclare var onmousedown: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseenter: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseleave: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousemove: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseout: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseover: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmouseup: ((this: Window, ev: MouseEvent) => any) | null;\ndeclare var onmousewheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var onmsgesturechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturedoubletap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgestureend: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturehold: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturestart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsgesturetap: ((this: Window, ev: Event) => any) | null;\ndeclare var onmsinertiastart: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointercancel: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerdown: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerenter: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerleave: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointermove: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerout: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerover: ((this: Window, ev: Event) => any) | null;\ndeclare var onmspointerup: ((this: Window, ev: Event) => any) | null;\ndeclare var onoffline: ((this: Window, ev: Event) => any) | null;\ndeclare var ononline: ((this: Window, ev: Event) => any) | null;\ndeclare var onorientationchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onpagehide: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpageshow: ((this: Window, ev: PageTransitionEvent) => any) | null;\ndeclare var onpause: ((this: Window, ev: Event) => any) | null;\ndeclare var onplay: ((this: Window, ev: Event) => any) | null;\ndeclare var onplaying: ((this: Window, ev: Event) => any) | null;\ndeclare var onpopstate: ((this: Window, ev: PopStateEvent) => any) | null;\ndeclare var onprogress: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onratechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onreadystatechange: ((this: Window, ev: ProgressEvent) => any) | null;\ndeclare var onreset: ((this: Window, ev: Event) => any) | null;\ndeclare var onresize: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onscroll: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onseeked: ((this: Window, ev: Event) => any) | null;\ndeclare var onseeking: ((this: Window, ev: Event) => any) | null;\ndeclare var onselect: ((this: Window, ev: UIEvent) => any) | null;\ndeclare var onstalled: ((this: Window, ev: Event) => any) | null;\ndeclare var onstorage: ((this: Window, ev: StorageEvent) => any) | null;\ndeclare var onsubmit: ((this: Window, ev: Event) => any) | null;\ndeclare var onsuspend: ((this: Window, ev: Event) => any) | null;\ndeclare var ontimeupdate: ((this: Window, ev: Event) => any) | null;\ndeclare var onunload: ((this: Window, ev: Event) => any) | null;\ndeclare var onvolumechange: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayblur: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydeactivate: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaydisconnect: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplayfocus: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypointerunrestricted: ((this: Window, ev: Event) => any) | null;\ndeclare var onvrdisplaypresentchange: ((this: Window, ev: Event) => any) | null;\ndeclare var onwaiting: ((this: Window, ev: Event) => any) | null;\ndeclare var opener: any;\ndeclare var orientation: string | number;\ndeclare var outerHeight: number;\ndeclare var outerWidth: number;\ndeclare var pageXOffset: number;\ndeclare var pageYOffset: number;\ndeclare var parent: Window;\ndeclare var performance: Performance;\ndeclare var personalbar: BarProp;\ndeclare var screen: Screen;\ndeclare var screenLeft: number;\ndeclare var screenTop: number;\ndeclare var screenX: number;\ndeclare var screenY: number;\ndeclare var scrollX: number;\ndeclare var scrollY: number;\ndeclare var scrollbars: BarProp;\ndeclare var self: Window;\ndeclare var speechSynthesis: SpeechSynthesis;\ndeclare var status: string;\ndeclare var statusbar: BarProp;\ndeclare var styleMedia: StyleMedia;\ndeclare var toolbar: BarProp;\ndeclare var top: Window;\ndeclare var window: Window;\ndeclare function alert(message?: any): void;\ndeclare function blur(): void;\ndeclare function cancelAnimationFrame(handle: number): void;\n/** @deprecated */\ndeclare function captureEvents(): void;\ndeclare function close(): void;\ndeclare function confirm(message?: string): boolean;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise;\ndeclare function createImageBitmap(image: HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise;\ndeclare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;\ndeclare function focus(): void;\ndeclare function getComputedStyle(elt: Element, pseudoElt?: string | null): CSSStyleDeclaration;\ndeclare function getMatchedCSSRules(elt: Element, pseudoElt?: string | null): CSSRuleList;\ndeclare function getSelection(): Selection;\ndeclare function matchMedia(mediaQuery: string): MediaQueryList;\ndeclare function moveBy(x?: number, y?: number): void;\ndeclare function moveTo(x?: number, y?: number): void;\ndeclare function msWriteProfilerMark(profilerMarkName: string): void;\ndeclare function open(url?: string, target?: string, features?: string, replace?: boolean): Window | null;\ndeclare function postMessage(message: any, targetOrigin: string, transfer?: any[]): void;\ndeclare function print(): void;\ndeclare function prompt(message?: string, _default?: string): string | null;\n/** @deprecated */\ndeclare function releaseEvents(): void;\ndeclare function requestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function resizeBy(x?: number, y?: number): void;\ndeclare function resizeTo(x?: number, y?: number): void;\ndeclare function scroll(options?: ScrollToOptions): void;\ndeclare function scroll(x?: number, y?: number): void;\ndeclare function scrollBy(options?: ScrollToOptions): void;\ndeclare function scrollBy(x?: number, y?: number): void;\ndeclare function scrollTo(options?: ScrollToOptions): void;\ndeclare function scrollTo(x?: number, y?: number): void;\ndeclare function stop(): void;\ndeclare function webkitCancelAnimationFrame(handle: number): void;\ndeclare function webkitConvertPointFromNodeToPage(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitConvertPointFromPageToNode(node: Node, pt: WebKitPoint): WebKitPoint;\ndeclare function webkitRequestAnimationFrame(callback: FrameRequestCallback): number;\ndeclare function toString(): string;\ndeclare function dispatchEvent(evt: Event): boolean;\ndeclare function clearInterval(handle?: number): void;\ndeclare function clearTimeout(handle?: number): void;\ndeclare function setInterval(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setInterval(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function setTimeout(handler: (...args: any[]) => void, timeout: number): number;\ndeclare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;\ndeclare function clearImmediate(handle: number): void;\ndeclare function setImmediate(handler: (...args: any[]) => void): number;\ndeclare function setImmediate(handler: any, ...args: any[]): number;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare var console: Console;\ndeclare var onanimationcancel: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationend: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationiteration: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var onanimationstart: ((this: Window, ev: AnimationEvent) => any) | null;\ndeclare var ongotpointercapture: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onlostpointercapture: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointercancel: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerdown: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerenter: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerleave: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointermove: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerout: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerover: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var onpointerup: ((this: Window, ev: PointerEvent) => any) | null;\ndeclare var ontouchcancel: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchend: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchmove: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontouchstart: ((this: Window, ev: TouchEvent) => any) | null;\ndeclare var ontransitioncancel: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionend: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionrun: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var ontransitionstart: ((this: Window, ev: TransitionEvent) => any) | null;\ndeclare var onwheel: ((this: Window, ev: WheelEvent) => any) | null;\ndeclare var indexedDB: IDBFactory;\ndeclare function atob(encodedString: string): string;\ndeclare function btoa(rawString: string): string;\ndeclare function fetch(input?: Request | string, init?: RequestInit): Promise;\ndeclare var sessionStorage: Storage;\ndeclare var localStorage: Storage;\ndeclare function addEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;\ndeclare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\ndeclare function removeEventListener(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void;\ndeclare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\ntype BlobPart = BufferSource | Blob | string;\ntype HeadersInit = Headers | string[][] | Record;\ntype BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string;\ntype RequestInfo = Request | string;\ntype DOMHighResTimeStamp = number;\ntype PerformanceEntryList = PerformanceEntry[];\ntype PushMessageDataInit = BufferSource | string;\ntype VibratePattern = number | number[];\ntype BufferSource = ArrayBufferView | ArrayBuffer;\ntype DOMTimeStamp = number;\ntype FormDataEntryValue = File | string;\ntype ScrollBehavior = \"auto\" | \"instant\" | \"smooth\";\ntype ScrollLogicalPosition = \"start\" | \"center\" | \"end\" | \"nearest\";\ntype MouseWheelEvent = WheelEvent;\ntype ScrollRestoration = \"auto\" | \"manual\";\ntype InsertPosition = \"beforebegin\" | \"afterbegin\" | \"beforeend\" | \"afterend\";\ntype OrientationLockType = \"any\" | \"natural\" | \"portrait\" | \"landscape\" | \"portrait-primary\" | \"portrait-secondary\" | \"landscape-primary\"| \"landscape-secondary\";\ntype IDBValidKey = number | string | Date | BufferSource | IDBArrayKey;\ntype AlgorithmIdentifier = string | Algorithm;\ntype MutationRecordType = \"attributes\" | \"characterData\" | \"childList\";\ntype AAGUID = string;\ntype ByteString = string;\ntype ConstrainBoolean = boolean | ConstrainBooleanParameters;\ntype ConstrainDOMString = string | string[] | ConstrainDOMStringParameters;\ntype ConstrainDouble = number | ConstrainDoubleRange;\ntype ConstrainLong = number | ConstrainLongRange;\ntype CryptoOperationData = ArrayBufferView;\ntype GLbitfield = number;\ntype GLboolean = boolean;\ntype GLbyte = number;\ntype GLclampf = number;\ntype GLenum = number;\ntype GLfloat = number;\ntype GLint = number;\ntype GLintptr = number;\ntype GLshort = number;\ntype GLsizei = number;\ntype GLsizeiptr = number;\ntype GLubyte = number;\ntype GLuint = number;\ntype GLushort = number;\ntype IDBKeyPath = string;\ntype MSInboundPayload = MSVideoRecvPayload | MSAudioRecvPayload;\ntype MSLocalClientEvent = MSLocalClientEventBase | MSAudioLocalClientEvent;\ntype MSOutboundPayload = MSVideoSendPayload | MSAudioSendPayload;\ntype RTCIceGatherCandidate = RTCIceCandidateDictionary | RTCIceCandidateComplete;\ntype RTCTransport = RTCDtlsTransport | RTCSrtpSdesTransport;\ntype USVString = string;\ntype payloadtype = number;\ntype MessageEventSource = Window | MessagePort | ServiceWorker;\ntype AnimationPlayState = \"idle\" | \"running\" | \"paused\" | \"finished\";\ntype AppendMode = \"segments\" | \"sequence\";\ntype AudioContextLatencyCategory = \"balanced\" | \"interactive\" | \"playback\";\ntype AudioContextState = \"suspended\" | \"running\" | \"closed\";\ntype AutomationRate = \"a-rate\" | \"k-rate\";\ntype BinaryType = \"blob\" | \"arraybuffer\";\ntype BiquadFilterType = \"lowpass\" | \"highpass\" | \"bandpass\" | \"lowshelf\" | \"highshelf\" | \"peaking\" | \"notch\" | \"allpass\";\ntype CanPlayTypeResult = \"\" | \"maybe\" | \"probably\";\ntype CanvasFillRule = \"nonzero\" | \"evenodd\";\ntype ChannelCountMode = \"max\" | \"clamped-max\" | \"explicit\";\ntype ChannelInterpretation = \"speakers\" | \"discrete\";\ntype ClientTypes = \"window\" | \"worker\" | \"sharedworker\" | \"all\";\ntype CompositeOperation = \"replace\" | \"add\" | \"accumulate\";\ntype DisplayCaptureSurfaceType = \"monitor\" | \"window\" | \"application\" | \"browser\";\ntype DistanceModelType = \"linear\" | \"inverse\" | \"exponential\";\ntype DocumentReadyState = \"loading\" | \"interactive\" | \"complete\";\ntype EndOfStreamError = \"network\" | \"decode\";\ntype ExpandGranularity = \"character\" | \"word\" | \"sentence\" | \"textedit\";\ntype FillMode = \"none\" | \"forwards\" | \"backwards\" | \"both\" | \"auto\";\ntype GamepadHand = \"\" | \"left\" | \"right\";\ntype GamepadHapticActuatorType = \"vibration\";\ntype GamepadInputEmulationType = \"mouse\" | \"keyboard\" | \"gamepad\";\ntype GamepadMappingType = \"\" | \"standard\";\ntype IDBCursorDirection = \"next\" | \"nextunique\" | \"prev\" | \"prevunique\";\ntype IDBRequestReadyState = \"pending\" | \"done\";\ntype IDBTransactionMode = \"readonly\" | \"readwrite\" | \"versionchange\";\ntype IterationCompositeOperation = \"replace\" | \"accumulate\";\ntype KeyFormat = \"raw\" | \"spki\" | \"pkcs8\" | \"jwk\";\ntype KeyType = \"public\" | \"private\" | \"secret\";\ntype KeyUsage = \"encrypt\" | \"decrypt\" | \"sign\" | \"verify\" | \"deriveKey\" | \"deriveBits\" | \"wrapKey\" | \"unwrapKey\";\ntype ListeningState = \"inactive\" | \"active\" | \"disambiguation\";\ntype MSCredentialType = \"FIDO_2_0\";\ntype MSIceAddrType = \"os\" | \"stun\" | \"turn\" | \"peer-derived\";\ntype MSIceType = \"failed\" | \"direct\" | \"relay\";\ntype MSStatsType = \"description\" | \"localclientevent\" | \"inbound-network\" | \"outbound-network\" | \"inbound-payload\" | \"outbound-payload\" | \"transportdiagnostics\";\ntype MSTransportType = \"Embedded\" | \"USB\" | \"NFC\" | \"BT\";\ntype MSWebViewPermissionState = \"unknown\" | \"defer\" | \"allow\" | \"deny\";\ntype MSWebViewPermissionType = \"geolocation\" | \"unlimitedIndexedDBQuota\" | \"media\" | \"pointerlock\" | \"webnotifications\";\ntype MediaDeviceKind = \"audioinput\" | \"audiooutput\" | \"videoinput\";\ntype MediaKeyMessageType = \"license-request\" | \"license-renewal\" | \"license-release\" | \"individualization-request\";\ntype MediaKeySessionType = \"temporary\" | \"persistent-license\" | \"persistent-release-message\";\ntype MediaKeyStatus = \"usable\" | \"expired\" | \"output-downscaled\" | \"output-not-allowed\" | \"status-pending\" | \"internal-error\";\ntype MediaKeysRequirement = \"required\" | \"optional\" | \"not-allowed\";\ntype MediaStreamTrackState = \"live\" | \"ended\";\ntype NavigationReason = \"up\" | \"down\" | \"left\" | \"right\";\ntype NavigationType = \"navigate\" | \"reload\" | \"back_forward\" | \"prerender\";\ntype NotificationDirection = \"auto\" | \"ltr\" | \"rtl\";\ntype NotificationPermission = \"default\" | \"denied\" | \"granted\";\ntype OscillatorType = \"sine\" | \"square\" | \"sawtooth\" | \"triangle\" | \"custom\";\ntype OverSampleType = \"none\" | \"2x\" | \"4x\";\ntype PanningModelType = \"equalpower\" | \"HRTF\";\ntype PaymentComplete = \"success\" | \"fail\" | \"unknown\";\ntype PaymentShippingType = \"shipping\" | \"delivery\" | \"pickup\";\ntype PlaybackDirection = \"normal\" | \"reverse\" | \"alternate\" | \"alternate-reverse\";\ntype PushEncryptionKeyName = \"p256dh\" | \"auth\";\ntype PushPermissionState = \"denied\" | \"granted\" | \"prompt\";\ntype RTCBundlePolicy = \"balanced\" | \"max-compat\" | \"max-bundle\";\ntype RTCDataChannelState = \"connecting\" | \"open\" | \"closing\" | \"closed\";\ntype RTCDegradationPreference = \"maintain-framerate\" | \"maintain-resolution\" | \"balanced\";\ntype RTCDtlsRole = \"auto\" | \"client\" | \"server\";\ntype RTCDtlsTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\" | \"failed\";\ntype RTCDtxStatus = \"disabled\" | \"enabled\";\ntype RTCErrorDetailType = \"data-channel-failure\" | \"dtls-failure\" | \"fingerprint-failure\" | \"idp-bad-script-failure\" | \"idp-execution-failure\" | \"idp-load-failure\" | \"idp-need-login\" | \"idp-timeout\" | \"idp-tls-failure\" | \"idp-token-expired\" | \"idp-token-invalid\" | \"sctp-failure\" | \"sdp-syntax-error\" | \"hardware-encoder-not-available\" | \"hardware-encoder-error\";\ntype RTCIceCandidateType = \"host\" | \"srflx\" | \"prflx\" | \"relay\";\ntype RTCIceComponent = \"rtp\" | \"rtcp\";\ntype RTCIceConnectionState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCIceCredentialType = \"password\" | \"oauth\";\ntype RTCIceGatherPolicy = \"all\" | \"nohost\" | \"relay\";\ntype RTCIceGathererState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceGatheringState = \"new\" | \"gathering\" | \"complete\";\ntype RTCIceProtocol = \"udp\" | \"tcp\";\ntype RTCIceRole = \"controlling\" | \"controlled\";\ntype RTCIceTcpCandidateType = \"active\" | \"passive\" | \"so\";\ntype RTCIceTransportPolicy = \"relay\" | \"all\";\ntype RTCIceTransportState = \"new\" | \"checking\" | \"connected\" | \"completed\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCPeerConnectionState = \"new\" | \"connecting\" | \"connected\" | \"disconnected\" | \"failed\" | \"closed\";\ntype RTCPriorityType = \"very-low\" | \"low\" | \"medium\" | \"high\";\ntype RTCRtcpMuxPolicy = \"negotiate\" | \"require\";\ntype RTCRtpTransceiverDirection = \"sendrecv\" | \"sendonly\" | \"recvonly\" | \"inactive\";\ntype RTCSctpTransportState = \"new\" | \"connecting\" | \"connected\" | \"closed\";\ntype RTCSdpType = \"offer\" | \"pranswer\" | \"answer\" | \"rollback\";\ntype RTCSignalingState = \"stable\" | \"have-local-offer\" | \"have-remote-offer\" | \"have-local-pranswer\" | \"have-remote-pranswer\" | \"closed\";\ntype RTCStatsIceCandidatePairState = \"frozen\" | \"waiting\" | \"inprogress\" | \"failed\" | \"succeeded\" | \"cancelled\";\ntype RTCStatsIceCandidateType = \"host\" | \"serverreflexive\" | \"peerreflexive\" | \"relayed\";\ntype RTCStatsType = \"inboundrtp\" | \"outboundrtp\" | \"session\" | \"datachannel\" | \"track\" | \"transport\" | \"candidatepair\" | \"localcandidate\" | \"remotecandidate\";\ntype ReadyState = \"closed\" | \"open\" | \"ended\";\ntype ReferrerPolicy = \"\" | \"no-referrer\" | \"no-referrer-when-downgrade\" | \"origin-only\" | \"origin-when-cross-origin\" | \"unsafe-url\";\ntype RequestCache = \"default\" | \"no-store\" | \"reload\" | \"no-cache\" | \"force-cache\" | \"only-if-cached\";\ntype RequestCredentials = \"omit\" | \"same-origin\" | \"include\";\ntype RequestDestination = \"\" | \"audio\" | \"audioworklet\" | \"document\" | \"embed\" | \"font\" | \"image\" | \"manifest\" | \"object\" | \"paintworklet\" | \"report\" | \"script\" | \"sharedworker\" | \"style\" | \"track\" | \"video\" | \"worker\" | \"xslt\";\ntype RequestMode = \"navigate\" | \"same-origin\" | \"no-cors\" | \"cors\";\ntype RequestRedirect = \"follow\" | \"error\" | \"manual\";\ntype ResponseType = \"basic\" | \"cors\" | \"default\" | \"error\" | \"opaque\" | \"opaqueredirect\";\ntype ScopedCredentialType = \"ScopedCred\";\ntype SelectionMode = \"select\" | \"start\" | \"end\" | \"preserve\";\ntype ServiceWorkerState = \"installing\" | \"installed\" | \"activating\" | \"activated\" | \"redundant\";\ntype ServiceWorkerUpdateViaCache = \"imports\" | \"all\" | \"none\";\ntype TextTrackKind = \"subtitles\" | \"captions\" | \"descriptions\" | \"chapters\" | \"metadata\";\ntype TextTrackMode = \"disabled\" | \"hidden\" | \"showing\";\ntype TouchType = \"direct\" | \"stylus\";\ntype Transport = \"usb\" | \"nfc\" | \"ble\";\ntype VRDisplayEventReason = \"mounted\" | \"navigation\" | \"requested\" | \"unmounted\";\ntype VREye = \"left\" | \"right\";\ntype VideoFacingModeEnum = \"user\" | \"environment\" | \"left\" | \"right\";\ntype VisibilityState = \"hidden\" | \"visible\" | \"prerender\" | \"unloaded\";\ntype WorkerType = \"classic\" | \"module\";\ntype XMLHttpRequestResponseType = \"\" | \"arraybuffer\" | \"blob\" | \"document\" | \"json\" | \"text\";\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n/////////////////////////////\n/// WorkerGlobalScope APIs\n/////////////////////////////\n// These are only available in a Web Worker\ndeclare function importScripts(...urls: string[]): void;\n\n\n\n/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0 \n \nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, \nMERCHANTABLITY OR NON-INFRINGEMENT. \n \nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// \n\n\n\n\n/////////////////////////////\n/// Windows Script Host APIS\n/////////////////////////////\n\n\ninterface ActiveXObject {\n new (s: string): any;\n}\ndeclare var ActiveXObject: ActiveXObject;\n\ninterface ITextWriter {\n Write(s: string): void;\n WriteLine(s: string): void;\n Close(): void;\n}\n\ninterface TextStreamBase {\n /**\n * The column number of the current character position in an input stream.\n */\n Column: number;\n\n /**\n * The current line number in an input stream.\n */\n Line: number;\n\n /**\n * Closes a text stream.\n * It is not necessary to close standard streams; they close automatically when the process ends. If\n * you close a standard stream, be aware that any other pointers to that standard stream become invalid.\n */\n Close(): void;\n}\n\ninterface TextStreamWriter extends TextStreamBase {\n /**\n * Sends a string to an output stream.\n */\n Write(s: string): void;\n\n /**\n * Sends a specified number of blank lines (newline characters) to an output stream.\n */\n WriteBlankLines(intLines: number): void;\n\n /**\n * Sends a string followed by a newline character to an output stream.\n */\n WriteLine(s: string): void;\n}\n\ninterface TextStreamReader extends TextStreamBase {\n /**\n * Returns a specified number of characters from an input stream, starting at the current pointer position.\n * Does not return until the ENTER key is pressed.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n Read(characters: number): string;\n\n /**\n * Returns all characters from an input stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadAll(): string;\n\n /**\n * Returns an entire line from an input stream.\n * Although this method extracts the newline character, it does not add it to the returned string.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n */\n ReadLine(): string;\n\n /**\n * Skips a specified number of characters when reading from an input text stream.\n * Can only be used on a stream in reading mode; causes an error in writing or appending mode.\n * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.)\n */\n Skip(characters: number): void;\n\n /**\n * Skips the next line when reading from an input text stream.\n * Can only be used on a stream in reading mode, not writing or appending mode.\n */\n SkipLine(): void;\n\n /**\n * Indicates whether the stream pointer position is at the end of a line.\n */\n AtEndOfLine: boolean;\n\n /**\n * Indicates whether the stream pointer position is at the end of a stream.\n */\n AtEndOfStream: boolean;\n}\n\ndeclare var WScript: {\n /**\n * Outputs text to either a message box (under WScript.exe) or the command console window followed by\n * a newline (under CScript.exe).\n */\n Echo(s: any): void;\n\n /**\n * Exposes the write-only error output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdErr: TextStreamWriter;\n\n /**\n * Exposes the write-only output stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdOut: TextStreamWriter;\n Arguments: { length: number; Item(n: number): string; };\n\n /**\n * The full path of the currently running script.\n */\n ScriptFullName: string;\n\n /**\n * Forces the script to stop immediately, with an optional exit code.\n */\n Quit(exitCode?: number): number;\n\n /**\n * The Windows Script Host build version number.\n */\n BuildVersion: number;\n\n /**\n * Fully qualified path of the host executable.\n */\n FullName: string;\n\n /**\n * Gets/sets the script mode - interactive(true) or batch(false).\n */\n Interactive: boolean;\n\n /**\n * The name of the host executable (WScript.exe or CScript.exe).\n */\n Name: string;\n\n /**\n * Path of the directory containing the host executable.\n */\n Path: string;\n\n /**\n * The filename of the currently running script.\n */\n ScriptName: string;\n\n /**\n * Exposes the read-only input stream for the current script.\n * Can be accessed only while using CScript.exe.\n */\n StdIn: TextStreamReader;\n\n /**\n * Windows Script Host version\n */\n Version: string;\n\n /**\n * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event.\n */\n ConnectObject(objEventSource: any, strPrefix: string): void;\n\n /**\n * Creates a COM object.\n * @param strProgiID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n CreateObject(strProgID: string, strPrefix?: string): any;\n\n /**\n * Disconnects a COM object from its event sources.\n */\n DisconnectObject(obj: any): void;\n\n /**\n * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file.\n * @param strPathname Fully qualified path to the file containing the object persisted to disk.\n * For objects in memory, pass a zero-length string.\n * @param strProgID\n * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events.\n */\n GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any;\n\n /**\n * Suspends script execution for a specified length of time, then continues execution.\n * @param intTime Interval (in milliseconds) to suspend script execution.\n */\n Sleep(intTime: number): void;\n};\n\n/**\n * WSH is an alias for WScript under Windows Script Host\n */\ndeclare var WSH: typeof WScript;\n\n/**\n * Represents an Automation SAFEARRAY\n */\ndeclare class SafeArray {\n private constructor();\n private SafeArray_typekey: SafeArray;\n}\n\n/**\n * Allows enumerating over a COM collection, which may not have indexed item access.\n */\ninterface Enumerator {\n /**\n * Returns true if the current item is the last one in the collection, or the collection is empty,\n * or the current item is undefined.\n */\n atEnd(): boolean;\n\n /**\n * Returns the current item in the collection\n */\n item(): T;\n\n /**\n * Resets the current item in the collection to the first item. If there are no items in the collection,\n * the current item is set to undefined.\n */\n moveFirst(): void;\n\n /**\n * Moves the current item to the next item in the collection. If the enumerator is at the end of\n * the collection or the collection is empty, the current item is set to undefined.\n */\n moveNext(): void;\n}\n\ninterface EnumeratorConstructor {\n new (safearray: SafeArray): Enumerator;\n new (collection: { Item(index: any): T }): Enumerator;\n new (collection: any): Enumerator;\n}\n\ndeclare var Enumerator: EnumeratorConstructor;\n\n/**\n * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions.\n */\ninterface VBArray {\n /**\n * Returns the number of dimensions (1-based).\n */\n dimensions(): number;\n\n /**\n * Takes an index for each dimension in the array, and returns the item at the corresponding location.\n */\n getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T;\n\n /**\n * Returns the smallest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n lbound(dimension?: number): number;\n\n /**\n * Returns the largest available index for a given dimension.\n * @param dimension 1-based dimension (defaults to 1)\n */\n ubound(dimension?: number): number;\n\n /**\n * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions,\n * each successive dimension is appended to the end of the array.\n * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6]\n */\n toArray(): T[];\n}\n\ninterface VBArrayConstructor {\n new (safeArray: SafeArray): VBArray;\n}\n\ndeclare var VBArray: VBArrayConstructor;\n\n/**\n * Automation date (VT_DATE)\n */\ndeclare class VarDate {\n private constructor();\n private VarDate_typekey: VarDate;\n}\n\ninterface DateConstructor {\n new (vd: VarDate): Date;\n}\n\ninterface Date {\n getVarDate: () => VarDate;\n}\n\n\n"; diff --git a/src/lib/typescriptServices-amd.js b/src/lib/typescriptServices-amd.js index 59a048c5..a573383c 100644 --- a/src/lib/typescriptServices-amd.js +++ b/src/lib/typescriptServices-amd.js @@ -14,18 +14,55 @@ 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]; +var __assign = (this && this.__assign) || function () { + __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; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return t; +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; }; var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -33,6 +70,13 @@ var __extends = (this && this.__extends) || (function () { }; })(); var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.0"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".1"; +})(ts || (ts = {})); (function (ts) { /* @internal */ var Comparison; @@ -41,7 +85,1953 @@ var ts; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); - // token > SyntaxKind.Identifer => token is a keyword +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.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 = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i])) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + var key = keySelector(value); + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearch = binarySearch; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + 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 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + 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."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertTypeIsNever(_) { } // tslint:disable-line no-empty + ts.assertTypeIsNever = assertTypeIsNever; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + 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 = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync var SyntaxKind; (function (SyntaxKind) { @@ -198,185 +2188,195 @@ var ts; SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 178] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 179] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 180] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 181] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 182] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 183] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 184] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 185] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 186] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 187] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 188] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 189] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 190] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 191] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 192] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 193] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 194] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 195] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 196] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 197] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 198] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 199] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 200] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 201] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 202] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 203] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 204] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 205] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 206] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 207] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 208] = "MetaProperty"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 209] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 210] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 211] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 212] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 213] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 214] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 215] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 216] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 217] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 218] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 219] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 220] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 221] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 222] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 223] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 224] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 225] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 226] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 227] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 228] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 229] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 230] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 231] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 232] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 233] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 234] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 235] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 236] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 237] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 238] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 239] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 240] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 241] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 242] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 243] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 244] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 245] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 246] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 247] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 248] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 249] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 250] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 251] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 252] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 253] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 254] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 255] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 256] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 257] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 258] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 259] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 260] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 261] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 262] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 263] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 264] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 265] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 266] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 267] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 268] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 269] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 270] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 271] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 272] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 273] = "Bundle"; + SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 274] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 275] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 276] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 277] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 278] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 279] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 280] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 281] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 282] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 283] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 286] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 287] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 288] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 289] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 290] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 291] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 292] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 293] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 294] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 295] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 296] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -385,15 +2385,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 177] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -402,13 +2402,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 274] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 292] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 284] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 292] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -432,26 +2432,32 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - // This flag will be set when the parser encounters a dynamic import expression so that module resolution - // will not have to walk the tree if the flag is not set. However, this flag is just a approximation because - // once it is set, the flag never gets cleared (hence why it's named "PossiblyContainsDynamicImport"). - // During editing, if dynamic import is removed, incremental parsing will *NOT* update this flag. This means that the tree will always be traversed - // during module resolution. However, the removal operation should not occur often and in the case of the + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the // removal, it is likely that users will add the import anyway. // The advantage of this approach is its simplicity. For the case of batch compilation, // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. - /* @internal */ - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; - /* @internal */ NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; - /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; // Exclude these flags when parsing a Type NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); var ModifierFlags; (function (ModifierFlags) { @@ -474,6 +2480,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -502,8 +2509,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; @@ -572,15 +2580,16 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -758,8 +2767,6 @@ var ts; 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"; @@ -791,6 +2798,8 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -840,74 +2849,93 @@ var ts; 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["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 2048] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 8192] = "Null"; - TypeFlags[TypeFlags["Never"] = 16384] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 65536] = "Object"; - TypeFlags[TypeFlags["Union"] = 131072] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 524288] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 4096] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 16384] = "Null"; + TypeFlags[TypeFlags["Never"] = 32768] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 131072] = "Object"; + TypeFlags[TypeFlags["Union"] = 262144] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType"; + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; + TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -1048,6 +3076,11 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1058,6 +3091,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1065,12 +3099,6 @@ var ts; LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - /* @internal */ - 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"; @@ -1293,6 +3321,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1406,9 +3435,9 @@ var ts; // Precomputed Formats 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["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1424,12 +3453,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "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["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1479,6 +3508,7 @@ var ts; "reference": { args: [ { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, { name: "path", optional: true, captureSpan: true }, { name: "no-default-lib", optional: true } ], @@ -1504,3004 +3534,6 @@ var ts; }, }); })(ts || (ts = {})); -/*@internal*/ -var ts; -(function (ts) { - /** Gets a timestamp with (at least) ms resolution */ - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -/*@internal*/ -/** Performance measurements for the compiler. */ -(function (ts) { - var performance; - (function (performance) { - // NOTE: cannot use ts.noop as core.ts loads after this - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName) { - if (enabled) { - marks.set(markName, ts.timestamp()); - counts.set(markName, (counts.get(markName) || 0) + 1); - profilerEvent(markName); - } - } - performance.mark = mark; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); - var start = startMarkName && marks.get(startMarkName) || profilerStart; - measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); - } - } - performance.measure = measure; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName) { - return counts && counts.get(markName) || 0; - } - performance.getCount = getCount; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName) { - return measures && measures.get(measureName) || 0; - } - performance.getDuration = getDuration; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb) { - measures.forEach(function (measure, key) { - cb(key, measure); - }); - } - performance.forEachMeasure = forEachMeasure; - /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - /** Disables performance measurements for the compiler. */ - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); -/// -/// -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.8"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; -})(ts || (ts = {})); -(function (ts) { - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. - return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - function sortAndDeduplicateDiagnostics(diagnostics) { - return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); - } - ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - function closeFileWatcher(watcher) { - watcher.close(); - } - ts.closeFileWatcher = closeFileWatcher; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new MapCtr(); - } - ts.createMap = createMap; - /** Create a new escaped identifier map. */ - function createUnderscoreEscapedMap() { - return new MapCtr(); - } - ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - function createSymbolTable(symbols) { - var result = createMap(); - if (symbols) { - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.escapedName, symbol); - } - } - return result; - } - ts.createSymbolTable = createSymbolTable; - function createMapFromTemplate(template) { - var map = new MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // tslint:disable-next-line no-in-operator variable-name - 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 = /** @class */ (function () { - function MapIterator(data, selector) { - this.index = 0; - this.data = data; - this.selector = selector; - this.keys = Object.keys(data); - } - MapIterator.prototype.next = function () { - var index = this.index; - if (index < this.keys.length) { - this.index++; - return { value: this.selector(this.data, this.keys[index]), done: false }; - } - return { value: undefined, done: true }; - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - } - class_1.prototype.get = function (key) { - return this.data[key]; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - } - this.data[key] = value; - return this; - }; - class_1.prototype.has = function (key) { - // tslint:disable-next-line:no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - delete this.data[key]; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.data, function (_data, key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.data, function (data, key) { return data[key]; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); - }; - class_1.prototype.forEach = function (action) { - for (var key in this.data) { - action(this.data[key], key); - } - }; - return class_1; - }()); - } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = isRootedDiskPath(fileName) - ? normalizePath(fileName) - : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; - function length(array) { - return array ? array.length : 0; - } - ts.length = length; - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEach(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - return undefined; - } - ts.forEach = forEach; - /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ - function firstDefined(array, callback) { - if (array === undefined) { - return undefined; - } - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result !== undefined) { - return result; - } - } - return undefined; - } - ts.firstDefined = firstDefined; - function firstDefinedIterator(iter, callback) { - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) { - return undefined; - } - var result = callback(value); - if (result !== undefined) { - return result; - } - } - } - ts.firstDefinedIterator = firstDefinedIterator; - function findAncestor(node, callback) { - while (node) { - var result = callback(node); - if (result === "quit") { - return undefined; - } - else if (result) { - return node; - } - node = node.parent; - } - return undefined; - } - ts.findAncestor = findAncestor; - function zipWith(arrayA, arrayB, callback) { - var result = []; - Debug.assertEqual(arrayA.length, arrayB.length); - for (var i = 0; i < arrayA.length; i++) { - result.push(callback(arrayA[i], arrayB[i], i)); - } - return result; - } - ts.zipWith = zipWith; - function zipToIterator(arrayA, arrayB) { - Debug.assertEqual(arrayA.length, arrayB.length); - var i = 0; - return { - next: function () { - if (i === arrayA.length) { - return { value: undefined, done: true }; - } - i++; - return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; - } - }; - } - ts.zipToIterator = zipToIterator; - function zipToMap(keys, values) { - Debug.assert(keys.length === values.length); - var map = createMap(); - for (var i = 0; i < keys.length; ++i) { - map.set(keys[i], values[i]); - } - return map; - } - ts.zipToMap = zipToMap; - /** - * Iterates through `array` by index and performs the callback on each element of array until the callback - * returns a falsey value, then returns false. - * If no such value is found, the callback is applied to each element of array and `true` is returned. - */ - function every(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!callback(array[i], i)) { - return false; - } - } - } - return true; - } - ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.findLast = findLast; - /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { - if (predicate(array[i], i)) { - return i; - } - } - return -1; - } - ts.findIndex = findIndex; - /** - * Returns the first truthy result of `callback`, or else fails. - * This is like `forEach`, but never returns undefined. - */ - function findMap(array, callback) { - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (array) { - for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { - var v = array_1[_i]; - if (equalityComparer(v, value)) { - return true; - } - } - } - return false; - } - ts.contains = contains; - function arraysEqual(a, b, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); - } - ts.arraysEqual = arraysEqual; - function indexOfAnyCharCode(text, charCodes, start) { - for (var i = start || 0; i < text.length; i++) { - if (contains(charCodes, text.charCodeAt(i))) { - return i; - } - } - return -1; - } - ts.indexOfAnyCharCode = indexOfAnyCharCode; - function countWhere(array, predicate) { - var count = 0; - if (array) { - for (var i = 0; i < array.length; i++) { - var v = array[i]; - if (predicate(v, i)) { - count++; - } - } - } - return count; - } - ts.countWhere = countWhere; - function filter(array, f) { - if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; - } - return result; - } - } - return array; - } - ts.filter = filter; - function filterMutate(array, f) { - var outIndex = 0; - for (var i = 0; i < array.length; i++) { - if (f(array[i], i, array)) { - array[outIndex] = array[i]; - outIndex++; - } - } - array.length = outIndex; - } - ts.filterMutate = filterMutate; - function clear(array) { - array.length = 0; - } - ts.clear = clear; - function map(array, f) { - var result; - if (array) { - result = []; - for (var i = 0; i < array.length; i++) { - result.push(f(array[i], i)); - } - } - return result; - } - ts.map = map; - function mapIterator(iter, mapFn) { - return { - next: function () { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } - }; - } - ts.mapIterator = mapIterator; - function sameMap(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = f(item, i); - if (item !== mapped) { - var result = array.slice(0, i); - result.push(mapped); - for (i++; i < array.length; i++) { - result.push(f(array[i], i)); - } - return result; - } - } - } - return array; - } - ts.sameMap = sameMap; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ - function flatten(array) { - var result; - if (array) { - result = []; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (v) { - if (isArray(v)) { - addRange(result, v); - } - else { - result.push(v); - } - } - } - } - return result; - } - ts.flatten = flatten; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ - function flatMap(array, mapfn) { - var result; - if (array) { - result = []; - for (var i = 0; i < array.length; i++) { - var v = mapfn(array[i], i); - if (v) { - if (isArray(v)) { - addRange(result, v); - } - else { - result.push(v); - } - } - } - } - return result; - } - ts.flatMap = flatMap; - function flatMapIterator(iter, mapfn) { - var first = iter.next(); - if (first.done) { - return ts.emptyIterator; - } - var currentIter = getIterator(first.value); - return { - next: function () { - while (true) { - var currentRes = currentIter.next(); - if (!currentRes.done) { - return currentRes; - } - var iterRes = iter.next(); - if (iterRes.done) { - return iterRes; - } - currentIter = getIterator(iterRes.value); - } - }, - }; - function getIterator(x) { - var res = mapfn(x); - return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; - } - } - ts.flatMapIterator = flatMapIterator; - function sameFlatMap(array, mapfn) { - var result; - if (array) { - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapfn(item, i); - if (result || item !== mapped || isArray(mapped)) { - if (!result) { - result = array.slice(0, i); - } - if (isArray(mapped)) { - addRange(result, mapped); - } - else { - result.push(mapped); - } - } - } - } - return result || array; - } - ts.sameFlatMap = sameFlatMap; - function mapAllOrFail(array, mapFn) { - var result = []; - for (var i = 0; i < array.length; i++) { - var mapped = mapFn(array[i], i); - if (mapped === undefined) { - return undefined; - } - result.push(mapped); - } - return result; - } - ts.mapAllOrFail = mapAllOrFail; - function mapDefined(array, mapFn) { - var result = []; - if (array) { - for (var i = 0; i < array.length; i++) { - var mapped = mapFn(array[i], i); - if (mapped !== undefined) { - result.push(mapped); - } - } - } - return result; - } - ts.mapDefined = mapDefined; - function mapDefinedIterator(iter, mapFn) { - return { - next: function () { - while (true) { - var res = iter.next(); - if (res.done) { - return res; - } - var value = mapFn(res.value); - if (value !== undefined) { - return { value: value, done: false }; - } - } - } - }; - } - ts.mapDefinedIterator = mapDefinedIterator; - ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; - function singleIterator(value) { - var done = false; - return { - next: function () { - var wasDone = done; - done = true; - return wasDone ? { value: undefined, done: true } : { value: value, done: false }; - } - }; - } - ts.singleIterator = singleIterator; - /** - * Computes the first matching span of elements and returns a tuple of the first span - * and the remaining elements. - */ - function span(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ - function spanMap(array, keyfn, mapfn) { - var result; - if (array) { - result = []; - var len = array.length; - var previousKey = void 0; - var key = void 0; - var start = 0; - var pos = 0; - while (start < len) { - while (pos < len) { - var value = array[pos]; - key = keyfn(value, pos); - if (pos === 0) { - previousKey = key; - } - else if (key !== previousKey) { - break; - } - pos++; - } - if (start < pos) { - var v = mapfn(array.slice(start, pos), previousKey, start, pos); - if (v) { - result.push(v); - } - start = pos; - } - previousKey = key; - pos++; - } - } - return result; - } - ts.spanMap = spanMap; - function mapEntries(map, f) { - if (!map) { - return undefined; - } - var result = createMap(); - map.forEach(function (value, key) { - var _a = f(key, value), newKey = _a[0], newValue = _a[1]; - result.set(newKey, newValue); - }); - return result; - } - ts.mapEntries = mapEntries; - function some(array, predicate) { - if (array) { - if (predicate) { - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; - if (predicate(v)) { - return true; - } - } - } - else { - return array.length > 0; - } - } - return false; - } - ts.some = some; - function concatenate(array1, array2) { - if (!some(array2)) - return array1; - if (!some(array1)) - return array2; - return array1.concat(array2); - } - ts.concatenate = concatenate; - function deduplicateRelational(array, equalityComparer, comparer) { - // Perform a stable sort of the array. This ensures the first entry in a list of - // duplicates remains the first entry in the result. - var indices = array.map(function (_, i) { return i; }); - stableSortIndices(array, indices, comparer); - var last = array[indices[0]]; - var deduplicated = [indices[0]]; - for (var i = 1; i < indices.length; i++) { - var index = indices[i]; - var item = array[index]; - if (!equalityComparer(last, item)) { - deduplicated.push(index); - last = item; - } - } - // restore original order - deduplicated.sort(); - return deduplicated.map(function (i) { return array[i]; }); - } - function deduplicateEquality(array, equalityComparer) { - var result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; - pushIfUnique(result, item, equalityComparer); - } - return result; - } - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ - function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); - } - ts.deduplicate = deduplicate; - /** - * Deduplicates an array that has already been sorted. - */ - function deduplicateSorted(array, comparer) { - if (!array) - return undefined; - if (array.length === 0) - return []; - var last = array[0]; - var deduplicated = [last]; - for (var i = 1; i < array.length; i++) { - var next = array[i]; - switch (comparer(next, last)) { - // equality comparison - case true: - // relational comparison - case 0 /* EqualTo */: - continue; - case -1 /* LessThan */: - // If `array` is sorted, `next` should **never** be less than `last`. - return Debug.fail("Array is unsorted."); - } - deduplicated.push(last = next); - } - return deduplicated; - } - function insertSorted(array, insert, compare) { - if (array.length === 0) { - array.push(insert); - return; - } - var insertIndex = binarySearch(array, insert, identity, compare); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, insert); - } - } - ts.insertSorted = insertSorted; - function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); - } - ts.sortAndDeduplicate = sortAndDeduplicate; - function arrayIsEqualTo(array1, array2, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; - function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !equalOwnProperties(oldOptions.paths, newOptions.paths); - } - ts.changesAffectModuleResolution = changesAffectModuleResolution; - function compact(array) { - var result; - if (array) { - for (var i = 0; i < array.length; i++) { - var v = array[i]; - if (result || !v) { - if (!result) { - result = array.slice(0, i); - } - if (v) { - result.push(v); - } - } - } - } - return result || array; - } - ts.compact = compact; - /** - * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that - * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted - * based on the provided comparer. - */ - function relativeComplement(arrayA, arrayB, comparer) { - if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) - return arrayB; - var result = []; - loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { - if (offsetB > 0) { - // Ensure `arrayB` is properly sorted. - Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); - } - loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { - if (offsetA > startA) { - // Ensure `arrayA` is properly sorted. We only need to perform this check if - // `offsetA` has changed since we entered the loop. - Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); - } - switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1 /* LessThan */: - // If B is less than A, B does not exist in arrayA. Add B to the result and - // move to the next element in arrayB without changing the current position - // in arrayA. - result.push(arrayB[offsetB]); - continue loopB; - case 0 /* EqualTo */: - // If B is equal to A, B exists in arrayA. Move to the next element in - // arrayB without adding B to the result or changing the current position - // in arrayA. - continue loopB; - case 1 /* GreaterThan */: - // If B is greater than A, we need to keep looking for B in arrayA. Move to - // the next element in arrayA and recheck. - continue loopA; - } - } - } - return result; - } - ts.relativeComplement = relativeComplement; - function sum(array, prop) { - var result = 0; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - // TODO: Remove the following type assertion once the fix for #17069 is merged - result += v[prop]; - } - return result; - } - ts.sum = sum; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ - function append(to, value) { - if (value === undefined) - return to; - if (to === undefined) - return [value]; - to.push(value); - return to; - } - ts.append = append; - /** - * Gets the actual offset into an array for a relative offset. Negative offsets indicate a - * position offset from the end of the array. - */ - function toOffset(array, offset) { - return offset < 0 ? array.length + offset : offset; - } - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ - function addRange(to, from, start, end) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(start, end); - start = start === undefined ? 0 : toOffset(from, start); - end = end === undefined ? from.length : toOffset(from, end); - for (var i = start; i < end && i < from.length; i++) { - if (from[i] !== undefined) { - to.push(from[i]); - } - } - return to; - } - ts.addRange = addRange; - /** - * @return Whether the value was added. - */ - function pushIfUnique(array, toAdd, equalityComparer) { - if (contains(array, toAdd, equalityComparer)) { - return false; - } - else { - array.push(toAdd); - return true; - } - } - ts.pushIfUnique = pushIfUnique; - /** - * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. - */ - function appendIfUnique(array, toAdd, equalityComparer) { - if (array) { - pushIfUnique(array, toAdd, equalityComparer); - return array; - } - else { - return [toAdd]; - } - } - ts.appendIfUnique = appendIfUnique; - function stableSortIndices(array, indices, comparer) { - // sort indices by value then position - indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); - } - /** - * Returns a new sorted array. - */ - function sort(array, comparer) { - return array.slice().sort(comparer); - } - ts.sort = sort; - function best(iter, isBetter) { - var x = iter.next(); - if (x.done) { - return undefined; - } - var best = x.value; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) { - return best; - } - if (isBetter(value, best)) { - best = value; - } - } - } - ts.best = best; - function arrayIterator(array) { - var i = 0; - return { next: function () { - if (i === array.length) { - return { value: undefined, done: true }; - } - else { - i++; - return { value: array[i - 1], done: false }; - } - } }; - } - ts.arrayIterator = arrayIterator; - /** - * Stable sort of an array. Elements equal to each other maintain their relative position in the array. - */ - function stableSort(array, comparer) { - var indices = array.map(function (_, i) { return i; }); - stableSortIndices(array, indices, comparer); - return indices.map(function (i) { return array[i]; }); - } - ts.stableSort = stableSort; - function rangeEquals(array1, array2, pos, end) { - while (pos < end) { - if (array1[pos] !== array2[pos]) { - return false; - } - pos++; - } - return true; - } - ts.rangeEquals = rangeEquals; - /** - * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. - * A negative offset indicates the element should be retrieved from the end of the array. - */ - function elementAt(array, offset) { - if (array) { - offset = toOffset(array, offset); - if (offset < array.length) { - return array[offset]; - } - } - return undefined; - } - ts.elementAt = elementAt; - /** - * Returns the first element of an array if non-empty, `undefined` otherwise. - */ - function firstOrUndefined(array) { - return elementAt(array, 0); - } - ts.firstOrUndefined = firstOrUndefined; - function first(array) { - Debug.assert(array.length !== 0); - return array[0]; - } - ts.first = first; - /** - * Returns the last element of an array if non-empty, `undefined` otherwise. - */ - function lastOrUndefined(array) { - return elementAt(array, -1); - } - ts.lastOrUndefined = lastOrUndefined; - function last(array) { - Debug.assert(array.length !== 0); - return array[array.length - 1]; - } - ts.last = last; - /** - * Returns the only element of an array if it contains only one element, `undefined` otherwise. - */ - function singleOrUndefined(array) { - return array && array.length === 1 - ? array[0] - : undefined; - } - ts.singleOrUndefined = singleOrUndefined; - function singleOrMany(array) { - return array && array.length === 1 - ? array[0] - : array; - } - ts.singleOrMany = singleOrMany; - function replaceElement(array, index, value) { - var result = array.slice(0); - result[index] = value; - return result; - } - ts.replaceElement = replaceElement; - /** - * Performs a binary search, finding the index at which `value` occurs in `array`. - * If no such index is found, returns the 2's-complement of first index at which - * `array[index]` exceeds `value`. - * @param array A sorted array whose first element must be no larger than number - * @param value The value to be searched for in the array. - * @param keySelector A callback used to select the search key from `value` and each element of - * `array`. - * @param keyComparer A callback used to compare two keys in a sorted array. - * @param offset An offset into `array` at which to start the search. - */ - function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { - return -1; - } - var low = offset || 0; - var high = array.length - 1; - var key = keySelector(value); - while (low <= high) { - var middle = low + ((high - low) >> 1); - var midKey = keySelector(array[middle]); - switch (keyComparer(midKey, key)) { - case -1 /* LessThan */: - low = middle + 1; - break; - case 0 /* EqualTo */: - return middle; - case 1 /* GreaterThan */: - high = middle - 1; - break; - } - } - return ~low; - } - ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial, start, count) { - if (array && array.length > 0) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start < 0 ? 0 : start; - var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos++; - } - else { - result = initial; - } - while (pos <= end) { - result = f(result, array[pos], pos); - pos++; - } - return result; - } - } - return initial; - } - ts.reduceLeft = reduceLeft; - var hasOwnProperty = Object.prototype.hasOwnProperty; - /** - * Indicates whether a map-like contains an own property with the specified key. - * - * @param map A map-like. - * @param key A property key. - */ - function hasProperty(map, key) { - return hasOwnProperty.call(map, key); - } - ts.hasProperty = hasProperty; - /** - * Gets the value of an owned property in a map-like. - * - * @param map A map-like. - * @param key A property key. - */ - function getProperty(map, key) { - return hasOwnProperty.call(map, key) ? map[key] : undefined; - } - ts.getProperty = getProperty; - /** - * Gets the owned, enumerable property keys of a map-like. - */ - function getOwnKeys(map) { - var keys = []; - for (var key in map) { - if (hasOwnProperty.call(map, key)) { - keys.push(key); - } - } - return keys; - } - ts.getOwnKeys = getOwnKeys; - function getOwnValues(sparseArray) { - var values = []; - for (var key in sparseArray) { - if (hasOwnProperty.call(sparseArray, key)) { - values.push(sparseArray[key]); - } - } - return values; - } - ts.getOwnValues = getOwnValues; - function arrayFrom(iterator, map) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(map ? map(value) : value); - } - return result; - var _b; - } - ts.arrayFrom = arrayFrom; - function forEachEntry(map, callback) { - var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { - var key = pair[0], value = pair[1]; - var result = callback(value, key); - if (result) { - return result; - } - } - return undefined; - var _b; - } - ts.forEachEntry = forEachEntry; - function forEachKey(map, callback) { - var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { - var result = callback(key); - if (result) { - return result; - } - } - return undefined; - var _b; - } - ts.forEachKey = forEachKey; - function copyEntries(source, target) { - source.forEach(function (value, key) { - target.set(key, value); - }); - } - ts.copyEntries = copyEntries; - function assign(t) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { - var arg = args_1[_a]; - for (var p in arg) { - if (hasProperty(arg, p)) { - t[p] = arg[p]; - } - } - } - return t; - } - ts.assign = assign; - /** - * Performs a shallow equality comparison of the contents of two map-likes. - * - * @param left A map-like whose properties should be compared. - * @param right A map-like whose properties should be compared. - */ - function equalOwnProperties(left, right, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) { - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (!equalityComparer(left[key], right[key])) - return false; - } - } - for (var key in right) { - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } - } - return true; - } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = createMap(); - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var value = array_6[_i]; - result.set(makeKey(value), makeValue(value)); - } - return result; - } - ts.arrayToMap = arrayToMap; - function arrayToNumericMap(array, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = []; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; - result[makeKey(value)] = makeValue(value); - } - return result; - } - ts.arrayToNumericMap = arrayToNumericMap; - function arrayToSet(array, makeKey) { - return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); - } - ts.arrayToSet = arrayToSet; - function arrayToMultiMap(values, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - result.add(makeKey(value), makeValue(value)); - } - return result; - } - ts.arrayToMultiMap = arrayToMultiMap; - function group(values, getGroupId) { - return arrayFrom(arrayToMultiMap(values, getGroupId).values()); - } - ts.group = group; - function cloneMap(map) { - var clone = createMap(); - copyEntries(map, clone); - return clone; - } - ts.cloneMap = cloneMap; - function clone(object) { - var result = {}; - for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } - } - return result; - } - ts.clone = clone; - function extend(first, second) { - var result = {}; - for (var id in second) { - if (hasOwnProperty.call(second, id)) { - result[id] = second[id]; - } - } - for (var id in first) { - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } - } - return result; - } - ts.extend = extend; - function createMultiMap() { - var map = createMap(); - map.add = multiMapAdd; - map.remove = multiMapRemove; - return map; - } - ts.createMultiMap = createMultiMap; - function multiMapAdd(key, value) { - var values = this.get(key); - if (values) { - values.push(value); - } - else { - this.set(key, values = [value]); - } - return values; - } - function multiMapRemove(key, value) { - var values = this.get(key); - if (values) { - unorderedRemoveItem(values, value); - if (!values.length) { - this.delete(key); - } - } - } - /** - * Tests whether a value is an array. - */ - function isArray(value) { - return Array.isArray ? Array.isArray(value) : value instanceof Array; - } - ts.isArray = isArray; - function toArray(value) { - return isArray(value) ? value : [value]; - } - ts.toArray = toArray; - /** - * Tests whether a value is string - */ - function isString(text) { - return typeof text === "string"; - } - ts.isString = isString; - function tryCast(value, test) { - return value !== undefined && test(value) ? value : undefined; - } - ts.tryCast = tryCast; - function cast(value, test) { - if (value !== undefined && test(value)) - return value; - if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); - } - else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); - } - } - ts.cast = cast; - /** Does nothing. */ - function noop(_) { } // tslint:disable-line no-empty - ts.noop = noop; - /** Do nothing and return false */ - function returnFalse() { return false; } - ts.returnFalse = returnFalse; - /** Do nothing and return true */ - function returnTrue() { return true; } - ts.returnTrue = returnTrue; - /** Returns its argument. */ - function identity(x) { return x; } - ts.identity = identity; - /** Returns lower case string */ - function toLowerCase(x) { return x.toLowerCase(); } - ts.toLowerCase = toLowerCase; - /** Throws an error because a function is not implemented. */ - function notImplemented() { - throw new Error("Not implemented"); - } - ts.notImplemented = notImplemented; - function memoize(callback) { - var value; - return function () { - if (callback) { - value = callback(); - callback = undefined; - } - return value; - }; - } - ts.memoize = memoize; - function chain(a, b, c, d, e) { - if (e) { - var args_2 = []; - for (var i = 0; i < arguments.length; i++) { - args_2[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (_) { return function (u) { return u; }; }; - } - } - ts.chain = chain; - function compose(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } - ts.compose = compose; - function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); - } - ts.formatStringFromArgs = formatStringFromArgs; - function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; - } - ts.getLocaleSpecificMessage = getLocaleSpecificMessage; - function createFileDiagnostic(file, start, length, message) { - Debug.assertGreaterThanOrEqual(start, 0); - Debug.assertGreaterThanOrEqual(length, 0); - if (file) { - Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(start + length, file.text.length); - } - var text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); - } - return { - file: file, - start: start, - length: length, - messageText: text, - category: message.category, - code: message.code, - }; - } - ts.createFileDiagnostic = createFileDiagnostic; - /* internal */ - function formatMessage(_dummy, message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); - } - return text; - } - ts.formatMessage = formatMessage; - function createCompilerDiagnostic(message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); - } - return { - file: undefined, - start: undefined, - length: undefined, - messageText: text, - category: message.category, - code: message.code - }; - } - ts.createCompilerDiagnostic = createCompilerDiagnostic; - function createCompilerDiagnosticFromMessageChain(chain) { - return { - file: undefined, - start: undefined, - length: undefined, - code: chain.code, - category: chain.category, - messageText: chain.next ? chain : chain.messageText - }; - } - ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; - function chainDiagnosticMessages(details, message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); - } - return { - messageText: text, - category: message.category, - code: message.code, - next: details - }; - } - ts.chainDiagnosticMessages = chainDiagnosticMessages; - function concatenateDiagnosticMessageChains(headChain, tailChain) { - var lastChain = headChain; - while (lastChain.next) { - lastChain = lastChain.next; - } - lastChain.next = tailChain; - return headChain; - } - ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; - function equateValues(a, b) { - return a === b; - } - ts.equateValues = equateValues; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function equateStringsCaseInsensitive(a, b) { - return a === b - || a !== undefined - && b !== undefined - && a.toUpperCase() === b.toUpperCase(); - } - ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the - * integer value of each code-point. - */ - function equateStringsCaseSensitive(a, b) { - return equateValues(a, b); - } - ts.equateStringsCaseSensitive = equateStringsCaseSensitive; - function compareComparableValues(a, b) { - return a === b ? 0 /* EqualTo */ : - a === undefined ? -1 /* LessThan */ : - b === undefined ? 1 /* GreaterThan */ : - a < b ? -1 /* LessThan */ : - 1 /* GreaterThan */; - } - /** - * Compare two numeric values for their order relative to each other. - * To compare strings, use any of the `compareStrings` functions. - */ - function compareValues(a, b) { - return compareComparableValues(a, b); - } - ts.compareValues = compareValues; - /** - * Compare two strings using a case-insensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-insensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function compareStringsCaseInsensitive(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - a = a.toUpperCase(); - b = b.toUpperCase(); - return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; - /** - * Compare two strings using a case-sensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point. - */ - function compareStringsCaseSensitive(a, b) { - return compareComparableValues(a, b); - } - ts.compareStringsCaseSensitive = compareStringsCaseSensitive; - /** - * Creates a string comparer for use with string collation in the UI. - */ - var createUIStringComparer = (function () { - var defaultComparer; - var enUSComparer; - var stringComparerFactory = getStringComparerFactory(); - return createStringComparer; - function compareWithCallback(a, b, comparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - var value = comparer(a, b); - return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - function createIntlCollatorStringComparer(locale) { - // Intl.Collator.prototype.compare is bound to the collator. See NOTE in - // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare - var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; - return function (a, b) { return compareWithCallback(a, b, comparer); }; - } - function createLocaleCompareStringComparer(locale) { - // if the locale is not the default locale (`undefined`), use the fallback comparer. - if (locale !== undefined) - return createFallbackStringComparer(); - return function (a, b) { return compareWithCallback(a, b, compareStrings); }; - function compareStrings(a, b) { - return a.localeCompare(b); - } - } - function createFallbackStringComparer() { - // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". - // We first sort case insensitively. So "Aaa" will come before "baa". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - // - // For case insensitive comparisons we always map both strings to their - // upper-case form as some unicode characters do not properly round-trip to - // lowercase (such as `ẞ` (German sharp capital s)). - return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; - function compareDictionaryOrder(a, b) { - return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); - } - function compareStrings(a, b) { - return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - } - function getStringComparerFactory() { - // If the host supports Intl, we use it for comparisons using the default locale. - if (typeof Intl === "object" && typeof Intl.Collator === "function") { - return createIntlCollatorStringComparer; - } - // If the host does not support Intl, we fall back to localeCompare. - // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. - if (typeof String.prototype.localeCompare === "function" && - typeof String.prototype.toLocaleUpperCase === "function" && - "a".localeCompare("B") < 0) { - return createLocaleCompareStringComparer; - } - // Otherwise, fall back to ordinal comparison: - return createFallbackStringComparer; - } - function createStringComparer(locale) { - // Hold onto common string comparers. This avoids constantly reallocating comparers during - // tests. - if (locale === undefined) { - return defaultComparer || (defaultComparer = stringComparerFactory(locale)); - } - else if (locale === "en-US") { - return enUSComparer || (enUSComparer = stringComparerFactory(locale)); - } - else { - return stringComparerFactory(locale); - } - } - })(); - var uiComparerCaseSensitive; - var uiLocale; - function getUILocale() { - return uiLocale; - } - ts.getUILocale = getUILocale; - function setUILocale(value) { - if (uiLocale !== value) { - uiLocale = value; - uiComparerCaseSensitive = undefined; - } - } - ts.setUILocale = setUILocale; - /** - * Compare two strings in a using the case-sensitive sort behavior of the UI locale. - * - * Ordering is not predictable between different host locales, but is best for displaying - * ordered data for UI presentation. Characters with multiple unicode representations may - * be considered equal. - * - * Case-sensitive comparisons compare strings that differ in base characters, or - * accents/diacritic marks, or case as unequal. - */ - function compareStringsCaseSensitiveUI(a, b) { - var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); - return comparer(a, b); - } - ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; - function compareProperties(a, b, key, comparer) { - return a === b ? 0 /* EqualTo */ : - a === undefined ? -1 /* LessThan */ : - b === undefined ? 1 /* GreaterThan */ : - comparer(a[key], b[key]); - } - ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; - } - function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || - compareValues(d1.start, d2.start) || - compareValues(d1.length, d2.length) || - compareValues(d1.code, d2.code) || - compareMessageText(d1.messageText, d2.messageText) || - 0 /* EqualTo */; - } - ts.compareDiagnostics = compareDiagnostics; - /** True is greater than false. */ - function compareBooleans(a, b) { - return compareValues(a ? 1 : 0, b ? 1 : 0); - } - ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { - while (text1 && text2) { - // We still have both chains. - var string1 = isString(text1) ? text1 : text1.messageText; - var string2 = isString(text2) ? text2 : text2.messageText; - var res = compareStringsCaseSensitive(string1, string2); - if (res) { - return res; - } - text1 = isString(text1) ? undefined : text1.next; - text2 = isString(text2) ? undefined : text2.next; - } - if (!text1 && !text2) { - // if the chains are done, then these messages are the same. - return 0 /* EqualTo */; - } - // We still have one chain remaining. The shorter chain should come first. - return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; - } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") - */ - function getRootLength(path) { - if (path.charCodeAt(0) === 47 /* slash */) { - if (path.charCodeAt(1) !== 47 /* slash */) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) - return 3; - } - // Per RFC 1738 'file' URI schema has the shape file:/// - // if is omitted then it is assumed that host value is 'localhost', - // however slash after the omitted is not removed. - // file:///folder1/file1 - this is a correct URI - // file://folder2/file2 - this is an incorrect URI - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47 /* slash */; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, - // e.g. "path//file.ts". Drop these before re-joining the parts. - if (part) { - normalized.push(part); - } - } - } - } - 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 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 { path: root, parts: parts }; - } - } - 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; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - function getEmitModuleResolutionKind(compilerOptions) { - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - } - return moduleResolution; - } - ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; - function getAllowSyntheticDefaultImports(compilerOptions) { - var moduleKind = getEmitModuleKind(compilerOptions); - return compilerOptions.allowSyntheticDefaultImports !== undefined - ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; - } - ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; - function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; - } - ts.getStrictOptionValue = getStrictOptionValue; - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); - } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - if (rootLength === 0) { - // If the path is not rooted it is relative to current directory - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); - } - return normalizedPathComponents(path, rootLength); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } - } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ - // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; - // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol - // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// - if (url.charCodeAt(rootLength) === 47 /* slash */) { - rootLength++; - } - else { - // non slash character means we continue proceeding to next component of root search - break; - } - } - // there are no parts after http:// just return current string as the pathComponent - if (rootLength === urlLength) { - return [url]; - } - // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components after the root normally like any other folder components - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] - // so that other path manipulations will be correct and it can be merged with relative paths correctly - return [url + ts.directorySeparator]; - } - } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } - } - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.pop(); - } - // Find the component that differs - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - // Get the relative path - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); - } - ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; - } - ts.combinePaths = combinePaths; - function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - /** - * Adds a trailing directory separator to a path, if it does not already have one. - * @param path The path. - */ - function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); - var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; - for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; - } - } - return compareValues(aComponents.length, bComponents.length); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); - if (childComponents.length < parentComponents.length) { - return false; - } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - function removePrefix(str, prefix) { - return startsWith(str, prefix) ? str.substr(prefix.length) : str; - } - ts.removePrefix = removePrefix; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; - function removeSuffix(str, suffix) { - return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; - } - ts.removeSuffix = removeSuffix; - function stringContains(str, substring) { - return str.indexOf(substring) !== -1; - } - ts.stringContains = stringContains; - function hasExtension(fileName) { - return stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; - // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. - // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future - // proof. - var reservedCharacterPattern = /[^\w\s\/]/g; - var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - 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) { - return undefined; - } - var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); - // If excluding, match "foo/bar/baz...", but if including, only allow "foo". - var terminator = usage === "exclude" ? "($|/)" : "$"; - return "^(" + pattern + ")" + terminator; - } - ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function getRegularExpressionsForWildcards(specs, basePath, usage) { - if (specs === undefined || specs.length === 0) { - return undefined; - } - return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); - }); - } - /** - * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, - * and does not contain any glob characters itself. - */ - function isImplicitGlob(lastPathComponent) { - return !/[.*?]/.test(lastPathComponent); - } - ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, _a) { - var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; - var subpattern = ""; - var hasWrittenComponent = false; - var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); - if (usage !== "exclude" && lastComponent === "**") { - return undefined; - } - // getNormalizedPathComponents includes the separator for the root component. - // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); - if (isImplicitGlob(lastComponent)) { - components.push("**", "*"); - } - var optionalCount = 0; - for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { - var component = components_1[_i]; - if (component === "**") { - subpattern += doubleAsteriskRegexFragment; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - 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 */) { - componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - 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); - } - } - hasWrittenComponent = true; - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; - } - return subpattern; - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; - } - function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); - return { - includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), - includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), - includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), - excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) - }; - } - ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); - var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); - // Associate an array of results with each include regex. This keeps results in order of the "include" order. - // If there are no "includes", then just put everything in results[0]. - var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { - var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); - } - return flatten(results); - function visitDirectory(path, absolutePath, depth) { - var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name, extensions)) - return "continue"; - if (excludeRegex && excludeRegex.test(absoluteName)) - return "continue"; - if (!includeFileRegexes) { - results[0].push(name); - } - else { - var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); - if (includeIndex !== -1) { - results[includeIndex].push(name); - } - } - }; - for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { - var current = _b[_i]; - _loop_1(current); - } - if (depth !== undefined) { - depth--; - if (depth === 0) { - return; - } - } - for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { - var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); - if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && - (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName, depth); - } - } - } - } - ts.matchFiles = matchFiles; - /** - * Computes the unique non-wildcard base paths amongst the provided include patterns. - */ - function getBasePaths(path, includes, useCaseSensitiveFileNames) { - // Storage for our results in the form of literal paths (e.g. the paths as written by the user). - var basePaths = [path]; - if (includes) { - // Storage for literal base paths amongst the include patterns. - var includeBasePaths = []; - for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { - var include = includes_1[_i]; - // We also need to check the relative paths by converting them to absolute and normalizing - // in case they escape the base path (e.g "..\somedirectory") - var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - // Append the literal and canonical candidate base paths. - includeBasePaths.push(getIncludeBasePath(absolute)); - } - // Sort the offsets array using either the literal or canonical path representations. - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); - var _loop_2 = function (includeBasePath) { - if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { - basePaths.push(includeBasePath); - } - }; - // Iterate over each include base path and include unique base paths that are not a - // subpath of an existing base path - for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { - var includeBasePath = includeBasePaths_1[_a]; - _loop_2(includeBasePath); - } - } - return basePaths; - } - function getIncludeBasePath(absolute) { - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - if (wildcardOffset < 0) { - // No "*" or "?" in the path - return !hasExtension(absolute) - ? absolute - : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); - } - return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - } - function ensureScriptKind(fileName, scriptKind) { - // Using scriptKind as a condition handles both: - // - 'scriptKind' is unspecified and thus it is `undefined` - // - 'scriptKind' is set and it is `Unknown` (0) - // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt - // to get the ScriptKind from the file name. If it cannot be resolved - // from the file name then the default 'TS' script kind is returned. - return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; - } - ts.ensureScriptKind = ensureScriptKind; - function getScriptKindFromFileName(fileName) { - var ext = fileName.substr(fileName.lastIndexOf(".")); - switch (ext.toLowerCase()) { - case ".js" /* Js */: - return 1 /* JS */; - case ".jsx" /* Jsx */: - return 2 /* JSX */; - case ".ts" /* Ts */: - return 3 /* TS */; - case ".tsx" /* Tsx */: - return 4 /* TSX */; - case ".json" /* Json */: - return 6 /* JSON */; - default: - return 0 /* Unknown */; - } - } - ts.getScriptKindFromFileName = getScriptKindFromFileName; - /** - * List of supported extensions in order of file resolution precedence. - */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; - /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; - } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); - } - ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { - if (!fileName) { - return false; - } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { - var extension = _a[_i]; - if (fileExtensionIs(fileName, extension)) { - return true; - } - } - return false; - } - ts.isSupportedSourceFileName = isSupportedSourceFileName; - /** - * Extension boundaries by priority. Lower numbers indicate higher priorities, and are - * aligned to the offset of the highest priority extension in the - * allSupportedExtensions array. - */ - 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])) { - return adjustExtensionPriority(i, supportedExtensions); - } - } - // If its not in the list of supported extensions, this is likely a - // TypeScript file with a non-ts extension - return 0 /* Highest */; - } - ts.getExtensionPriority = getExtensionPriority; - /** - * Adjusts an extension priority to be the highest priority within the same range. - */ - function adjustExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { - return 0 /* TypeScriptFiles */; - } - else if (extensionPriority < supportedExtensions.length) { - return 2 /* DeclarationAndJavaScriptFiles */; - } - else { - return supportedExtensions.length; - } - } - ts.adjustExtensionPriority = adjustExtensionPriority; - /** - * Gets the next lowest extension priority for a given priority. - */ - function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { - return 2 /* DeclarationAndJavaScriptFiles */; - } - else { - return supportedExtensions.length; - } - } - ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; - function removeFileExtension(path) { - for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { - var ext = extensionsToRemove_1[_i]; - var extensionless = tryRemoveExtension(path, ext); - if (extensionless !== undefined) { - return extensionless; - } - } - return path; - } - ts.removeFileExtension = removeFileExtension; - function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; - } - ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; - function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); - } - ts.changeExtension = changeExtension; - /** - * Takes a string like "jquery-min.4.2.3" and returns "jquery" - */ - function removeMinAndVersionNumbers(fileName) { - // Match a "." or "-" followed by a version number or 'min' at the end of the name - var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; - // The "min" or version may both be present, in either order, so try applying the above twice. - return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); - } - ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; - function Symbol(flags, name) { - this.flags = flags; - this.escapedName = name; - this.declarations = undefined; - this.valueDeclaration = undefined; - this.id = undefined; - this.mergeId = undefined; - this.parent = undefined; - } - function Type(checker, flags) { - this.flags = flags; - if (Debug.isDebugging) { - this.checker = checker; - } - } - function Signature() { } // tslint:disable-line no-empty - function Node(kind, pos, end) { - this.pos = pos; - this.end = end; - this.kind = kind; - this.id = 0; - this.flags = 0 /* None */; - this.modifierFlagsCache = 0 /* None */; - this.transformFlags = 0 /* None */; - this.parent = undefined; - this.original = undefined; - } - function SourceMapSource(fileName, text, skipTrivia) { - this.fileName = fileName; - this.text = text; - this.skipTrivia = skipTrivia || (function (pos) { return pos; }); - } - ts.objectAllocator = { - getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, - getSourceFileConstructor: function () { return Node; }, - getSymbolConstructor: function () { return Symbol; }, - getTypeConstructor: function () { return Type; }, - 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 /* None */; - Debug.isDebugging = false; - function shouldAssert(level) { - return Debug.currentAssertionLevel >= level; - } - Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo, stackCrawlMark) { - if (!expression) { - if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); - } - fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); - } - } - 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."); - if (Error.captureStackTrace) { - Error.captureStackTrace(e, stackCrawlMark || fail); - } - throw e; - } - Debug.fail = fail; - function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); - return value; - } - Debug.assertDefined = assertDefined; - function assertEachDefined(value, message) { - for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { - var v = value_1[_i]; - assertDefined(v, message); - } - return value; - } - Debug.assertEachDefined = assertEachDefined; - function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); - } - Debug.assertNever = assertNever; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; - } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; - } - } - Debug.getFunctionName = getFunctionName; - function showSymbol(symbol) { - var symbolFlags = ts.SymbolFlags; - return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + map(symbol.declarations, showSyntaxKind) + " }"; - } - Debug.showSymbol = showSymbol; - function showFlags(flags, flagsEnum) { - var out = []; - for (var pow = 0; pow <= 30; pow++) { - var n = 1 << pow; - if (flags & n) { - out.push(flagsEnum[n]); - } - } - return out.join("|"); - } - function showSyntaxKind(node) { - var syntaxKind = ts.SyntaxKind; - return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); - } - Debug.showSyntaxKind = showSyntaxKind; - })(Debug = ts.Debug || (ts.Debug = {})); - /** Remove an item from an array, moving everything to its right one space left. */ - function orderedRemoveItem(array, item) { - for (var i = 0; i < array.length; i++) { - if (array[i] === item) { - orderedRemoveItemAt(array, i); - return true; - } - } - return false; - } - ts.orderedRemoveItem = orderedRemoveItem; - /** Remove an item by index from an array, moving everything to its right one space left. */ - function orderedRemoveItemAt(array, index) { - // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. - for (var i = index; i < array.length - 1; i++) { - array[i] = array[i + 1]; - } - array.pop(); - } - ts.orderedRemoveItemAt = orderedRemoveItemAt; - function unorderedRemoveItemAt(array, index) { - // Fill in the "hole" left at `index`. - array[index] = array[array.length - 1]; - array.pop(); - } - ts.unorderedRemoveItemAt = unorderedRemoveItemAt; - /** Remove the *first* occurrence of `item` from the array. */ - function unorderedRemoveItem(array, item) { - unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); - } - ts.unorderedRemoveItem = unorderedRemoveItem; - /** Remove the *first* element satisfying `predicate`. */ - function unorderedRemoveFirstItemWhere(array, predicate) { - for (var i = 0; i < array.length; i++) { - if (predicate(array[i])) { - unorderedRemoveItemAt(array, i); - break; - } - } - } - function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toLowerCase; - } - ts.createGetCanonicalFileName = createGetCanonicalFileName; - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - ts.matchPatternOrExact = matchPatternOrExact; - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - ts.patternText = patternText; - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - ts.matchedText = matchedText; - /** Return the object corresponding to the best pattern to match `candidate`. */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { - var v = values_2[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - startsWith(candidate, prefix) && - endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { - return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; - } - ts.extensionIsTypeScript = extensionIsTypeScript; - /** - * Gets the extension from a path. - * Path must have a valid extension. - */ - function extensionFromPath(path) { - var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - 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); }); - } - ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - function getAnyExtensionFromPath(path) { - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; - function isCheckJsEnabledForFile(sourceFile, compilerOptions) { - return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; - } - ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; - function and(f, g) { - return function (arg) { return f(arg) && g(arg); }; - } - ts.and = and; - function or(f, g) { - return function (arg) { return f(arg) || g(arg); }; - } - ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; - ts.emptyFileSystemEntries = { - files: ts.emptyArray, - directories: ts.emptyArray - }; - function singleElementArray(t) { - return t === undefined ? undefined : [t]; - } - ts.singleElementArray = singleElementArray; - function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { - unchanged = unchanged || noop; - 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 = comparer(newItem, oldItem); - if (compareResult === -1 /* LessThan */) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1 /* GreaterThan */) { - deleted(oldItem); - oldIndex++; - } - else { - unchanged(oldItem, newItem); - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; -})(ts || (ts = {})); -/// var ts; (function (ts) { /** @@ -4546,12 +3578,12 @@ var ts; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4778,47 +3810,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; - ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -4845,6 +3910,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. // MONACOCHANGE ts.sys = undefined; // END MONACOCHANGE @@ -4859,13 +3925,12 @@ var ts; } })(ts || (ts = {})); // -// generated from './diagnosticInformationMap.generated.ts' by '../../scripts/processDiagnosticMessages.js' -/// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ var ts; (function (ts) { - function diag(code, category, key, message) { - return { code: code, category: category, key: key, message: message }; + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; } // tslint:disable-next-line variable-name ts.Diagnostics = { @@ -4875,7 +3940,9 @@ var ts; A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), @@ -4922,6 +3989,7 @@ var ts; The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), @@ -4958,7 +4026,6 @@ var ts; An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), - A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), @@ -5078,6 +4145,8 @@ var ts; _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), @@ -5091,7 +4160,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5107,6 +4176,10 @@ var ts; An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5174,6 +4247,7 @@ var ts; The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), @@ -5212,7 +4286,7 @@ var ts; The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), @@ -5223,6 +4297,7 @@ var ts; Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), @@ -5286,7 +4361,7 @@ var ts; The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), @@ -5302,7 +4377,7 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), @@ -5366,6 +4441,14 @@ var ts; Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), 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."), @@ -5419,7 +4502,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -5449,6 +4532,11 @@ var ts; Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5560,6 +4648,10 @@ var ts; Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -5595,7 +4687,6 @@ var ts; DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), - Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), @@ -5680,12 +4771,12 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), @@ -5738,7 +4829,51 @@ var ts; Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), - All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5757,8 +4892,8 @@ var ts; 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), - Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), @@ -5768,8 +4903,9 @@ var ts; Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5799,6 +4935,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5828,6 +4965,7 @@ var ts; This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5835,7 +4973,9 @@ var ts; Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5872,10 +5012,51 @@ var ts; Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), }; })(ts || (ts = {})); -/// -/// var ts; (function (ts) { /* @internal */ @@ -5912,7 +5093,7 @@ var ts; "false": 86 /* FalseKeyword */, "finally": 87 /* FinallyKeyword */, "for": 88 /* ForKeyword */, - "from": 142 /* FromKeyword */, + "from": 143 /* FromKeyword */, "function": 89 /* FunctionKeyword */, "get": 125 /* GetKeyword */, "if": 90 /* IfKeyword */, @@ -5938,7 +5119,7 @@ var ts; "public": 114 /* PublicKeyword */, "readonly": 132 /* ReadonlyKeyword */, "require": 133 /* RequireKeyword */, - "global": 143 /* GlobalKeyword */, + "global": 144 /* GlobalKeyword */, "return": 96 /* ReturnKeyword */, "set": 136 /* SetKeyword */, "static": 115 /* StaticKeyword */, @@ -5954,6 +5135,7 @@ var ts; "typeof": 103 /* TypeOfKeyword */, "undefined": 140 /* UndefinedKeyword */, "unique": 141 /* UniqueKeyword */, + "unknown": 142 /* UnknownKeyword */, "var": 104 /* VarKeyword */, "void": 105 /* VoidKeyword */, "while": 106 /* WhileKeyword */, @@ -5961,7 +5143,7 @@ var ts; "yield": 116 /* YieldKeyword */, "async": 120 /* AsyncKeyword */, "await": 121 /* AwaitKeyword */, - "of": 144 /* OfKeyword */, + "of": 145 /* OfKeyword */, "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, @@ -6489,7 +5671,6 @@ var ts; // If we are not reducing and we have a truthy result, return it. return accumulator; } - hasPendingCommentRange = false; } pendingPos = startPos; pendingEnd = pos; @@ -6581,8 +5762,9 @@ var ts; } ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; // Current position (end position of text of current token) var pos; // end of text @@ -7038,7 +6220,7 @@ var ts; var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); - // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -7625,11 +6807,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -7664,6 +6845,13 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: return token = 23 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { @@ -7750,14 +6938,29 @@ var ts; } ts.createScanner = createScanner; })(ts || (ts = {})); -/// -/* @internal */ +/** Non-internal stuff goes here */ var ts; (function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7771,6 +6974,26 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; var stringWriter = createSingleLineStringWriter(); function createSingleLineStringWriter() { var str = ""; @@ -7806,6 +7029,87 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function usingSingleLineStringWriter(action) { var oldString = stringWriter.getText(); try { @@ -7849,7 +7153,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -7900,7 +7204,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 272 /* SourceFile */) { + while (node && node.kind !== 277 /* SourceFile */) { node = node.parent; } return node; @@ -7908,11 +7212,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 211 /* Block */: - case 239 /* CaseBlock */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return true; } return false; @@ -7956,6 +7260,14 @@ var ts; } } ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; // Returns true if this node is missing from the actual source code. A 'missing' node is different // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes // in the tree), it is definitely missing. However, a node may be defined, but still be @@ -7979,6 +7291,23 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -8000,9 +7329,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -8021,7 +7350,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 293 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8068,7 +7397,7 @@ var ts; */ function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -8102,7 +7431,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -8114,14 +7443,6 @@ var ts; return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); } ts.escapeLeadingUnderscores = escapeLeadingUnderscores; - /** - * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. - * @param identifier The identifier to escape - */ - function escapeIdentifier(identifier) { - return identifier; - } - ts.escapeIdentifier = escapeIdentifier; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8135,7 +7456,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 230 /* VariableDeclaration */ && node.parent.kind === 267 /* CatchClause */; + return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -8150,6 +7471,16 @@ var ts; return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; /** Given a symbol for a module, checks that it is a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -8157,11 +7488,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 237 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 272 /* SourceFile */ || - node.kind === 237 /* ModuleDeclaration */ || + return node.kind === 277 /* SourceFile */ || + node.kind === 242 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8178,9 +7509,9 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node.parent); - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8192,50 +7523,53 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 272 /* SourceFile */: - case 239 /* CaseBlock */: - case 267 /* CatchClause */: - case 237 /* ModuleDeclaration */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 272 /* CatchClause */: + case 242 /* ModuleDeclaration */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; - case 211 /* Block */: + case 216 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 280 /* JSDocFunctionType */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 290 /* JSDocTemplateTag */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 287 /* JSDocFunctionType */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 300 /* JSDocTemplateTag */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: return true; default: ts.assertTypeIsNever(node); @@ -8245,31 +7579,46 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isAnyImportSyntax(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: return true; default: return false; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 217 /* VariableStatement */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. function declarationNameToString(name) { - return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; function getNameFromIndexInfo(info) { @@ -8283,8 +7632,8 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); - case 146 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + case 147 /* ComputedPropertyName */: + return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: ts.Debug.assertNever(name); } @@ -8294,10 +7643,12 @@ var ts; switch (name.kind) { case 71 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -8316,12 +7667,7 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; - function createDiagnosticForNodeFromMessageChain(node, messageChain) { + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); return { @@ -8330,7 +7676,8 @@ var ts; length: span.length, code: messageChain.code, category: messageChain.category, - messageText: messageChain.next ? messageChain : messageChain.messageText + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation }; } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; @@ -8343,7 +7690,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 211 /* Block */) { + if (node.body && node.body.kind === 216 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8357,7 +7704,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -8366,23 +7713,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 235 /* TypeAliasDeclaration */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 240 /* TypeAliasDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: errorNode = node.name; break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8410,29 +7759,36 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isConstEnumDeclaration(node) { - return node.kind === 236 /* EnumDeclaration */ && isConst(node); + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; } - ts.isConstEnumDeclaration = isConstEnumDeclaration; - function isConst(node) { - return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) - || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } - ts.isConst = isConst; + ts.isEnumConst = isEnumConst; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; function isLet(node) { return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 185 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 185 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 214 /* ExpressionStatement */ + return node.kind === 219 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -8441,11 +7797,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 148 /* Parameter */ || - node.kind === 147 /* TypeParameter */ || - node.kind === 190 /* FunctionExpression */ || - node.kind === 191 /* ArrowFunction */ || - node.kind === 189 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 149 /* Parameter */ || + node.kind === 148 /* TypeParameter */ || + node.kind === 194 /* FunctionExpression */ || + node.kind === 195 /* ArrowFunction */ || + node.kind === 193 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8461,11 +7817,12 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (160 /* FirstTypeNode */ <= node.kind && node.kind <= 177 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { return true; } switch (node.kind) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 134 /* NumberKeyword */: case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: @@ -8474,72 +7831,76 @@ var ts; case 131 /* NeverKeyword */: return true; case 105 /* VoidKeyword */: - return node.parent.kind !== 194 /* VoidExpression */; - case 205 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 198 /* VoidExpression */; + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 147 /* TypeParameter */: - return node.parent.kind === 176 /* MappedType */ || node.parent.kind === 171 /* InferType */; + case 148 /* TypeParameter */: + return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 71 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 145 /* QualifiedName */ || node.kind === 183 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 145 /* QualifiedName */: - case 183 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: + case 146 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 164 /* TypeQuery */) { + if (parent.kind === 165 /* TypeQuery */) { return false; } + if (parent.kind === 181 /* ImportType */) { + return !parent.isTypeOf; + } // Do not recursively call isPartOfTypeNode on the parent. In the example: // // let a: A.B.C; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (160 /* FirstTypeNode */ <= parent.kind && parent.kind <= 177 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return node === parent.constraint; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 148 /* Parameter */: - case 230 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return node === parent.type; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return node === parent.type; - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return node === parent.type; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return node === parent.type; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } + } } return false; } @@ -8560,23 +7921,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitor(node); - case 239 /* CaseBlock */: - case 211 /* Block */: - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 224 /* WithStatement */: - case 225 /* SwitchStatement */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 226 /* LabeledStatement */: - case 228 /* TryStatement */: - case 267 /* CatchClause */: + case 244 /* CaseBlock */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8586,26 +7947,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 236 /* EnumDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -8628,10 +7989,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 166 /* ArrayType */) { + if (node && node.kind === 167 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 161 /* TypeReference */) { + else if (node && node.kind === 162 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8641,12 +8002,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 165 /* TypeLiteral */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 166 /* TypeLiteral */: return node.members; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return node.properties; } } @@ -8654,40 +8015,44 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 180 /* BindingElement */: - case 271 /* EnumMember */: - case 148 /* Parameter */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 269 /* ShorthandPropertyAssignment */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 276 /* EnumMember */: + case 149 /* Parameter */: + case 273 /* PropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 274 /* ShorthandPropertyAssignment */: + case 235 /* VariableDeclaration */: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 231 /* VariableDeclarationList */ - && node.parent.parent.kind === 212 /* VariableStatement */; + return node.parent.kind === 236 /* VariableDeclarationList */ + && node.parent.parent.kind === 217 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { - return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : ts.isPropertySignature(node) && hasReadonlyModifier(node); } ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return true; } return false; @@ -8698,7 +8063,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 226 /* LabeledStatement */) { + if (node.statement.kind !== 231 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8706,17 +8071,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 211 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 153 /* MethodDeclaration */ && node.parent.kind === 182 /* ObjectLiteralExpression */; + return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 153 /* MethodDeclaration */ && - (node.parent.kind === 182 /* ObjectLiteralExpression */ || - node.parent.kind === 203 /* ClassExpression */); + return node.kind === 154 /* MethodDeclaration */ && + (node.parent.kind === 186 /* ObjectLiteralExpression */ || + node.parent.kind === 207 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8728,30 +8093,52 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 268 /* PropertyAssignment */) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 273 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { - return ts.findAncestor(node.parent, ts.isFunctionLike); + return findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - return ts.findAncestor(node.parent, ts.isClassLike); + return findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 277 /* SourceFile */); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -8766,9 +8153,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 148 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8779,26 +8166,26 @@ var ts; node = node.parent; } break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 237 /* ModuleDeclaration */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 236 /* EnumDeclaration */: - case 272 /* SourceFile */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 242 /* ModuleDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 241 /* EnumDeclaration */: + case 277 /* SourceFile */: return node; } } @@ -8808,9 +8195,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return container; } } @@ -8832,27 +8219,27 @@ var ts; return node; } switch (node.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: node = node.parent; break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return node; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 148 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8868,14 +8255,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 190 /* FunctionExpression */ || func.kind === 191 /* ArrowFunction */) { + if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 189 /* ParenthesizedExpression */) { + while (parent.kind === 193 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 185 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8886,7 +8273,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 183 /* PropertyAccessExpression */ || kind === 184 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -8895,20 +8282,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 183 /* PropertyAccessExpression */ || kind === 184 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 99 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71 /* Identifier */: - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return node; } return undefined; @@ -8916,10 +8303,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return node.tag; - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8928,53 +8315,55 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // classes are valid targets return true; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 233 /* ClassDeclaration */; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: + return parent.kind === 238 /* ClassDeclaration */; + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 233 /* ClassDeclaration */; - case 148 /* Parameter */: + && parent.kind === 238 /* ClassDeclaration */; + case 149 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 154 /* Constructor */ - || parent.kind === 153 /* MethodDeclaration */ - || parent.kind === 156 /* SetAccessor */) - && grandparent.kind === 233 /* ClassDeclaration */; + && (parent.kind === 155 /* Constructor */ + || parent.kind === 154 /* MethodDeclaration */ + || parent.kind === 157 /* SetAccessor */) + && grandparent.kind === 238 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node, parent, grandparent); + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; function nodeOrChildIsDecorated(node, parent, grandparent) { - return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 233 /* ClassDeclaration */: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); - case 153 /* MethodDeclaration */: - case 156 /* SetAccessor */: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + case 238 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 154 /* MethodDeclaration */: + case 157 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 255 /* JsxOpeningElement */ || - parent.kind === 254 /* JsxSelfClosingElement */ || - parent.kind === 256 /* JsxClosingElement */) { + if (parent.kind === 260 /* JsxOpeningElement */ || + parent.kind === 259 /* JsxSelfClosingElement */ || + parent.kind === 261 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -8987,45 +8376,45 @@ var ts; case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 12 /* RegularExpressionLiteral */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 187 /* TaggedTemplateExpression */: - case 206 /* AsExpression */: - case 188 /* TypeAssertionExpression */: - case 207 /* NonNullExpression */: - case 189 /* ParenthesizedExpression */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: - case 191 /* ArrowFunction */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: - case 198 /* BinaryExpression */: - case 199 /* ConditionalExpression */: - case 202 /* SpreadElement */: - case 200 /* TemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: + case 210 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 211 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 206 /* SpreadElement */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* OmittedExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 201 /* YieldExpression */: - case 195 /* AwaitExpression */: - case 208 /* MetaProperty */: + case 208 /* OmittedExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 205 /* YieldExpression */: + case 199 /* AwaitExpression */: + case 212 /* MetaProperty */: return true; - case 145 /* QualifiedName */: - while (node.parent.kind === 145 /* QualifiedName */) { + case 146 /* QualifiedName */: + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 164 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); case 71 /* Identifier */: - if (node.parent.kind === 164 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -9041,47 +8430,47 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 271 /* EnumMember */: - case 268 /* PropertyAssignment */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 184 /* BindingElement */: return parent.initializer === node; - case 214 /* ExpressionStatement */: - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 223 /* ReturnStatement */: - case 224 /* WithStatement */: - case 225 /* SwitchStatement */: - case 264 /* CaseClause */: - case 227 /* ThrowStatement */: + case 219 /* ExpressionStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 228 /* ReturnStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 232 /* ThrowStatement */: return parent.expression === node; - case 218 /* ForStatement */: + case 223 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 231 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 231 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forInStatement.expression === node; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return node === parent.expression; - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return node === parent.expression; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return node === parent.expression; - case 149 /* Decorator */: - case 263 /* JsxExpression */: - case 262 /* JsxSpreadAttribute */: - case 270 /* SpreadAssignment */: + case 150 /* Decorator */: + case 268 /* JsxExpression */: + case 267 /* JsxSpreadAttribute */: + case 275 /* SpreadAssignment */: return true; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: return isExpressionNode(parent); @@ -9089,7 +8478,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 252 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9098,19 +8487,27 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 252 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536 /* JavaScriptFile */); + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 1048576 /* JSDoc */); + return !!node && !!(node.flags & 2097152 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -9121,8 +8518,8 @@ var ts; (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 185 /* CallExpression */) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 189 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -9133,7 +8530,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -9144,28 +8541,53 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - /** - * Given the symbol of a declaration, find the symbol of its Javascript container-like initializer, - * if it has one. Otherwise just return the original symbol. - * - * Container-like initializer behave like namespaces, so the binder needs to add contained symbols - * to their exports. An example is a function with assignments to `this` inside. - */ - function getJSInitializerSymbol(symbol) { - if (!symbol || !symbol.valueDeclaration) { - return symbol; + function getDeclarationOfJSInitializer(node) { + if (!isInJavaScriptFile(node) || !node.parent) { + return undefined; } - var declaration = symbol.valueDeclaration; - var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); - return e && e.symbol ? e.symbol : symbol; + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; } - ts.getJSInitializerSymbol = getJSInitializerSymbol; - /** Get the declaration initializer, when the initializer is container-like (See getJavascriptInitializer) */ - function getDeclaredJavascriptInitializer(node) { - if (node && ts.isVariableDeclaration(node) && node.initializer) { - return getJavascriptInitializer(node.initializer, /*isPrototypeAssignment*/ false) || - ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, /*isPrototypeAssignment*/ false); + ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJavaScriptFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ + function getDeclaredJavascriptInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); } ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** @@ -9174,7 +8596,7 @@ var ts; */ function getAssignedJavascriptInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { - var isPrototypeAssignment = ts.isPropertyAccessExpression(node.parent.left) && node.parent.left.name.escapedText === "prototype"; + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } @@ -9193,9 +8615,11 @@ var ts; function getJavascriptInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 190 /* FunctionExpression */ || e.kind === 191 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 190 /* FunctionExpression */ || initializer.kind === 203 /* ClassExpression */) { + if (initializer.kind === 194 /* FunctionExpression */ || + initializer.kind === 207 /* ClassExpression */ || + initializer.kind === 195 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -9217,6 +8641,13 @@ var ts; return e; } } + function isDefaultedJavascriptInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ function getOuterNameOfJsInitializer(node) { if (ts.isBinaryExpression(node.parent)) { @@ -9257,7 +8688,7 @@ var ts; return false; } function getRightMostAssignedExpression(node) { - while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { node = node.right; } return node; @@ -9280,6 +8711,14 @@ var ts; return 0 /* None */; } var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getSpecialPropertyAccessKind(lhs); + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9288,11 +8727,7 @@ var ts; return 2 /* ModuleExports */; } else if (isEntityNameExpression(lhs.expression)) { - if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { - // F.prototype = { ... } - return 6 /* Prototype */; - } - else if (ts.isPropertyAccessExpression(lhs.expression) && lhs.expression.name.escapedText === "prototype") { + if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr return 3 /* PrototypeProperty */; } @@ -9312,38 +8747,66 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 214 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + return node.parent; + case 257 /* ExternalModuleReference */: + return node.parent.parent; + case 189 /* CallExpression */: + return node.parent; + case 180 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242 /* ImportDeclaration */) { - return node.moduleSpecifier; - } - if (node.kind === 241 /* ImportEqualsDeclaration */) { - var reference = node.moduleReference; - if (reference.kind === 252 /* ExternalModuleReference */) { - return reference.expression; - } - } - if (node.kind === 248 /* ExportDeclaration */) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + return node.moduleSpecifier; + case 246 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 181 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9351,19 +8814,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 242 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 148 /* Parameter */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 269 /* ShorthandPropertyAssignment */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 149 /* Parameter */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 274 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9371,86 +8834,104 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 280 /* JSDocFunctionType */ && + return node.kind === 287 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ && - node.expression.right; + node.expression.operatorToken.kind === 58 /* EqualsToken */ + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: + return node.initializer; + case 273 /* PropertyAssignment */: return node.initializer; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 237 /* ModuleDeclaration */ && - node.body; + node.body.kind === 242 /* ModuleDeclaration */ + ? node.body + : undefined; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); - return result || ts.emptyArray; - function getJSDocCommentsAndTagsWorker(node) { - var parent = node.parent; - if (parent && (parent.kind === 268 /* PropertyAssignment */ || parent.kind === 151 /* PropertyDeclaration */ || getNestedModuleDeclaration(parent))) { - getJSDocCommentsAndTagsWorker(parent); - } - // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. - // /** - // * @param {number} name - // * @returns {number} - // */ - // var x = function(name) { return name.length; } - if (parent && parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { - getJSDocCommentsAndTagsWorker(parent.parent); - } - if (parent && parent.parent && parent.parent.parent && - (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { - getJSDocCommentsAndTagsWorker(parent.parent.parent); - } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || - node.kind === 183 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 214 /* ExpressionStatement */) { - getJSDocCommentsAndTagsWorker(parent); - } - // Pull parameter comments from declaring function as well - if (node.kind === 148 /* Parameter */) { - result = ts.addRange(result, ts.getJSDocParameterTags(node)); - } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { - result = ts.addRange(result, node.initializer.jsDoc); - } + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } + if (node.kind === 149 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); } + return result || ts.emptyArray; } ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 273 /* PropertyAssignment */ || + parent.kind === 152 /* PropertyDeclaration */ || + parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { @@ -9469,7 +8950,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -9478,10 +8962,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - ts.Debug.assert(node.parent.kind === 282 /* JSDocComment */); - return node.parent.parent; + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -9492,11 +8975,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9509,31 +8993,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 189 /* ParenthesizedExpression */: - case 181 /* ArrayLiteralExpression */: - case 202 /* SpreadElement */: - case 207 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 185 /* ArrayLiteralExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: node = parent; break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9560,27 +9044,31 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 211 /* Block */: - case 212 /* VariableStatement */: - case 224 /* WithStatement */: - case 215 /* IfStatement */: - case 225 /* SwitchStatement */: - case 239 /* CaseBlock */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 226 /* LabeledStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 228 /* TryStatement */: - case 267 /* CatchClause */: + case 216 /* Block */: + case 217 /* VariableStatement */: + case 229 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return true; } return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9588,15 +9076,15 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 172 /* ParenthesizedType */); + return walkUp(node, 175 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 189 /* ParenthesizedExpression */); + return walkUp(node, 193 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */) { + while (node.kind === 193 /* ParenthesizedExpression */) { node = node.expression; } return node; @@ -9604,11 +9092,11 @@ var ts; ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { + if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 192 /* DeleteExpression */; + return node && node.kind === 196 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9630,12 +9118,20 @@ var ts; switch (name.kind) { case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8 /* NumericLiteral */: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + } + } default: return false; } @@ -9643,7 +9139,7 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 146 /* ComputedPropertyName */ && + node.parent.kind === 147 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9651,32 +9147,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 271 /* EnumMember */: - case 268 /* PropertyAssignment */: - case 183 /* PropertyAccessExpression */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 187 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 145 /* QualifiedName */: - // Name on right hand side of dot in a type query + case 146 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 145 /* QualifiedName */) { + while (parent.kind === 146 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 164 /* TypeQuery */; + return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; } return false; - case 180 /* BindingElement */: - case 246 /* ImportSpecifier */: + case 184 /* BindingElement */: + case 251 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 250 /* ExportSpecifier */: - case 260 /* JsxAttribute */: + case 255 /* ExportSpecifier */: + case 265 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9692,29 +9188,49 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ || - node.kind === 240 /* NamespaceExportDeclaration */ || - node.kind === 243 /* ImportClause */ && !!node.name || - node.kind === 244 /* NamespaceImport */ || - node.kind === 246 /* ImportSpecifier */ || - node.kind === 250 /* ExportSpecifier */ || - node.kind === 247 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 245 /* NamespaceExportDeclaration */ || + node.kind === 248 /* ImportClause */ && !!node.name || + node.kind === 249 /* NamespaceImport */ || + node.kind === 251 /* ImportSpecifier */ || + node.kind === 255 /* ExportSpecifier */ || + node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; - function getClassExtendsHeritageClauseElement(node) { + function getEffectiveBaseTypeNode(node) { + if (isInJavaScriptFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } - ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -9750,11 +9266,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 144 /* LastKeyword */; + return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 144 /* LastContextualKeyword */; + return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9784,14 +9300,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9805,10 +9321,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -9831,11 +9347,11 @@ var ts; */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 146 /* ComputedPropertyName */ && + return name.kind === 147 /* ComputedPropertyName */ && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -9856,7 +9372,7 @@ var ts; if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -9909,11 +9425,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 148 /* Parameter */; + return root.kind === 149 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 180 /* BindingElement */) { + while (node.kind === 184 /* BindingElement */) { node = node.parent.parent; } return node; @@ -9921,15 +9437,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 154 /* Constructor */ - || kind === 190 /* FunctionExpression */ - || kind === 232 /* FunctionDeclaration */ - || kind === 191 /* ArrowFunction */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 237 /* ModuleDeclaration */ - || kind === 272 /* SourceFile */; + return kind === 155 /* Constructor */ + || kind === 194 /* FunctionExpression */ + || kind === 237 /* FunctionDeclaration */ + || kind === 195 /* ArrowFunction */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 242 /* ModuleDeclaration */ + || kind === 277 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -9948,23 +9464,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 186 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 186 /* NewExpression */: + case 190 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 196 /* PrefixUnaryExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 195 /* AwaitExpression */: - case 199 /* ConditionalExpression */: - case 201 /* YieldExpression */: + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: return 1 /* Right */; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (operator) { case 40 /* AsteriskAsteriskToken */: case 58 /* EqualsToken */: @@ -9988,15 +9504,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 186 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 198 /* BinaryExpression */) { + if (expression.kind === 202 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 196 /* PrefixUnaryExpression */ || expression.kind === 197 /* PostfixUnaryExpression */) { + else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10006,83 +9522,18 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 203 /* ClassExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* TemplateExpression */: - case 189 /* ParenthesizedExpression */: - case 204 /* OmittedExpression */: - return 19; - case 187 /* TaggedTemplateExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - return 18; - case 186 /* NewExpression */: - return hasArguments ? 18 : 17; - case 185 /* CallExpression */: - return 17; - case 197 /* PostfixUnaryExpression */: - return 16; - case 196 /* PrefixUnaryExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 195 /* AwaitExpression */: - return 15; - case 198 /* BinaryExpression */: + case 306 /* CommaListExpression */: + return 0; + case 206 /* SpreadElement */: + return 1; + case 205 /* YieldExpression */: + return 2; + case 203 /* ConditionalExpression */: + return 4; + case 202 /* BinaryExpression */: switch (operatorKind) { - case 51 /* ExclamationToken */: - case 52 /* TildeToken */: - return 15; - case 40 /* AsteriskAsteriskToken */: - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 14; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 13; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 12; - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - case 92 /* InKeyword */: - case 93 /* InstanceOfKeyword */: - return 11; - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 10; - case 48 /* AmpersandToken */: - return 9; - case 50 /* CaretToken */: - return 8; - case 49 /* BarToken */: - return 7; - case 53 /* AmpersandAmpersandToken */: - return 6; - case 54 /* BarBarToken */: - return 5; + case 26 /* CommaToken */: + return 0; case 58 /* EqualsToken */: case 59 /* PlusEqualsToken */: case 60 /* MinusEqualsToken */: @@ -10097,49 +9548,135 @@ var ts; case 70 /* CaretEqualsToken */: case 69 /* BarEqualsToken */: return 3; - case 26 /* CommaToken */: - return 0; default: - return -1; + return getBinaryOperatorPrecedence(operatorKind); } - case 199 /* ConditionalExpression */: - return 4; - case 201 /* YieldExpression */: - return 2; - case 202 /* SpreadElement */: - return 1; - case 296 /* CommaListExpression */: - return 0; + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: + return 16; + case 201 /* PostfixUnaryExpression */: + return 17; + case 189 /* CallExpression */: + return 18; + case 190 /* NewExpression */: + return hasArguments ? 19 : 18; + case 191 /* TaggedTemplateExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + return 19; + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 71 /* Identifier */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 204 /* TemplateExpression */: + case 193 /* ParenthesizedExpression */: + case 208 /* OmittedExpression */: + return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; + /* @internal */ + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 54 /* BarBarToken */: + return 5; + case 53 /* AmpersandAmpersandToken */: + return 6; + case 49 /* BarToken */: + return 7; + case 50 /* CaretToken */: + return 8; + case 48 /* AmpersandToken */: + return 9; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return 10; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + return 11; + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 37 /* PlusToken */: + case 38 /* MinusToken */: + return 13; + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + return 14; + case 40 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; function createDiagnosticCollection() { - var nonFileDiagnostics = []; + var nonFileDiagnostics = []; // See GH#19873 var filesWithDiagnostics = []; var fileDiagnostics = ts.createMap(); var hasReadNonFileDiagnostics = false; - var modificationCount = 0; return { add: add, + lookup: lookup, getGlobalDiagnostics: getGlobalDiagnostics, getDiagnostics: getDiagnostics, - getModificationCount: getModificationCount, reattachFileDiagnostics: reattachFileDiagnostics }; - function getModificationCount() { - return modificationCount; - } function reattachFileDiagnostics(newFile) { ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } function add(diagnostic) { var diagnostics; if (diagnostic.file) { diagnostics = fileDiagnostics.get(diagnostic.file.fileName); if (!diagnostics) { - diagnostics = []; + diagnostics = []; // See GH#19873 fileDiagnostics.set(diagnostic.file.fileName, diagnostics); ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); } @@ -10153,7 +9690,6 @@ var ts; diagnostics = nonFileDiagnostics; } ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); - modificationCount++; } function getGlobalDiagnostics() { hasReadNonFileDiagnostics = true; @@ -10257,13 +9793,25 @@ var ts; var lineStart; var lineCount; var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } function write(s) { if (s && s.length) { if (lineStart) { - output += getIndentString(indent); + s = getIndentString(indent) + s; lineStart = false; } output += s; + updateLineCountAndPosFor(s); } } function reset() { @@ -10275,20 +9823,13 @@ var ts; } function rawWrite(s) { if (s !== undefined) { - if (lineStart) { - lineStart = false; - } output += s; + updateLineCountAndPosFor(s); } } function writeLiteral(s) { if (s && s.length) { write(s); - var lineStartsOfS = ts.computeLineStarts(s); - if (lineStartsOfS.length > 1) { - lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); - } } } function writeLine() { @@ -10300,7 +9841,9 @@ var ts; } } function writeTextOfNode(text, node) { - write(getTextOfNodeFromSourceText(text, node)); + var s = getTextOfNodeFromSourceText(text, node); + write(s); + updateLineCountAndPosFor(s); } reset(); return { @@ -10313,8 +9856,8 @@ var ts; decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, clear: reset, @@ -10333,8 +9876,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -10348,35 +9891,46 @@ var ts; /** * Resolves a local path to a path which is absolute to the base of the emit */ - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { + function getDeclarationEmitOutputFilePath(fileName, host) { + // TODO: GH#25810 following should work but makes the build break: + // return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDir(fileName, host, outputDir) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10408,14 +9962,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10431,11 +9988,7 @@ var ts; } ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { - return ts.forEach(node.members, function (member) { - if (member.kind === 154 /* Constructor */ && nodeIsPresent(member.body)) { - return member; - } - }); + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorValueParameter(accessor) { @@ -10451,7 +10004,8 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -10464,7 +10018,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -10472,16 +10026,17 @@ var ts; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 var firstAccessor; var secondAccessor; var getAccessor; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 155 /* GetAccessor */) { + if (accessor.kind === 156 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 156 /* SetAccessor */) { + else if (accessor.kind === 157 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10490,7 +10045,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 155 /* GetAccessor */ || member.kind === 156 /* SetAccessor */) + if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10501,10 +10056,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 155 /* GetAccessor */ && !getAccessor) { + if (member.kind === 156 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 156 /* SetAccessor */ && !setAccessor) { + if (member.kind === 157 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10527,27 +10082,29 @@ var ts; return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; /** * Gets the effective return type annotation of a signature. If the node was parsed in a * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node * was parsed in a JavaScript file, gets the type annotation from JSDoc. @@ -10646,19 +10203,19 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -10821,7 +10378,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 205 /* ExpressionWithTypeArguments */ && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -10839,8 +10396,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 182 /* ObjectLiteralExpression */ - || kind === 181 /* ArrayLiteralExpression */; + return kind === 186 /* ObjectLiteralExpression */ + || kind === 185 /* ArrayLiteralExpression */; } return false; } @@ -10850,7 +10407,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 205 /* ExpressionWithTypeArguments */ + return node.kind === 209 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 /* ImplementsKeyword */ @@ -10859,22 +10416,29 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 182 /* ObjectLiteralExpression */ && + return expression.kind === 186 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 181 /* ArrayLiteralExpression */ && + return expression.kind === 185 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -10899,7 +10463,7 @@ var ts; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); - // handel utf8 + // handle utf8 if (charCode < 0x80) { output.push(charCode); } @@ -10956,6 +10520,78 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11143,8 +10779,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11163,6 +10799,10 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function getCheckFlags(symbol) { return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } @@ -11217,21 +10857,21 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 197 /* PostfixUnaryExpression */: - case 196 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 214 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function compareDataObjects(dst, src) { @@ -11322,7 +10962,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 65536 /* Object */ ? type.objectFlags : 0; + return type.flags & 131072 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11334,7 +10974,7 @@ var ts; } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { - return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; function showModuleSpecifier(_a) { @@ -11342,12 +10982,45 @@ var ts; return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); } ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { case 6 /* ESNext */: return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; case 3 /* ES2016 */: @@ -11371,6 +11044,11 @@ var ts; return position >= span.start && position < textSpanEnd(span); } ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; // Returns true if 'span' contains 'other'. function textSpanContainsTextSpan(span, other) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); @@ -11419,6 +11097,13 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + /* @internal */ + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11555,9 +11240,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 147 /* TypeParameter */) { + if (d && d.kind === 148 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 234 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { return current; } } @@ -11565,7 +11250,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 154 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11582,27 +11267,34 @@ var ts; return isEmptyBindingPattern(node.name); } ts.isEmptyBindingElement = isEmptyBindingElement; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 180 /* BindingElement */ || ts.isBindingPattern(node))) { - node = node.parent; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; } - return node; + return node.parent; } - function getCombinedModifierFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = ts.getModifierFlags(node); - if (node.kind === 230 /* VariableDeclaration */) { + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 235 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 231 /* VariableDeclarationList */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 236 /* VariableDeclarationList */) { + flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 212 /* VariableStatement */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 217 /* VariableStatement */) { + flags |= getFlags(node); } return flags; } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } ts.getCombinedModifierFlags = getCombinedModifierFlags; // Returns the node flags for this node and all relevant parent nodes. This is done so that // nodes like variable declarations and binding elements can returned a view of their flags @@ -11612,19 +11304,7 @@ var ts; // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 230 /* VariableDeclaration */) { - node = node.parent; - } - if (node && node.kind === 231 /* VariableDeclarationList */) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 212 /* VariableStatement */) { - flags |= node.flags; - } - return flags; + return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; /** @@ -11674,7 +11354,7 @@ var ts; // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -11732,16 +11412,6 @@ var ts; return unescapeLeadingUnderscores(symbol.escapedName); } ts.symbolName = symbolName; - /** - * Remove extra underscore from escaped identifier text content. - * @deprecated Use `id.text` for the unescaped text. - * @param identifier The escaped identifier text. - * @returns The unescaped identifier text. - */ - function unescapeIdentifier(id) { - return id; - } - ts.unescapeIdentifier = unescapeIdentifier; /** * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol @@ -11758,17 +11428,17 @@ var ts; } // Covers remaining cases switch (hostNode.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return expr.name; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -11777,10 +11447,10 @@ var ts; return undefined; case 1 /* EndOfFileToken */: return undefined; - case 189 /* ParenthesizedExpression */: { + case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 226 /* LabeledStatement */: { + case 231 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -11792,7 +11462,7 @@ var ts; } function getDeclarationIdentifier(node) { var name = getNameOfDeclaration(node); - return ts.isIdentifier(name) ? name : undefined; + return name && ts.isIdentifier(name) ? name : undefined; } function getNameOfJSDocTypedef(declaration) { return declaration.name || nameForNamelessJSDocTypedef(declaration); @@ -11803,22 +11473,20 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; - function getNameOfDeclaration(declaration) { - if (!declaration) { - return undefined; - } + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 292 /* JSDocPropertyTag */: - case 287 /* JSDocParameterTag */: { + case 302 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 145 /* QualifiedName */) { + if (name.kind === 146 /* QualifiedName */) { return name.right; } break; } - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var expr = declaration; switch (ts.getSpecialPropertyAssignmentKind(expr)) { case 1 /* ExportsProperty */: @@ -11830,16 +11498,39 @@ var ts; return undefined; } } - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 247 /* ExportAssignment */: { + case 252 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } } return declaration.name; } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } /** * Gets the JSDoc parameter tags for the node if present. * @@ -11854,12 +11545,22 @@ var ts; * parameters by name and binding patterns do not have a name. */ 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; }); + if (param.name) { + if (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; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } } - // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name - return undefined; + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; /** @@ -11869,33 +11570,38 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286 /* JSDocClassTag */); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288 /* JSDocReturnTag */); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } ts.getJSDocTemplateTag = getJSDocTemplateTag; /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node) { // We should have already issued an error if there were multiple type jsdocs, so just use the first one. - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -11914,25 +11620,35 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); - if (!tag && node.kind === 148 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -11940,22 +11656,37 @@ var ts; var tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } ts.getJSDocTags = getJSDocTags; /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ function getAllJSDocTagsOfKind(node, kind) { - var tags = getJSDocTags(node); - return ts.filter(tags, function (doc) { return doc.kind === kind; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -11999,618 +11730,647 @@ var ts; ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 145 /* QualifiedName */; + return node.kind === 146 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 146 /* ComputedPropertyName */; + return node.kind === 147 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 147 /* TypeParameter */; + return node.kind === 148 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 148 /* Parameter */; + return node.kind === 149 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 149 /* Decorator */; + return node.kind === 150 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 150 /* PropertySignature */; + return node.kind === 151 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 151 /* PropertyDeclaration */; + return node.kind === 152 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 152 /* MethodSignature */; + return node.kind === 153 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 153 /* MethodDeclaration */; + return node.kind === 154 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 154 /* Constructor */; + return node.kind === 155 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 155 /* GetAccessor */; + return node.kind === 156 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 156 /* SetAccessor */; + return node.kind === 157 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 157 /* CallSignature */; + return node.kind === 158 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 158 /* ConstructSignature */; + return node.kind === 159 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 159 /* IndexSignature */; + return node.kind === 160 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 160 /* TypePredicate */; + return node.kind === 161 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 161 /* TypeReference */; + return node.kind === 162 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 162 /* FunctionType */; + return node.kind === 163 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 163 /* ConstructorType */; + return node.kind === 164 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 164 /* TypeQuery */; + return node.kind === 165 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 165 /* TypeLiteral */; + return node.kind === 166 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 166 /* ArrayType */; + return node.kind === 167 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 167 /* TupleType */; + return node.kind === 168 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 168 /* UnionType */; + return node.kind === 171 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 169 /* IntersectionType */; + return node.kind === 172 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 170 /* ConditionalType */; + return node.kind === 173 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 171 /* InferType */; + return node.kind === 174 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 172 /* ParenthesizedType */; + return node.kind === 175 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 173 /* ThisType */; + return node.kind === 176 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 174 /* TypeOperator */; + return node.kind === 177 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 175 /* IndexedAccessType */; + return node.kind === 178 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 176 /* MappedType */; + return node.kind === 179 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 177 /* LiteralType */; + return node.kind === 180 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 181 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 178 /* ObjectBindingPattern */; + return node.kind === 182 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 179 /* ArrayBindingPattern */; + return node.kind === 183 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 180 /* BindingElement */; + return node.kind === 184 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 181 /* ArrayLiteralExpression */; + return node.kind === 185 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 182 /* ObjectLiteralExpression */; + return node.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 183 /* PropertyAccessExpression */; + return node.kind === 187 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 184 /* ElementAccessExpression */; + return node.kind === 188 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 185 /* CallExpression */; + return node.kind === 189 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 186 /* NewExpression */; + return node.kind === 190 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 187 /* TaggedTemplateExpression */; + return node.kind === 191 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 188 /* TypeAssertionExpression */; + return node.kind === 192 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 189 /* ParenthesizedExpression */; + return node.kind === 193 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 295 /* PartiallyEmittedExpression */) { + while (node.kind === 305 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 190 /* FunctionExpression */; + return node.kind === 194 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 191 /* ArrowFunction */; + return node.kind === 195 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 192 /* DeleteExpression */; + return node.kind === 196 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 193 /* TypeOfExpression */; + return node.kind === 197 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 194 /* VoidExpression */; + return node.kind === 198 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 195 /* AwaitExpression */; + return node.kind === 199 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 196 /* PrefixUnaryExpression */; + return node.kind === 200 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 197 /* PostfixUnaryExpression */; + return node.kind === 201 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 198 /* BinaryExpression */; + return node.kind === 202 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 199 /* ConditionalExpression */; + return node.kind === 203 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 200 /* TemplateExpression */; + return node.kind === 204 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 201 /* YieldExpression */; + return node.kind === 205 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 202 /* SpreadElement */; + return node.kind === 206 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 203 /* ClassExpression */; + return node.kind === 207 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 204 /* OmittedExpression */; + return node.kind === 208 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 205 /* ExpressionWithTypeArguments */; + return node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 206 /* AsExpression */; + return node.kind === 210 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 207 /* NonNullExpression */; + return node.kind === 211 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 208 /* MetaProperty */; + return node.kind === 212 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 209 /* TemplateSpan */; + return node.kind === 214 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 210 /* SemicolonClassElement */; + return node.kind === 215 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 211 /* Block */; + return node.kind === 216 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 212 /* VariableStatement */; + return node.kind === 217 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 213 /* EmptyStatement */; + return node.kind === 218 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 214 /* ExpressionStatement */; + return node.kind === 219 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 215 /* IfStatement */; + return node.kind === 220 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 216 /* DoStatement */; + return node.kind === 221 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 217 /* WhileStatement */; + return node.kind === 222 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 218 /* ForStatement */; + return node.kind === 223 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 219 /* ForInStatement */; + return node.kind === 224 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 220 /* ForOfStatement */; + return node.kind === 225 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 221 /* ContinueStatement */; + return node.kind === 226 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 222 /* BreakStatement */; + return node.kind === 227 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 222 /* BreakStatement */ || node.kind === 221 /* ContinueStatement */; + return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 223 /* ReturnStatement */; + return node.kind === 228 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 224 /* WithStatement */; + return node.kind === 229 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 225 /* SwitchStatement */; + return node.kind === 230 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 226 /* LabeledStatement */; + return node.kind === 231 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 227 /* ThrowStatement */; + return node.kind === 232 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 228 /* TryStatement */; + return node.kind === 233 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 229 /* DebuggerStatement */; + return node.kind === 234 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 230 /* VariableDeclaration */; + return node.kind === 235 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 231 /* VariableDeclarationList */; + return node.kind === 236 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 232 /* FunctionDeclaration */; + return node.kind === 237 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 233 /* ClassDeclaration */; + return node.kind === 238 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 234 /* InterfaceDeclaration */; + return node.kind === 239 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 235 /* TypeAliasDeclaration */; + return node.kind === 240 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 236 /* EnumDeclaration */; + return node.kind === 241 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */; + return node.kind === 242 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 238 /* ModuleBlock */; + return node.kind === 243 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 239 /* CaseBlock */; + return node.kind === 244 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 240 /* NamespaceExportDeclaration */; + return node.kind === 245 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */; + return node.kind === 246 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 242 /* ImportDeclaration */; + return node.kind === 247 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 243 /* ImportClause */; + return node.kind === 248 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 244 /* NamespaceImport */; + return node.kind === 249 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 245 /* NamedImports */; + return node.kind === 250 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 246 /* ImportSpecifier */; + return node.kind === 251 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 247 /* ExportAssignment */; + return node.kind === 252 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 248 /* ExportDeclaration */; + return node.kind === 253 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 249 /* NamedExports */; + return node.kind === 254 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 250 /* ExportSpecifier */; + return node.kind === 255 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 251 /* MissingDeclaration */; + return node.kind === 256 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 252 /* ExternalModuleReference */; + return node.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 253 /* JsxElement */; + return node.kind === 258 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 254 /* JsxSelfClosingElement */; + return node.kind === 259 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 255 /* JsxOpeningElement */; + return node.kind === 260 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 256 /* JsxClosingElement */; + return node.kind === 261 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 257 /* JsxFragment */; + return node.kind === 262 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 258 /* JsxOpeningFragment */; + return node.kind === 263 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 259 /* JsxClosingFragment */; + return node.kind === 264 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 260 /* JsxAttribute */; + return node.kind === 265 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 261 /* JsxAttributes */; + return node.kind === 266 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 262 /* JsxSpreadAttribute */; + return node.kind === 267 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 263 /* JsxExpression */; + return node.kind === 268 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 264 /* CaseClause */; + return node.kind === 269 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 265 /* DefaultClause */; + return node.kind === 270 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 266 /* HeritageClause */; + return node.kind === 271 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 267 /* CatchClause */; + return node.kind === 272 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 268 /* PropertyAssignment */; + return node.kind === 273 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 269 /* ShorthandPropertyAssignment */; + return node.kind === 274 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 270 /* SpreadAssignment */; + return node.kind === 275 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 271 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 272 /* SourceFile */; + return node.kind === 277 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 273 /* Bundle */; + return node.kind === 278 /* Bundle */; } ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 279 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 274 /* JSDocTypeExpression */; + return node.kind === 281 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 275 /* JSDocAllType */; + return node.kind === 282 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 276 /* JSDocUnknownType */; + return node.kind === 283 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 277 /* JSDocNullableType */; + return node.kind === 284 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 278 /* JSDocNonNullableType */; + return node.kind === 285 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 279 /* JSDocOptionalType */; + return node.kind === 286 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 280 /* JSDocFunctionType */; + return node.kind === 287 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 281 /* JSDocVariadicType */; + return node.kind === 288 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 282 /* JSDocComment */; + return node.kind === 289 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 285 /* JSDocAugmentsTag */; + return node.kind === 293 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 294 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocThisTag(node) { + return node.kind === 298 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 287 /* JSDocParameterTag */; + return node.kind === 296 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 288 /* JSDocReturnTag */; + return node.kind === 297 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 289 /* JSDocTypeTag */; + return node.kind === 299 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 290 /* JSDocTemplateTag */; + return node.kind === 300 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 291 /* JSDocTypedefTag */; + return node.kind === 301 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 292 /* JSDocPropertyTag */; + return node.kind === 302 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 292 /* JSDocPropertyTag */ || node.kind === 287 /* JSDocParameterTag */; + return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 283 /* JSDocTypeLiteral */; + return node.kind === 290 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 295 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 291 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); // Node tests // @@ -12619,7 +12379,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 293 /* SyntaxList */; + return n.kind === 303 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -12629,7 +12389,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 145 /* FirstNode */; + return kind >= 146 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -12638,7 +12398,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 144 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -12663,6 +12423,10 @@ var ts; return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; return kind === 15 /* TemplateMiddle */ @@ -12676,7 +12440,6 @@ var ts; // Identifiers /* @internal */ function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; @@ -12700,13 +12463,23 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 145 /* QualifiedName */ + return kind === 146 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12715,14 +12488,14 @@ var ts; return kind === 71 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 146 /* ComputedPropertyName */; + || kind === 147 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 178 /* ObjectBindingPattern */ - || kind === 179 /* ArrayBindingPattern */; + || kind === 182 /* ObjectBindingPattern */ + || kind === 183 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -12737,13 +12510,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; default: return false; @@ -12752,13 +12525,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 162 /* FunctionType */: - case 280 /* JSDocFunctionType */: - case 163 /* ConstructorType */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 163 /* FunctionType */: + case 287 /* JSDocFunctionType */: + case 164 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12773,30 +12547,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 154 /* Constructor */ - || kind === 151 /* PropertyDeclaration */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 159 /* IndexSignature */ - || kind === 210 /* SemicolonClassElement */ - || kind === 251 /* MissingDeclaration */; + return kind === 155 /* Constructor */ + || kind === 152 /* PropertyDeclaration */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 160 /* IndexSignature */ + || kind === 215 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 233 /* ClassDeclaration */ || node.kind === 203 /* ClassExpression */); + return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 155 /* GetAccessor */ || node.kind === 156 /* SetAccessor */); + return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; default: return false; @@ -12806,29 +12579,32 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 158 /* ConstructSignature */ - || kind === 157 /* CallSignature */ - || kind === 150 /* PropertySignature */ - || kind === 152 /* MethodSignature */ - || kind === 159 /* IndexSignature */ - || kind === 251 /* MissingDeclaration */; + return kind === 159 /* ConstructSignature */ + || kind === 158 /* CallSignature */ + || kind === 151 /* PropertySignature */ + || kind === 153 /* MethodSignature */ + || kind === 160 /* IndexSignature */; } ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 268 /* PropertyAssignment */ - || kind === 269 /* ShorthandPropertyAssignment */ - || kind === 270 /* SpreadAssignment */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 251 /* MissingDeclaration */; + return kind === 273 /* PropertyAssignment */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 275 /* SpreadAssignment */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 160 /* FirstTypeNode */ && kind <= 177 /* LastTypeNode */) + return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) || kind === 119 /* AnyKeyword */ + || kind === 142 /* UnknownKeyword */ || kind === 134 /* NumberKeyword */ || kind === 135 /* ObjectKeyword */ || kind === 122 /* BooleanKeyword */ @@ -12839,14 +12615,14 @@ var ts; || kind === 140 /* UndefinedKeyword */ || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ - || kind === 205 /* ExpressionWithTypeArguments */ - || kind === 275 /* JSDocAllType */ - || kind === 276 /* JSDocUnknownType */ - || kind === 277 /* JSDocNullableType */ - || kind === 278 /* JSDocNonNullableType */ - || kind === 279 /* JSDocOptionalType */ - || kind === 280 /* JSDocFunctionType */ - || kind === 281 /* JSDocVariadicType */; + || kind === 209 /* ExpressionWithTypeArguments */ + || kind === 282 /* JSDocAllType */ + || kind === 283 /* JSDocUnknownType */ + || kind === 284 /* JSDocNullableType */ + || kind === 285 /* JSDocNonNullableType */ + || kind === 286 /* JSDocOptionalType */ + || kind === 287 /* JSDocFunctionType */ + || kind === 288 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -12859,8 +12635,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return true; } return false; @@ -12871,8 +12647,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 179 /* ArrayBindingPattern */ - || kind === 178 /* ObjectBindingPattern */; + return kind === 183 /* ArrayBindingPattern */ + || kind === 182 /* ObjectBindingPattern */; } return false; } @@ -12880,15 +12656,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 181 /* ArrayLiteralExpression */ - || kind === 182 /* ObjectLiteralExpression */; + return kind === 185 /* ArrayLiteralExpression */ + || kind === 186 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 180 /* BindingElement */ - || kind === 204 /* OmittedExpression */; + return kind === 184 /* BindingElement */ + || kind === 208 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12897,9 +12673,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 184 /* BindingElement */: return true; } return false; @@ -12920,8 +12696,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 178 /* ObjectBindingPattern */: - case 182 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return true; } return false; @@ -12933,28 +12709,36 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return true; } return false; } ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 187 /* PropertyAccessExpression */ + || kind === 146 /* QualifiedName */ + || kind === 181 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 183 /* PropertyAccessExpression */ - || kind === 145 /* QualifiedName */; + return kind === 187 /* PropertyAccessExpression */ + || kind === 146 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 187 /* TaggedTemplateExpression */: - case 149 /* Decorator */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: + case 150 /* Decorator */: return true; default: return false; @@ -12962,12 +12746,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 185 /* CallExpression */ || node.kind === 186 /* NewExpression */; + return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 200 /* TemplateExpression */ + return kind === 204 /* TemplateExpression */ || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12978,32 +12762,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - case 186 /* NewExpression */: - case 185 /* CallExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 187 /* TaggedTemplateExpression */: - case 181 /* ArrayLiteralExpression */: - case 189 /* ParenthesizedExpression */: - case 182 /* ObjectLiteralExpression */: - case 203 /* ClassExpression */: - case 190 /* FunctionExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 190 /* NewExpression */: + case 189 /* CallExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 191 /* TaggedTemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 193 /* ParenthesizedExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: case 71 /* Identifier */: case 12 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 99 /* ThisKeyword */: case 101 /* TrueKeyword */: case 97 /* SuperKeyword */: - case 207 /* NonNullExpression */: - case 208 /* MetaProperty */: + case 211 /* NonNullExpression */: + case 212 /* MetaProperty */: case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13017,13 +12801,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 195 /* AwaitExpression */: - case 188 /* TypeAssertionExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 192 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13032,9 +12816,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return true; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; default: @@ -13053,15 +12837,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 199 /* ConditionalExpression */: - case 201 /* YieldExpression */: - case 191 /* ArrowFunction */: - case 198 /* BinaryExpression */: - case 202 /* SpreadElement */: - case 206 /* AsExpression */: - case 204 /* OmittedExpression */: - case 296 /* CommaListExpression */: - case 295 /* PartiallyEmittedExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: + case 195 /* ArrowFunction */: + case 202 /* BinaryExpression */: + case 206 /* SpreadElement */: + case 210 /* AsExpression */: + case 208 /* OmittedExpression */: + case 306 /* CommaListExpression */: + case 305 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13069,18 +12853,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 188 /* TypeAssertionExpression */ - || kind === 206 /* AsExpression */; + return kind === 192 /* TypeAssertionExpression */ + || kind === 210 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 295 /* PartiallyEmittedExpression */; + return node.kind === 305 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 294 /* NotEmittedStatement */; + return node.kind === 304 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13091,13 +12875,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return true; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13105,7 +12889,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 219 /* ForInStatement */ || node.kind === 220 /* ForOfStatement */; + return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13129,111 +12913,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 238 /* ModuleBlock */ - || kind === 237 /* ModuleDeclaration */ + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */ || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 238 /* ModuleBlock */ - || kind === 237 /* ModuleDeclaration */; + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 237 /* ModuleDeclaration */; + || kind === 242 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 245 /* NamedImports */ - || kind === 244 /* NamespaceImport */; + return kind === 250 /* NamedImports */ + || kind === 249 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ || node.kind === 236 /* EnumDeclaration */; + return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 191 /* ArrowFunction */ - || kind === 180 /* BindingElement */ - || kind === 233 /* ClassDeclaration */ - || kind === 203 /* ClassExpression */ - || kind === 154 /* Constructor */ - || kind === 236 /* EnumDeclaration */ - || kind === 271 /* EnumMember */ - || kind === 250 /* ExportSpecifier */ - || kind === 232 /* FunctionDeclaration */ - || kind === 190 /* FunctionExpression */ - || kind === 155 /* GetAccessor */ - || kind === 243 /* ImportClause */ - || kind === 241 /* ImportEqualsDeclaration */ - || kind === 246 /* ImportSpecifier */ - || kind === 234 /* InterfaceDeclaration */ - || kind === 260 /* JsxAttribute */ - || kind === 153 /* MethodDeclaration */ - || kind === 152 /* MethodSignature */ - || kind === 237 /* ModuleDeclaration */ - || kind === 240 /* NamespaceExportDeclaration */ - || kind === 244 /* NamespaceImport */ - || kind === 148 /* Parameter */ - || kind === 268 /* PropertyAssignment */ - || kind === 151 /* PropertyDeclaration */ - || kind === 150 /* PropertySignature */ - || kind === 156 /* SetAccessor */ - || kind === 269 /* ShorthandPropertyAssignment */ - || kind === 235 /* TypeAliasDeclaration */ - || kind === 147 /* TypeParameter */ - || kind === 230 /* VariableDeclaration */ - || kind === 291 /* JSDocTypedefTag */; + return kind === 195 /* ArrowFunction */ + || kind === 184 /* BindingElement */ + || kind === 238 /* ClassDeclaration */ + || kind === 207 /* ClassExpression */ + || kind === 155 /* Constructor */ + || kind === 241 /* EnumDeclaration */ + || kind === 276 /* EnumMember */ + || kind === 255 /* ExportSpecifier */ + || kind === 237 /* FunctionDeclaration */ + || kind === 194 /* FunctionExpression */ + || kind === 156 /* GetAccessor */ + || kind === 248 /* ImportClause */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 251 /* ImportSpecifier */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 265 /* JsxAttribute */ + || kind === 154 /* MethodDeclaration */ + || kind === 153 /* MethodSignature */ + || kind === 242 /* ModuleDeclaration */ + || kind === 245 /* NamespaceExportDeclaration */ + || kind === 249 /* NamespaceImport */ + || kind === 149 /* Parameter */ + || kind === 273 /* PropertyAssignment */ + || kind === 152 /* PropertyDeclaration */ + || kind === 151 /* PropertySignature */ + || kind === 157 /* SetAccessor */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 240 /* TypeAliasDeclaration */ + || kind === 148 /* TypeParameter */ + || kind === 235 /* VariableDeclaration */ + || kind === 301 /* JSDocTypedefTag */ + || kind === 295 /* JSDocCallbackTag */ + || kind === 302 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 232 /* FunctionDeclaration */ - || kind === 251 /* MissingDeclaration */ - || kind === 233 /* ClassDeclaration */ - || kind === 234 /* InterfaceDeclaration */ - || kind === 235 /* TypeAliasDeclaration */ - || kind === 236 /* EnumDeclaration */ - || kind === 237 /* ModuleDeclaration */ - || kind === 242 /* ImportDeclaration */ - || kind === 241 /* ImportEqualsDeclaration */ - || kind === 248 /* ExportDeclaration */ - || kind === 247 /* ExportAssignment */ - || kind === 240 /* NamespaceExportDeclaration */; + return kind === 237 /* FunctionDeclaration */ + || kind === 256 /* MissingDeclaration */ + || kind === 238 /* ClassDeclaration */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 240 /* TypeAliasDeclaration */ + || kind === 241 /* EnumDeclaration */ + || kind === 242 /* ModuleDeclaration */ + || kind === 247 /* ImportDeclaration */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 253 /* ExportDeclaration */ + || kind === 252 /* ExportAssignment */ + || kind === 245 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 222 /* BreakStatement */ - || kind === 221 /* ContinueStatement */ - || kind === 229 /* DebuggerStatement */ - || kind === 216 /* DoStatement */ - || kind === 214 /* ExpressionStatement */ - || kind === 213 /* EmptyStatement */ - || kind === 219 /* ForInStatement */ - || kind === 220 /* ForOfStatement */ - || kind === 218 /* ForStatement */ - || kind === 215 /* IfStatement */ - || kind === 226 /* LabeledStatement */ - || kind === 223 /* ReturnStatement */ - || kind === 225 /* SwitchStatement */ - || kind === 227 /* ThrowStatement */ - || kind === 228 /* TryStatement */ - || kind === 212 /* VariableStatement */ - || kind === 217 /* WhileStatement */ - || kind === 224 /* WithStatement */ - || kind === 294 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + return kind === 227 /* BreakStatement */ + || kind === 226 /* ContinueStatement */ + || kind === 234 /* DebuggerStatement */ + || kind === 221 /* DoStatement */ + || kind === 219 /* ExpressionStatement */ + || kind === 218 /* EmptyStatement */ + || kind === 224 /* ForInStatement */ + || kind === 225 /* ForOfStatement */ + || kind === 223 /* ForStatement */ + || kind === 220 /* IfStatement */ + || kind === 231 /* LabeledStatement */ + || kind === 228 /* ReturnStatement */ + || kind === 230 /* SwitchStatement */ + || kind === 232 /* ThrowStatement */ + || kind === 233 /* TryStatement */ + || kind === 217 /* VariableStatement */ + || kind === 222 /* WhileStatement */ + || kind === 229 /* WithStatement */ + || kind === 304 /* NotEmittedStatement */ + || kind === 308 /* EndOfDeclarationMarker */ + || kind === 307 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 147 /* TypeParameter */) { - return node.parent.kind !== 290 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 148 /* TypeParameter */) { + return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13260,10 +13046,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 211 /* Block */) + if (node.kind !== 216 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 228 /* TryStatement */ || node.parent.kind === 267 /* CatchClause */) { + if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { return false; } } @@ -13273,8 +13059,8 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 252 /* ExternalModuleReference */ - || kind === 145 /* QualifiedName */ + return kind === 257 /* ExternalModuleReference */ + || kind === 146 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13284,76 +13070,78 @@ var ts; var kind = node.kind; return kind === 99 /* ThisKeyword */ || kind === 71 /* Identifier */ - || kind === 183 /* PropertyAccessExpression */; + || kind === 187 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 253 /* JsxElement */ - || kind === 263 /* JsxExpression */ - || kind === 254 /* JsxSelfClosingElement */ + return kind === 258 /* JsxElement */ + || kind === 268 /* JsxExpression */ + || kind === 259 /* JsxSelfClosingElement */ || kind === 10 /* JsxText */ - || kind === 257 /* JsxFragment */; + || kind === 262 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 260 /* JsxAttribute */ - || kind === 262 /* JsxSpreadAttribute */; + return kind === 265 /* JsxAttribute */ + || kind === 267 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 263 /* JsxExpression */; + || kind === 268 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 255 /* JsxOpeningElement */ - || kind === 254 /* JsxSelfClosingElement */; + return kind === 260 /* JsxOpeningElement */ + || kind === 259 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 264 /* CaseClause */ - || kind === 265 /* DefaultClause */; + return kind === 269 /* CaseClause */ + || kind === 270 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 274 /* FirstJSDocNode */ && node.kind <= 292 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 282 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 284 /* FirstJSDocTagNode */ && node.kind <= 292 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 156 /* SetAccessor */; + return node.kind === 157 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 155 /* GetAccessor */; + return node.kind === 156 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; /** True if has type node attached to it. */ @@ -13376,13 +13164,13 @@ var ts; ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { switch (node.kind) { - case 260 /* JsxAttribute */: - case 262 /* JsxSpreadAttribute */: - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; default: return false; @@ -13391,16 +13179,1318 @@ var ts; ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 161 /* TypeReference */ || node.kind === 205 /* ExpressionWithTypeArguments */; + return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); -/// -/// +/* @internal */ +(function (ts) { + /** @internal */ + function isNamedImportsOrExports(node) { + return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + /* @internal */ + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + /* @internal */ + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + /* @internal */ + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + /* @internal */ + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + /* @internal */ + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /* @internal */ + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + 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 separators) + * (\\.(?!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) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + 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 */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + 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); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJavaScriptFileExtension(fileName) { + return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + 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 (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTypeScript(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; +})(ts || (ts = {})); var ts; (function (ts) { var SignatureFlags; @@ -13409,7 +14499,6 @@ var ts; 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 = {})); @@ -13420,7 +14509,7 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 272 /* SourceFile */) { + if (kind === 277 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71 /* Identifier */) { @@ -13451,6 +14540,13 @@ var ts; } } } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -13465,28 +14561,28 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 144 /* LastToken */) { + if (!node || node.kind <= 145 /* LastToken */) { return; } switch (node.kind) { - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -13494,7 +14590,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -13502,51 +14598,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -13557,298 +14653,302 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 167 /* TupleType */: + case 168 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 171 /* InferType */: + case 174 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 172 /* ParenthesizedType */: - case 174 /* TypeOperator */: + case 181 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 175 /* ParenthesizedType */: + case 177 /* TypeOperator */: return visitNode(cbNode, node.type); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 176 /* MappedType */: + case 179 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return visitNode(cbNode, node.literal); - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 206 /* AsExpression */: + case 210 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return visitNode(cbNode, node.name); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 211 /* Block */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 272 /* SourceFile */: + case 277 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return visitNode(cbNode, node.label); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 264 /* CaseClause */: + case 269 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 149 /* Decorator */: + case 150 /* Decorator */: return visitNode(cbNode, node.expression); - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 271 /* EnumMember */: + case 276 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 251 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 274 /* JSDocTypeExpression */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 281 /* JSDocTypeExpression */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 286 /* JSDocOptionalType */: + case 288 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 278 /* JSDocNonNullableType */: - return visitNode(cbNode, node.type); - case 277 /* JSDocNullableType */: - return visitNode(cbNode, node.type); - case 279 /* JSDocOptionalType */: - return visitNode(cbNode, node.type); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 281 /* JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 282 /* JSDocComment */: + case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 287 /* JSDocParameterTag */: - case 292 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: + case 302 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -13857,17 +14957,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 288 /* JSDocReturnTag */: + case 297 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 285 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 274 /* JSDocTypeExpression */) { + node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -13875,7 +14975,18 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 283 /* JSDocTypeLiteral */: + case 295 /* JSDocCallbackTag */: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 298 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 291 /* JSDocSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -13883,7 +14994,7 @@ var ts; } } return; - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -13891,7 +15002,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -13925,10 +15042,11 @@ var ts; // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. - newSourceFile.flags |= (sourceFile.flags & 524288 /* PossiblyContainsDynamicImport */); + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); return newSourceFile; } ts.updateSourceFile = updateSourceFile; @@ -14050,7 +15168,15 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -14068,25 +15194,58 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); // Set source file so that errors will be reported with this file name sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); - var result = sourceFile; + sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); + var pos = getNodePos(); if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 /* OpenBraceToken */ || - lookAhead(function () { return token() === 9 /* StringLiteral */; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(219 /* ExpressionStatement */); + switch (token()) { + case 21 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 38 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17 /* OpenBraceToken */); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -14110,9 +15269,11 @@ var ts; switch (scriptKind) { case 1 /* JS */: case 2 /* JSX */: - case 6 /* JSON */: contextFlags = 65536 /* JavaScriptFile */; break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; default: contextFlags = 0 /* None */; break; @@ -14138,7 +15299,7 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { var isDeclarationFile = isDeclarationFileName(fileName); if (isDeclarationFile) { - contextFlags |= 2097152 /* Ambient */; + contextFlags |= 4194304 /* Ambient */; } sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; @@ -14164,13 +15325,10 @@ var ts; } } function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - } - } + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; return node; } function fixupParentReferences(rootNode) { @@ -14206,10 +15364,11 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(272 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -14312,9 +15471,7 @@ var ts; return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { // Don't report another error if it would just be at the same position as the last error. @@ -14326,9 +15483,14 @@ var ts; // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -14488,8 +15650,8 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { addJSDocComment(node); } @@ -14523,7 +15685,7 @@ var ts; if (reportAtCurrentPosition) { parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); } - else { + else if (diagnosticMessage) { parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); @@ -14590,7 +15752,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(146 /* ComputedPropertyName */); + var node = createNode(147 /* ComputedPropertyName */); parseExpected(21 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -14610,25 +15772,26 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; + switch (token()) { + case 76 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + case 79 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 115 /* StaticKeyword */: + case 125 /* GetKeyword */: + case 136 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -14726,7 +15889,7 @@ var ts; case 14 /* JsxChildren */: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); @@ -14815,6 +15978,8 @@ var ts; return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; case 14 /* JsxChildren */: return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -14915,7 +16080,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 6387712 /* ContextFlags */; + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -15001,14 +16166,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 154 /* Constructor */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 151 /* PropertyDeclaration */: - case 210 /* SemicolonClassElement */: + case 155 /* Constructor */: + case 160 /* IndexSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 215 /* SemicolonClassElement */: return true; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -15023,8 +16188,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: return true; } } @@ -15033,58 +16198,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 212 /* VariableStatement */: - case 211 /* Block */: - case 215 /* IfStatement */: - case 214 /* ExpressionStatement */: - case 227 /* ThrowStatement */: - case 223 /* ReturnStatement */: - case 225 /* SwitchStatement */: - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 213 /* EmptyStatement */: - case 228 /* TryStatement */: - case 226 /* LabeledStatement */: - case 216 /* DoStatement */: - case 229 /* DebuggerStatement */: - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - case 247 /* ExportAssignment */: - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 217 /* VariableStatement */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 219 /* ExpressionStatement */: + case 232 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 230 /* SwitchStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 218 /* EmptyStatement */: + case 233 /* TryStatement */: + case 231 /* LabeledStatement */: + case 221 /* DoStatement */: + case 234 /* DebuggerStatement */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 271 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 150 /* PropertySignature */: - case 157 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 151 /* PropertySignature */: + case 158 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 230 /* VariableDeclaration */) { + if (node.kind !== 235 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -15105,7 +16270,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 148 /* Parameter */) { + if (node.kind !== 149 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -15146,6 +16311,7 @@ var ts; case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; + default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` } } // Parses a comma-delimited list of elements @@ -15209,7 +16375,12 @@ var ts; return result; } function createMissingList() { - return createNodeArray([], getNodePos()); + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -15234,7 +16405,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(145 /* QualifiedName */, entity.pos); + var node = createNode(146 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -15271,19 +16442,19 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(200 /* TemplateExpression */); + var template = createNode(204 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(209 /* TemplateSpan */); + var span = createNode(214 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18 /* CloseBraceToken */) { @@ -15334,28 +16505,55 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(161 /* TypeReference */); + var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 162 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 163 /* FunctionType */: + case 164 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 175 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(160 /* TypePredicate */, lhs.pos); + var node = createNode(161 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(173 /* ThisType */); + var node = createNode(176 /* ThisType */); nextToken(); return finishNode(node); } - function parseJSDocAllType() { - var result = createNode(275 /* JSDocAllType */); + function parseJSDocAllType(postFixEquals) { + var result = createNode(282 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(286 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(285 /* JSDocNonNullableType */); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -15377,49 +16575,56 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(276 /* JSDocUnknownType */, pos); + var result = createNode(283 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(277 /* JSDocNullableType */, pos); + var result = createNode(284 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(280 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(161 /* TypeReference */); + var node = createNode(162 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(148 /* Parameter */); + var parameter = createNode(149 /* Parameter */); if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58 /* EqualsToken */) { + return createPostfixType(286 /* JSDocOptionalType */, type); + } + return type; } function parseTypeQuery() { - var node = createNode(164 /* TypeQuery */); + var node = createNode(165 /* TypeQuery */); parseExpected(103 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(147 /* TypeParameter */); + var node = createNode(148 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(85 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -15464,7 +16669,7 @@ var ts; isStartOfType(/*inStartOfParameter*/ true); } function parseParameter() { - var node = createNodeWithJSDoc(148 /* Parameter */); + var node = createNodeWithJSDoc(149 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); @@ -15492,15 +16697,21 @@ var ts; node.initializer = parseInitializer(); return finishNode(node); } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -15518,7 +16729,8 @@ var ts; } return false; } - function parseParameterList(flags) { + // Returns true on success. + function parseParameterList(signature, flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -15532,25 +16744,18 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1 /* Yield */)); - setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; + if (!parseExpected(19 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. @@ -15563,7 +16768,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 158 /* ConstructSignature */) { + if (kind === 159 /* ConstructSignature */) { parseExpected(94 /* NewKeyword */); } fillSignature(56 /* ColonToken */, 4 /* Type */, node); @@ -15624,7 +16829,7 @@ var ts; return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 159 /* IndexSignature */; + node.kind = 160 /* IndexSignature */; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -15634,13 +16839,13 @@ var ts; node.name = parsePropertyName(); node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 152 /* MethodSignature */; + node.kind = 153 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(56 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 150 /* PropertySignature */; + node.kind = 151 /* PropertySignature */; node.type = parseTypeAnnotation(); if (token() === 58 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt @@ -15657,7 +16862,7 @@ var ts; if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } - var idToken; + var idToken = false; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; @@ -15686,10 +16891,10 @@ var ts; } function parseTypeMember() { if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(157 /* CallSignature */); + return parseSignatureMember(158 /* CallSignature */); } if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(158 /* ConstructSignature */); + return parseSignatureMember(159 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -15702,8 +16907,20 @@ var ts; nextToken(); return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; } + function nextTokenIsDot() { + return nextToken() === 23 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 19 /* OpenParenToken */: + case 27 /* LessThanToken */: + case 23 /* DotToken */: + return true; + } + return false; + } function parseTypeLiteral() { - var node = createNode(165 /* TypeLiteral */); + var node = createNode(166 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -15729,14 +16946,14 @@ var ts; return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(147 /* TypeParameter */); + var node = createNode(148 /* TypeParameter */); node.name = parseIdentifier(); parseExpected(92 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(176 /* MappedType */); + var node = createNode(179 /* MappedType */); parseExpected(17 /* OpenBraceToken */); if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { node.readonlyToken = parseTokenNode(); @@ -15758,23 +16975,35 @@ var ts; parseExpected(18 /* CloseBraceToken */); return finishNode(node); } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(24 /* DotDotDotToken */)) { + var node = createNode(170 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 169 /* OptionalType */; + } + return type; + } function parseTupleType() { - var node = createNode(167 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(168 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(172 /* ParenthesizedType */); + var node = createNode(175 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); parseExpected(20 /* CloseParenToken */); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } @@ -15783,10 +17012,10 @@ var ts; return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(177 /* LiteralType */); + var node = createNode(180 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(196 /* PrefixUnaryExpression */); + unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } @@ -15801,12 +17030,33 @@ var ts; node.literal = expression; return finishNode(node); } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 91 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(181 /* ImportType */); + if (parseOptional(103 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(91 /* ImportKeyword */); + parseExpected(19 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(20 /* CloseParenToken */); + if (parseOptional(23 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } function nextTokenIsNumericLiteral() { return nextToken() === 8 /* NumericLiteral */; } function parseNonArrayType() { switch (token()) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 138 /* SymbolKeyword */: @@ -15817,13 +17067,15 @@ var ts; // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39 /* AsteriskToken */: - return parseJSDocAllType(); + return parseJSDocAllType(/*postfixEquals*/ false); + case 61 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(278 /* JSDocNonNullableType */); + return parseJSDocNonNullableType(); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -15845,13 +17097,15 @@ var ts; } } case 103 /* TypeOfKeyword */: - return parseTypeQuery(); + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); case 17 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); case 21 /* OpenBracketToken */: return parseTupleType(); case 19 /* OpenParenToken */: return parseParenthesizedType(); + case 91 /* ImportKeyword */: + return parseImportType(); default: return parseTypeReference(); } @@ -15859,6 +17113,7 @@ var ts; function isStartOfType(inStartOfParameter) { switch (token()) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 122 /* BooleanKeyword */: @@ -15886,6 +17141,7 @@ var ts; case 51 /* ExclamationToken */: case 24 /* DotDotDotToken */: case 126 /* InferKeyword */: + case 91 /* ImportKeyword */: return true; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); @@ -15905,34 +17161,27 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 58 /* EqualsToken */: - // only parse postfix = inside jsdoc, because it's ambiguous elsewhere - if (!(contextFlags & 1048576 /* JSDoc */)) { - return type; - } - type = createJSDocPostfixType(279 /* JSDocOptionalType */, type); - break; case 51 /* ExclamationToken */: - type = createJSDocPostfixType(278 /* JSDocNonNullableType */, type); + type = createPostfixType(285 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type - if (!(contextFlags & 1048576 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(277 /* JSDocNullableType */, type); + type = createPostfixType(284 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(175 /* IndexedAccessType */, type.pos); + var node = createNode(178 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); parseExpected(22 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(166 /* ArrayType */, type.pos); + var node = createNode(167 /* ArrayType */, type.pos); node.elementType = type; parseExpected(22 /* CloseBracketToken */); type = finishNode(node); @@ -15944,23 +17193,23 @@ var ts; } return type; } - function createJSDocPostfixType(kind, type) { + function createPostfixType(kind, type) { nextToken(); var postfix = createNode(kind, type.pos); postfix.type = type; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(174 /* TypeOperator */); + var node = createNode(177 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(171 /* InferType */); + var node = createNode(174 /* InferType */); parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(147 /* TypeParameter */); + var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -15973,12 +17222,6 @@ var ts; return parseTypeOperator(operator); case 126 /* InferKeyword */: return parseInferType(); - case 24 /* DotDotDotToken */: { - var result = createNode(281 /* JSDocVariadicType */); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -15997,10 +17240,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(169 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(168 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { if (token() === 27 /* LessThanToken */) { @@ -16057,7 +17300,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(160 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -16079,15 +17322,12 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(163 /* ConstructorType */); + if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(170 /* ConditionalType */, type.pos); + var node = createNode(173 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); @@ -16125,7 +17365,7 @@ var ts; case 71 /* Identifier */: return true; case 91 /* ImportKeyword */: - return lookAhead(nextTokenIsOpenParenOrLessThan); + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); } @@ -16280,7 +17520,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(201 /* YieldExpression */); + var node = createNode(205 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -16302,13 +17542,13 @@ var ts; ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(191 /* ArrowFunction */, asyncModifier.pos); + node = createNode(195 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(191 /* ArrowFunction */, identifier.pos); + node = createNode(195 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(148 /* Parameter */, identifier.pos); + var parameter = createNode(149 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -16490,7 +17730,7 @@ var ts; // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] if (token() === 120 /* AsyncKeyword */) { nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { return 0 /* False */; @@ -16504,7 +17744,7 @@ var ts; return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(191 /* ArrowFunction */); + var node = createNodeWithJSDoc(195 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -16514,9 +17754,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); - // If we couldn't get parameters, we definitely could not parse out an arrow function. - if (!node.parameters) { + if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -16570,7 +17808,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(199 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -16585,14 +17823,14 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 144 /* OfKeyword */; + return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { // We either have a binary operator here, or we're finished. We call // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, // recursively call the function below, and parse binaryExpression as a rightOperand @@ -16647,85 +17885,42 @@ var ts; if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - return 7; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(198 /* BinaryExpression */, left.pos); + var node = createNode(202 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(206 /* AsExpression */, left.pos); + var node = createNode(210 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(196 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(192 /* DeleteExpression */); + var node = createNode(196 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(193 /* TypeOfExpression */); + var node = createNode(197 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(194 /* VoidExpression */); + var node = createNode(198 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -16741,7 +17936,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(195 /* AwaitExpression */); + var node = createNode(199 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -16766,7 +17961,7 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } /** @@ -16783,12 +17978,13 @@ var ts; var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 188 /* TypeAssertionExpression */) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -16881,7 +18077,7 @@ var ts; */ function parseUpdateExpression() { if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(196 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -16894,7 +18090,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(197 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -16935,14 +18131,30 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" - // For example: - // var foo3 = require("subfolder - // import * as foo1 from "module-from-node - // We want this import to be a statement rather than import call expression - sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - expression = parseTokenNode(); + if (token() === 91 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(212 /* MetaProperty */, fullStart); + node.keywordToken = 91 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } } else { expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); @@ -17009,50 +18221,34 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(183 /* PropertyAccessExpression */, expression.pos); + var node = createNode(187 /* PropertyAccessExpression */, expression.pos); node.expression = expression; parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71 /* Identifier */) { - return lhs.escapedText === rhs.escapedText; - } - if (lhs.kind === 99 /* ThisKeyword */) { - return true; - } - // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only - // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression - // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return lhs.name.escapedText === rhs.name.escapedText && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 255 /* JsxOpeningElement */) { - var node = createNode(253 /* JsxElement */, opening.pos); + if (opening.kind === 260 /* JsxOpeningElement */) { + var node = createNode(258 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } - else if (opening.kind === 258 /* JsxOpeningFragment */) { - var node = createNode(257 /* JsxFragment */, opening.pos); + else if (opening.kind === 263 /* JsxOpeningFragment */) { + var node = createNode(262 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 254 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -17067,11 +18263,11 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(198 /* BinaryExpression */, result.pos); + var badNode = createNode(202 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -17084,8 +18280,21 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; case 10 /* JsxText */: case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); @@ -17093,8 +18302,9 @@ var ts; return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -17102,36 +18312,16 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - else if (token() === 1 /* EndOfFileToken */) { - // If we hit EOF, issue the error at the tag that lacks the closing element - // rather than at the end of the file (which is useless) - if (ts.isJsxOpeningFragment(openingTag)) { - parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); - } - else { - var openingTagName = openingTag.tagName; - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - } - break; - } - else if (token() === 7 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(261 /* JsxAttributes */); + var jsxAttributes = createNode(266 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } @@ -17140,18 +18330,19 @@ var ts; parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(255 /* JsxOpeningElement */, fullStart); + node = createNode(260 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -17163,9 +18354,10 @@ var ts; parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(254 /* JsxSelfClosingElement */, fullStart); + node = createNode(259 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -17179,7 +18371,7 @@ var ts; var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(183 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -17187,7 +18379,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(263 /* JsxExpression */); + var node = createNode(268 /* JsxExpression */); if (!parseExpected(17 /* OpenBraceToken */)) { return undefined; } @@ -17209,7 +18401,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(260 /* JsxAttribute */); + var node = createNode(265 /* JsxAttribute */); node.name = parseIdentifierName(); if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { @@ -17224,7 +18416,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(262 /* JsxSpreadAttribute */); + var node = createNode(267 /* JsxSpreadAttribute */); parseExpected(17 /* OpenBraceToken */); parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); @@ -17232,7 +18424,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(256 /* JsxClosingElement */); + var node = createNode(261 /* JsxClosingElement */); parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -17245,11 +18437,10 @@ var ts; return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(259 /* JsxClosingFragment */); + var node = createNode(264 /* JsxClosingFragment */); parseExpected(28 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { - var unexpectedTagName = parseJsxElementName(); - parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29 /* GreaterThanToken */); @@ -17261,7 +18452,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(188 /* TypeAssertionExpression */); + var node = createNode(192 /* TypeAssertionExpression */); parseExpected(27 /* LessThanToken */); node.type = parseType(); parseExpected(29 /* GreaterThanToken */); @@ -17272,7 +18463,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(183 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -17280,40 +18471,48 @@ var ts; } if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(207 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(184 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - // It's not uncommon for a user to write: "new Type[]". - // Check for that common pattern and report a better error message. - if (token() !== 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); + if (token() === 22 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteral(argument)) { + argument.text = internIdentifier(argument.text); } + indexedAccess.argumentExpression = argument; } parseExpected(22 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } - if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(187 /* TaggedTemplateExpression */, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); continue; } return expression; } } + function isTemplateStartOfTaggedTemplate() { + return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); @@ -17326,7 +18525,11 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(185 /* CallExpression */, expression.pos); + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -17334,7 +18537,7 @@ var ts; continue; } else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(185 /* CallExpression */, expression.pos); + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -17367,8 +18570,10 @@ var ts; function canFollowTypeArgumentsInExpression() { switch (token()) { case 19 /* OpenParenToken */: // foo( - // this case are the only case where this token can legally follow a type argument - // list. So we definitely want to treat this as a type arg list. + case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 14 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. case 23 /* DotToken */: // foo. case 20 /* CloseParenToken */: // foo) case 22 /* CloseBracketToken */: // foo] @@ -17431,7 +18636,7 @@ var ts; case 89 /* FunctionKeyword */: return parseFunctionExpression(); case 94 /* NewKeyword */: - return parseNewExpression(); + return parseNewExpressionOrNewDotTarget(); case 41 /* SlashToken */: case 63 /* SlashEqualsToken */: if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { @@ -17444,28 +18649,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(189 /* ParenthesizedExpression */); + var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(202 /* SpreadElement */); + var node = createNode(206 /* SpreadElement */); parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(204 /* OmittedExpression */) : + token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(181 /* ArrayLiteralExpression */); + var node = createNode(185 /* ArrayLiteralExpression */); parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17477,17 +18682,17 @@ var ts; function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 270 /* SpreadAssignment */; + node.kind = 275 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 155 /* GetAccessor */); + return parseAccessorDeclaration(node, 156 /* GetAccessor */); } if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* SetAccessor */); + return parseAccessorDeclaration(node, 157 /* SetAccessor */); } var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -17504,7 +18709,7 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - node.kind = 269 /* ShorthandPropertyAssignment */; + node.kind = 274 /* ShorthandPropertyAssignment */; var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; @@ -17512,14 +18717,14 @@ var ts; } } else { - node.kind = 268 /* PropertyAssignment */; + node.kind = 273 /* PropertyAssignment */; parseExpected(56 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(182 /* ObjectLiteralExpression */); + var node = createNode(186 /* ObjectLiteralExpression */); parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17538,7 +18743,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(190 /* FunctionExpression */); + var node = createNodeWithJSDoc(194 /* FunctionExpression */); node.modifiers = parseModifiers(); parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); @@ -17559,18 +18764,30 @@ var ts; function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } - function parseNewExpression() { + function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); parseExpected(94 /* NewKeyword */); if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(208 /* MetaProperty */, fullStart); + var node_2 = createNode(212 /* MetaProperty */, fullStart); node_2.keywordToken = 94 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } - var node = createNode(186 /* NewExpression */, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(190 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; if (node.typeArguments || token() === 19 /* OpenParenToken */) { node.arguments = parseArgumentList(); } @@ -17578,7 +18795,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(211 /* Block */); + var node = createNode(216 /* Block */); if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17611,12 +18828,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(213 /* EmptyStatement */); + var node = createNode(218 /* EmptyStatement */); parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(215 /* IfStatement */); + var node = createNode(220 /* IfStatement */); parseExpected(90 /* IfKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -17626,7 +18843,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(216 /* DoStatement */); + var node = createNode(221 /* DoStatement */); parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); parseExpected(106 /* WhileKeyword */); @@ -17641,7 +18858,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(217 /* WhileStatement */); + var node = createNode(222 /* WhileStatement */); parseExpected(106 /* WhileKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -17664,8 +18881,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(144 /* OfKeyword */) : parseOptional(144 /* OfKeyword */)) { - var forOfStatement = createNode(220 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { + var forOfStatement = createNode(225 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -17673,14 +18890,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(219 /* ForInStatement */, pos); + var forInStatement = createNode(224 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(218 /* ForStatement */, pos); + var forStatement = createNode(223 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(25 /* SemicolonToken */); if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { @@ -17698,7 +18915,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 222 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -17706,7 +18923,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(223 /* ReturnStatement */); + var node = createNode(228 /* ReturnStatement */); parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -17715,16 +18932,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(224 /* WithStatement */); + var node = createNode(229 /* WithStatement */); parseExpected(107 /* WithKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - node.statement = doInsideOfContext(4194304 /* InWithStatement */, parseStatement); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(264 /* CaseClause */); + var node = createNode(269 /* CaseClause */); parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(56 /* ColonToken */); @@ -17732,7 +18949,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(265 /* DefaultClause */); + var node = createNode(270 /* DefaultClause */); parseExpected(79 /* DefaultKeyword */); parseExpected(56 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -17742,12 +18959,12 @@ var ts; return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(225 /* SwitchStatement */); + var node = createNode(230 /* SwitchStatement */); parseExpected(98 /* SwitchKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(239 /* CaseBlock */); + var caseBlock = createNode(244 /* CaseBlock */); parseExpected(17 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(18 /* CloseBraceToken */); @@ -17762,7 +18979,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(227 /* ThrowStatement */); + var node = createNode(232 /* ThrowStatement */); parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -17770,7 +18987,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(228 /* TryStatement */); + var node = createNode(233 /* TryStatement */); parseExpected(102 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -17783,7 +19000,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(267 /* CatchClause */); + var result = createNode(272 /* CatchClause */); parseExpected(74 /* CatchKeyword */); if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -17797,7 +19014,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(229 /* DebuggerStatement */); + var node = createNode(234 /* DebuggerStatement */); parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -17809,12 +19026,12 @@ var ts; var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 226 /* LabeledStatement */; + node.kind = 231 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 214 /* ExpressionStatement */; + node.kind = 219 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -17886,7 +19103,7 @@ var ts; return false; } continue; - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: nextToken(); return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; case 91 /* ImportKeyword */: @@ -17940,7 +19157,7 @@ var ts; case 87 /* FinallyKeyword */: return true; case 91 /* ImportKeyword */: - return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); case 76 /* ConstKeyword */: case 84 /* ExportKeyword */: return isStartOfDeclaration(); @@ -17950,7 +19167,7 @@ var ts; case 129 /* ModuleKeyword */: case 130 /* NamespaceKeyword */: case 139 /* TypeKeyword */: - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 114 /* PublicKeyword */: @@ -17981,16 +19198,16 @@ var ts; case 17 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(230 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(230 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); } break; case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(232 /* FunctionDeclaration */)); + return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(233 /* ClassDeclaration */)); + return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); case 90 /* IfKeyword */: return parseIfStatement(); case 81 /* DoKeyword */: @@ -18000,9 +19217,9 @@ var ts; case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(221 /* ContinueStatement */); + return parseBreakOrContinueStatement(226 /* ContinueStatement */); case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(222 /* BreakStatement */); + return parseBreakOrContinueStatement(227 /* BreakStatement */); case 96 /* ReturnKeyword */: return parseReturnStatement(); case 107 /* WithKeyword */: @@ -18036,7 +19253,7 @@ var ts; case 117 /* AbstractKeyword */: case 115 /* StaticKeyword */: case 132 /* ReadonlyKeyword */: - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -18054,9 +19271,9 @@ var ts; if (ts.some(node.modifiers, isDeclareModifier)) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var m = _a[_i]; - m.flags |= 2097152 /* Ambient */; + m.flags |= 4194304 /* Ambient */; } - return doInsideOfContext(2097152 /* Ambient */, function () { return parseDeclarationWorker(node); }); + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); } else { return parseDeclarationWorker(node); @@ -18078,7 +19295,7 @@ var ts; return parseTypeAliasDeclaration(node); case 83 /* EnumKeyword */: return parseEnumDeclaration(node); - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: case 129 /* ModuleKeyword */: case 130 /* NamespaceKeyword */: return parseModuleDeclaration(node); @@ -18099,12 +19316,13 @@ var ts; if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(251 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; // TODO: GH#18217 } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -18121,16 +19339,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token() === 26 /* CommaToken */) { - return createNode(204 /* OmittedExpression */); + return createNode(208 /* OmittedExpression */); } - var node = createNode(180 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(180 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -18146,14 +19364,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(178 /* ObjectBindingPattern */); + var node = createNode(182 /* ObjectBindingPattern */); parseExpected(17 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(179 /* ArrayBindingPattern */); + var node = createNode(183 /* ArrayBindingPattern */); parseExpected(21 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(22 /* CloseBracketToken */); @@ -18175,7 +19393,7 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(230 /* VariableDeclaration */); + var node = createNode(235 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); if (allowExclamation && node.name.kind === 71 /* Identifier */ && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { @@ -18188,7 +19406,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(231 /* VariableDeclarationList */); + var node = createNode(236 /* VariableDeclarationList */); switch (token()) { case 104 /* VarKeyword */: break; @@ -18211,7 +19429,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 144 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -18226,13 +19444,13 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 212 /* VariableStatement */; + node.kind = 217 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 232 /* FunctionDeclaration */; + node.kind = 237 /* FunctionDeclaration */; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); @@ -18243,14 +19461,14 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 154 /* Constructor */; + node.kind = 155 /* Constructor */; parseExpected(123 /* ConstructorKeyword */); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 153 /* MethodDeclaration */; + node.kind = 154 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; @@ -18259,7 +19477,7 @@ var ts; return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 151 /* PropertyDeclaration */; + node.kind = 152 /* PropertyDeclaration */; if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } @@ -18297,18 +19515,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57 /* AtToken */) { @@ -18323,7 +19529,7 @@ var ts; // public foo() ... // true // public @dec blah ... // true; we will then report an error later // export public ... // true; we will then report an error later - if (isClassMemberModifier(idToken)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -18376,7 +19582,7 @@ var ts; if (!parseOptional(57 /* AtToken */)) { break; } - var decorator = createNode(149 /* Decorator */, decoratorStart); + var decorator = createNode(150 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -18426,7 +19632,7 @@ var ts; } function parseClassElement() { if (token() === 25 /* SemicolonToken */) { - var result = createNode(210 /* SemicolonClassElement */); + var result = createNode(215 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -18434,10 +19640,10 @@ var ts; node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 155 /* GetAccessor */); + return parseAccessorDeclaration(node, 156 /* GetAccessor */); } if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* SetAccessor */); + return parseAccessorDeclaration(node, 157 /* SetAccessor */); } if (token() === 123 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); @@ -18460,13 +19666,13 @@ var ts; return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 203 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 233 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; @@ -18508,17 +19714,15 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(266 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(271 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(205 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); @@ -18535,7 +19739,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 234 /* InterfaceDeclaration */; + node.kind = 239 /* InterfaceDeclaration */; parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -18544,7 +19748,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 235 /* TypeAliasDeclaration */; + node.kind = 240 /* TypeAliasDeclaration */; parseExpected(139 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -18558,13 +19762,13 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNodeWithJSDoc(271 /* EnumMember */); + var node = createNodeWithJSDoc(276 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 236 /* EnumDeclaration */; + node.kind = 241 /* EnumDeclaration */; parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(17 /* OpenBraceToken */)) { @@ -18577,7 +19781,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(238 /* ModuleBlock */); + var node = createNode(243 /* ModuleBlock */); if (parseExpected(17 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(18 /* CloseBraceToken */); @@ -18588,7 +19792,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 237 /* ModuleDeclaration */; + node.kind = 242 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; @@ -18600,8 +19804,8 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 237 /* ModuleDeclaration */; - if (token() === 143 /* GlobalKeyword */) { + node.kind = 242 /* ModuleDeclaration */; + if (token() === 144 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -18620,7 +19824,7 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 143 /* GlobalKeyword */) { + if (token() === 144 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } @@ -18646,7 +19850,7 @@ var ts; return nextToken() === 41 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 240 /* NamespaceExportDeclaration */; + node.kind = 245 /* NamespaceExportDeclaration */; parseExpected(118 /* AsKeyword */); parseExpected(130 /* NamespaceKeyword */); node.name = parseIdentifier(); @@ -18659,12 +19863,12 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 142 /* FromKeyword */) { + if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 242 /* ImportDeclaration */; + node.kind = 247 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; @@ -18672,14 +19876,14 @@ var ts; token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(142 /* FromKeyword */); + parseExpected(143 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 241 /* ImportEqualsDeclaration */; + node.kind = 246 /* ImportEqualsDeclaration */; node.name = identifier; parseExpected(58 /* EqualsToken */); node.moduleReference = parseModuleReference(); @@ -18693,7 +19897,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(243 /* ImportClause */, fullStart); + var importClause = createNode(248 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -18703,7 +19907,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(245 /* NamedImports */); + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); } return finishNode(importClause); } @@ -18713,7 +19917,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(252 /* ExternalModuleReference */); + var node = createNode(257 /* ExternalModuleReference */); parseExpected(133 /* RequireKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -18736,7 +19940,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(244 /* NamespaceImport */); + var namespaceImport = createNode(249 /* NamespaceImport */); parseExpected(39 /* AsteriskToken */); parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -18751,14 +19955,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 245 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(250 /* ExportSpecifier */); + return parseImportOrExportSpecifier(255 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(246 /* ImportSpecifier */); + return parseImportOrExportSpecifier(251 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -18783,25 +19987,24 @@ var ts; else { node.name = identifierName; } - if (kind === 246 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 248 /* ExportDeclaration */; + node.kind = 253 /* ExportDeclaration */; if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(142 /* FromKeyword */); + parseExpected(143 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(249 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 142 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(142 /* FromKeyword */); + if (token() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(143 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -18809,7 +20012,7 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 247 /* ExportAssignment */; + node.kind = 252 /* ExportAssignment */; if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } @@ -18821,15 +20024,31 @@ var ts; return finishNode(node); } function setExternalModuleIndicator(sourceFile) { - sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return ts.hasModifier(node, 1 /* Export */) - || node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 252 /* ExternalModuleReference */ - || node.kind === 242 /* ImportDeclaration */ - || node.kind === 247 /* ExportAssignment */ - || node.kind === 248 /* ExportDeclaration */ - ? node - : undefined; - }); + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ + || node.kind === 247 /* ImportDeclaration */ + || node.kind === 252 /* ExportAssignment */ + || node.kind === 253 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -18879,9 +20098,9 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(274 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); - result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { parseExpected(18 /* CloseBraceToken */); } @@ -18899,6 +20118,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -18916,7 +20136,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -18927,28 +20146,28 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } var tags; var tagsPos; var tagsEnd; var comments = []; - var result; - // Check for /** (JSDoc opening part) - if (!isJsDocStart(content, start)) { - return result; - } // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { + return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. var state = 1 /* SawAsterisk */; @@ -18962,21 +20181,19 @@ var ts; comments.push(text); indent += text.length; } - var t = nextJSDocToken(); - while (t === 5 /* WhitespaceTrivia */) { - t = nextJSDocToken(); - } - if (t === 4 /* NewLineTrivia */) { + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; indent = 0; - t = nextJSDocToken(); } loop: while (true) { - switch (t) { + switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` @@ -19032,13 +20249,12 @@ var ts; pushComment(scanner.getTokenText()); break; } - t = nextJSDocToken(); + nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - result = createJSDocComment(); + return createJSDocComment(); }); - return result; function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { comments.shift(); @@ -19049,19 +20265,30 @@ var ts; comments.pop(); } } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */; - } function createJSDocComment() { - var result = createNode(282 /* JSDocComment */, start); + var result = createNode(289 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } @@ -19073,52 +20300,48 @@ var ts; nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); - if (!tagName) { - return; - } var tag; - if (tagName) { - switch (tagName.escapedText) { - case "augments": - case "extends": - tag = parseAugmentsTag(atToken, tagName); - break; - case "class": - case "constructor": - tag = parseClassTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "this": + tag = parseThisTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } - else { - tag = parseUnknownTag(atToken, tagName); + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); } - if (!tag) { - // a badly malformed tag should not be added to the list of tags - return; - } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + return tag; } function parseTagComments(indent) { var comments = []; @@ -19160,6 +20383,16 @@ var ts; indent += whitespace.length; } break; + case 17 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; case 39 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token @@ -19181,12 +20414,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(284 /* JSDocTag */, atToken.pos); + var result = createNode(292 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -19201,6 +20437,10 @@ var ts; return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { + if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' var isBracketed = parseOptional(21 /* OpenBracketToken */); var name = parseJSDocEntityName(); @@ -19218,13 +20458,13 @@ var ts; switch (node.kind) { case 135 /* ObjectKeyword */: return true; - case 166 /* ArrayType */: + case 167 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target) { + function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespace(); @@ -19233,10 +20473,13 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 /* Parameter */ ? - createNode(287 /* JSDocParameterTag */, atToken.pos) : - createNode(292 /* JSDocPropertyTag */, atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + var result = target === 1 /* Property */ ? + createNode(302 /* JSDocPropertyTag */, atToken.pos) : + createNode(296 /* JSDocParameterTag */, atToken.pos); + var comment; + if (indent !== undefined) + comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -19247,22 +20490,25 @@ var ts; result.name = name; result.isNameFirst = isNameFirst; result.isBracketed = isBracketed; + result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name) { + function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(274 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - children = ts.append(children, child); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } } if (children) { - jsdocTypeLiteral = createNode(283 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 166 /* ArrayType */) { + if (typeExpression.type.kind === 167 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -19271,27 +20517,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(288 /* JSDocReturnTag */, atToken.pos); + var result = createNode(297 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289 /* JSDocTypeTag */, atToken.pos); + var result = createNode(299 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(285 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -19299,7 +20545,7 @@ var ts; } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(205 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); @@ -19309,9 +20555,9 @@ var ts; return res; } function parsePropertyAccessEntityNameExpression() { - var node = parseJSDocIdentifierName(/*createIfMissing*/ true); + var node = parseJSDocIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var prop = createNode(183 /* PropertyAccessExpression */, node.pos); + var prop = createNode(187 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); @@ -19319,42 +20565,41 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(286 /* JSDocClassTag */, atToken.pos); + var tag = createNode(294 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseThisTag(atToken, tagName) { + var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(291 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = scanner.getStartPos(); - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { + while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(283 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 289 /* JSDocTypeTag */) { + if (child.kind === 299 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -19367,29 +20612,76 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 166 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(237 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return finishNode(jsDocNamespaceNode); + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(291 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(57 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 297 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -19404,6 +20696,9 @@ var ts; } return a.escapedText === b.escapedText; } + function parseChildPropertyTag() { + return parseChildParameterOrPropertyTag(1 /* Property */); + } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; var seenAsterisk = false; @@ -19412,8 +20707,9 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 287 /* JSDocParameterTag */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -19445,78 +20741,67 @@ var ts; nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); - if (!tagName) { - return false; - } var t; switch (tagName.escapedText) { case "type": - return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0 /* Property */; + t = 1 /* Property */; break; case "arg": case "argument": case "param": - t = 1 /* Parameter */; + t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target); + var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); tag.comment = parseTagComments(tag.end - tag.pos); return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.some(tags, ts.isJSDocTemplateTag)) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 17 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); } - // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); - while (true) { - var typeParameter = createNode(147 /* TypeParameter */); - var name = parseJSDocIdentifierNameWithOptionalBraces(); + do { + skipWhitespace(); + var typeParameter = createNode(148 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 26 /* CommaToken */) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } + } while (parseOptionalJsdoc(26 /* CommaToken */)); + if (constraint) { + ts.first(typeParameters).constraint = constraint.type; } - var result = createNode(290 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; } - function parseJSDocIdentifierNameWithOptionalBraces() { - var parsedBrace = parseOptional(17 /* OpenBraceToken */); - var res = parseJSDocIdentifierName(); - if (parsedBrace) { - parseExpected(18 /* CloseBraceToken */); - } - return res; - } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } function parseJSDocEntityName() { - var entity = parseJSDocIdentifierName(/*createIfMissing*/ true); + var entity = parseJSDocIdentifierName(); if (parseOptional(21 /* OpenBracketToken */)) { parseExpected(22 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. @@ -19524,7 +20809,7 @@ var ts; // but it's not worth it to enforce that restriction. } while (parseOptional(23 /* DotToken */)) { - var name = parseJSDocIdentifierName(/*createIfMissing*/ true); + var name = parseJSDocIdentifierName(); if (parseOptional(21 /* OpenBracketToken */)) { parseExpected(22 /* CloseBracketToken */); } @@ -19532,21 +20817,14 @@ var ts; } return entity; } - function parseJSDocIdentifierName(createIfMissing) { - if (createIfMissing === void 0) { createIfMissing = false; } + function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - if (createIfMissing) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71 /* Identifier */, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -19654,7 +20932,7 @@ var ts; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); + visitNode(jsDocComment); } } checkNodePositions(node, aggressiveChecks); @@ -19750,10 +21028,17 @@ var ts; function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { var pos_2 = node.pos; - forEachChild(node, function (child) { + var visitNode_1 = function (child) { ts.Debug.assert(child.pos >= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -19778,6 +21063,12 @@ var ts; // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -19842,15 +21133,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -19859,15 +21150,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { // Missing nodes are effectively invisible to us. We never even consider them @@ -20029,9 +21311,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -20055,7 +21339,7 @@ var ts; context.pragmas = ts.createMap(); for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { var pragma = pragmas_1[_i]; - if (context.pragmas.has(pragma.name)) { + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 var currentValue = context.pragmas.get(pragma.name); if (currentValue instanceof Array) { currentValue.push(pragma.args); @@ -20074,6 +21358,7 @@ var ts; context.checkJsDirective = undefined; context.referencedFiles = []; context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; context.amdDependencies = []; context.hasNoDefaultLib = false; context.pragmas.forEach(function (entryOrList, key) { @@ -20083,13 +21368,18 @@ var ts; case "reference": { var referencedFiles_1 = context.referencedFiles; var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } else if (arg.arguments.types) { typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } else if (arg.arguments.path) { referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); } @@ -20100,10 +21390,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 break; } case "amd-module": { @@ -20126,7 +21413,7 @@ var ts; case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" ts.forEach(ts.toArray(entryOrList), function (entry) { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -20154,7 +21441,7 @@ var ts; var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; function extractPragmas(pragmas, range, text) { - var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks var pragma = ts.commentPragmas[name]; @@ -20191,14 +21478,16 @@ var ts; } return; } - var singleLine = singleLinePragmaRegEx.exec(text); + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); if (singleLine) { return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); } - var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) - var multiLineMatch; - while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { - addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } } } function addPragmaForMatch(pragmas, range, kind, match) { @@ -20235,3495 +21524,2292 @@ var ts; } return argMap; } -})(ts || (ts = {})); -/// -/// -/* @internal */ -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) { - return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; - } - ts.getModuleInstanceState = getModuleInstanceState; - function getModuleInstanceStateWorker(node) { - // A module is uninstantiated if it contains only - switch (node.kind) { - // 1. interface declarations, type alias declarations - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - return 0 /* NonInstantiated */; - // 2. const enum declarations - case 236 /* EnumDeclaration */: - if (ts.isConst(node)) { - return 2 /* ConstEnumOnly */; - } - break; - // 3. non-exported import declarations - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - if (!(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - break; - // 4. other uninstantiated module declarations. - case 238 /* ModuleBlock */: { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - var childState = getModuleInstanceStateWorker(n); - switch (childState) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; - default: - ts.Debug.assertNever(childState); - } - }); - return state_1; - } - case 237 /* ModuleDeclaration */: - return getModuleInstanceState(node); - case 71 /* Identifier */: - // Only jsdoc typedef definition can exist in jsdoc namespace, and it should - // be considered the same as type alias - if (node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - } - return 1 /* Instantiated */; - } - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - // The current node is the container of a control flow path. The current control flow should - // be saved and restored, and a new control flow initialized within the container. - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by control flow analysis - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - // state used for emit helpers - var emitFlags; - // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places or if we hit a class/namespace - // or if compiler options contain alwaysStrict. - var inStrictMode; - var symbolCount = 0; - var Symbol; // tslint:disable-line variable-name - var classifiableNames; - var unreachableFlow = { flags: 1 /* Unreachable */ }; - var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; - // state used to aggregate transform flags during bind. - var subtreeTransformFlags = 0 /* None */; - var skipTransformFlagAggregation; - /** - * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) - * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) - * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. - */ - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { - return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); - } - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createUnderscoreEscapedMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0 /* None */; - subtreeTransformFlags = 0 /* None */; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { - // bind in strict mode source files with alwaysStrict option - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createSymbolTable(); - } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createSymbolTable(); - } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237 /* ModuleDeclaration */)) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } - } - } - // Should not be called on a declaration with a computed property name, - // unless it is a well known Symbol. - function getDeclarationName(node) { - if (node.kind === 247 /* ExportAssignment */) { - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - } - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - var moduleName = ts.getTextOfIdentifierOrLiteral(name); - return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); - } - if (name.kind === 146 /* ComputedPropertyName */) { - var nameExpression = name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { - return ts.escapeLeadingUnderscores(nameExpression.text); - } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; - } - switch (node.kind) { - case 154 /* Constructor */: - return "__constructor" /* Constructor */; - case 162 /* FunctionType */: - case 157 /* CallSignature */: - return "__call" /* Call */; - case 163 /* ConstructorType */: - case 158 /* ConstructSignature */: - return "__new" /* New */; - case 159 /* IndexSignature */: - return "__index" /* Index */; - case 248 /* ExportDeclaration */: - return "__export" /* ExportStar */; - case 198 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { - // module.exports = ... - return "export=" /* ExportEquals */; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); - case 280 /* JSDocFunctionType */: - return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 148 /* Parameter */: - // Parameters with names are handled at the top of this function. Parameters - // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); - var functionType = node.parent; - var index = functionType.parameters.indexOf(node); - return "arg" + index; - case 291 /* JSDocTypedefTag */: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; - } - } - function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing" /* Missing */); - } - else { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // - // If we created a new symbol, either because we didn't have a symbol with this name - // in the symbol table, or we conflicted with an existing symbol, then just add this - // node as the sole declaration of the new symbol. - // - // Otherwise, we'll be merging into a compatible existing symbol (for example when - // you have multiple 'vars' with the same name in the same container). In this case - // just add this node into the declarations list of the symbol. - symbol = symbolTable.get(name); - if (includes & 2885600 /* Classifiable */) { - classifiableNames.set(name, true); - } - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - if (isReplaceableByMethod) - symbol.isReplaceableByMethod = true; - } - else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { - // A symbol already exists, so don't add this as a declaration. - return symbol; - } - else if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - else { - if (ts.isNamedDeclaration(node)) { - node.name.parent = node; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { - message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; - } - if (symbol.declarations && symbol.declarations.length) { - // If the current node is a default export of some sort, then check if - // there are any other default exports that we need to error on. - // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. - // Error on multiple export default in the following case: - // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default - // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 247 /* ExportAssignment */ && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - if (symbol.parent) { - ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); - } - else { - symbol.parent = parent; - } - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; - if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 250 /* ExportSpecifier */ || (node.kind === 241 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, - // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge - // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation - // and this case is specially handled. Module augmentations should only be merged with original module definition - // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 291 /* JSDocTypedefTag */) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; - var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - } - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name - // used for a container is unique. - function bindContainer(node, containerFlags) { - // Before we recurse into a node's children, we first save the existing parent, container - // and block-container. Then after we pop out of processing the children, we restore - // these saved values. - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - // Depending on what kind of node this is, we may have to adjust the current container - // and block-container. If the current node is a container, then it is automatically - // considered the current block-container as well. Also, for containers that we know - // may contain locals, we proactively initialize the .locals field. We do this because - // it's highly likely that the .locals will be needed to place some child in (for example, - // a parameter, or variable declaration). - // - // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped - // variable in them. We don't want to end up allocating an object for every 'block' we - // run into when most of them won't be necessary. - // - // Finally, if this is a block-container, then we clear out any existing .locals object - // it may contain within it. This happens in incremental scenarios. Because we can be - // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidentally move any stale data forward from - // a previous compilation. - if (containerFlags & 1 /* IsContainer */) { - container = blockScopeContainer = node; - if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createSymbolTable(); - } - addToContainerChain(container); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); - // A non-async IIFE is considered part of the containing control flow. Return statements behave - // similarly to break statements that exit to a label just past the statement body. - if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { - currentFlow.container = node; - } - } - // We create a return control flow graph for IIFEs and constructors. For constructors - // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 154 /* Constructor */ ? createBranchLabel() : undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - // Reset all reachability check related flags on node (for incremental scenarios) - node.flags &= ~1408 /* ReachabilityAndEmitFlags */; - if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 128 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 256 /* HasExplicitReturn */; - } - if (node.kind === 272 /* SourceFile */) { - node.flags |= emitFlags; - } - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 154 /* Constructor */) { - node.returnFlowNode = currentFlow; - } - } - if (!isIIFE) { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64 /* IsInterface */) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0 /* None */; - var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; - } - nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 217 /* WhileStatement */: - bindWhileStatement(node); - break; - case 216 /* DoStatement */: - bindDoStatement(node); - break; - case 218 /* ForStatement */: - bindForStatement(node); - break; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 215 /* IfStatement */: - bindIfStatement(node); - break; - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 228 /* TryStatement */: - bindTryStatement(node); - break; - case 225 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 239 /* CaseBlock */: - bindCaseBlock(node); - break; - case 264 /* CaseClause */: - bindCaseClause(node); - break; - case 226 /* LabeledStatement */: - bindLabeledStatement(node); - break; - case 196 /* PrefixUnaryExpression */: - bindPrefixUnaryExpressionFlow(node); - break; - case 197 /* PostfixUnaryExpression */: - bindPostfixUnaryExpressionFlow(node); - break; - case 198 /* BinaryExpression */: - bindBinaryExpressionFlow(node); - break; - case 192 /* DeleteExpression */: - bindDeleteExpressionFlow(node); - break; - case 199 /* ConditionalExpression */: - bindConditionalExpressionFlow(node); - break; - case 230 /* VariableDeclaration */: - bindVariableDeclarationFlow(node); - break; - case 185 /* CallExpression */: - bindCallExpressionFlow(node); - break; - case 282 /* JSDocComment */: - bindJSDocComment(node); - break; - case 291 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 183 /* PropertyAccessExpression */: - return isNarrowableReference(expr); - case 185 /* CallExpression */: - return hasNarrowableArgument(expr); - case 189 /* ParenthesizedExpression */: - return isNarrowingExpression(expr.expression); - case 198 /* BinaryExpression */: - return isNarrowingBinaryExpression(expr); - case 196 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { return false; } - function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 183 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + if (lhs.kind === 71 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 183 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); - } - function isNarrowableInOperands(left, right) { - return ts.isStringLiteralLike(left) && isNarrowingExpression(right); - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: - return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: - return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 189 /* ParenthesizedExpression */: - return isNarrowableOperand(expr.expression); - case 198 /* BinaryExpression */: - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4 /* BranchLabel */, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8 /* LoopLabel */, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1 /* Unreachable */) { - return antecedent; - } - if (!expression) { - return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; - } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(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 }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; - return res; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 215 /* IfStatement */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: - return parent.expression === node; - case 218 /* ForStatement */: - case 199 /* ConditionalExpression */: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 189 /* ParenthesizedExpression */) { - node = node.expression; - } - else if (node.kind === 196 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { - node = node.operand; - } - else { - return node.kind === 198 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 189 /* ParenthesizedExpression */ || - node.parent.kind === 196 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 226 /* LabeledStatement */ - ? ts.lastOrUndefined(activeLabels) - : undefined; - // if do statement is wrapped in labeled statement then target labels for break/continue with or without - // label should be the same - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 220 /* ForOfStatement */) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 231 /* VariableDeclarationList */) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 223 /* ReturnStatement */) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 222 /* BreakStatement */ ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.escapedText); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block - if (!(currentFlow.flags & 1 /* Unreachable */)) { - if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 265 /* DefaultClause */; }); - // We mark a switch statement as possibly exhaustive if it has no default clause and if all - // case clauses have unreachable end points (e.g. they all return). - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 216 /* DoStatement */) { - // do statement sets current flow inside bindDoStatement - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 181 /* ArrayLiteralExpression */) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 202 /* SpreadElement */) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 182 /* ObjectLiteralExpression */) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 268 /* PropertyAssignment */) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 269 /* ShorthandPropertyAssignment */) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 270 /* SpreadAssignment */) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 184 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 183 /* PropertyAccessExpression */) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 291 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - // If the target of the call expression is a function expression or arrow function we have - // an immediately invoked function expression (IIFE). Initialize the flowNode property to - // the current control flow (which includes evaluation of the IIFE arguments). - var expr = node.expression; - while (expr.kind === 189 /* ParenthesizedExpression */) { - expr = expr.expression; - } - if (expr.kind === 190 /* FunctionExpression */ || expr.kind === 191 /* ArrowFunction */) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 183 /* PropertyAccessExpression */) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 182 /* ObjectLiteralExpression */: - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 261 /* JsxAttributes */: - return 1 /* IsContainer */; - case 234 /* InterfaceDeclaration */: - return 1 /* IsContainer */ | 64 /* IsInterface */; - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 176 /* MappedType */: - return 1 /* IsContainer */ | 32 /* HasLocals */; - case 272 /* SourceFile */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 153 /* MethodDeclaration */: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; - } - // falls through - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 157 /* CallSignature */: - case 280 /* JSDocFunctionType */: - case 162 /* FunctionType */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 163 /* ConstructorType */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 238 /* ModuleBlock */: - return 4 /* IsControlFlowContainer */; - case 151 /* PropertyDeclaration */: - return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 267 /* CatchClause */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 239 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 211 /* Block */: - // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Otherwise 'x' - // would not appear to be a redeclaration of a block scoped local in the following - // example: - // - // function foo() { - // var x; - // let x; - // } - // - // If we placed 'var x' into the function locals and 'let x' into the locals of - // the block, then there would be no collision. - // - // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision - // conflict. - return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - // Modules, source files, and classes need specialized handling for how their - // members are declared (for example, a member of a class will go into a specific - // symbol table depending on if it is static or not). We defer to specialized - // handlers to take care of declaring these child members. - case 237 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 272 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 236 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 182 /* ObjectLiteralExpression */: - case 234 /* InterfaceDeclaration */: - case 261 /* JsxAttributes */: - // Interface/Object-types always have their children added to the 'members' of - // their container. They are only accessible through an instance of their - // container, and are never in scope otherwise (even inside the body of the - // object / type / interface declaring them). An exception is type parameters, - // which are in scope without qualification (similar to 'locals'). - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* JSDocFunctionType */: - case 235 /* TypeAliasDeclaration */: - case 176 /* MappedType */: - // All the children of these container types are never visible through another - // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, - // they're only accessed 'lexically' (i.e. from code that exists underneath - // their container in the tree). To accomplish this, we simply add their declared - // symbol to the 'locals' of the container. These symbols can then be found as - // the type checker walks up the containers, checking them for matching names. - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32 /* Static */) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 272 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 272 /* SourceFile */ || body.kind === 238 /* ModuleBlock */)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 248 /* ExportDeclaration */ || stat.kind === 247 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (node.flags & 2097152 /* Ambient */ && !hasExportDeclarations(node)) { - node.flags |= 32 /* ExportContext */; - } - else { - node.flags &= ~32 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1 /* Export */)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isModuleAugmentationExternal(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); - file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0 /* NonInstantiated */) { - var symbol = node.symbol; - // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only - symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) - // Current must be `const enum` only - && state === 2 /* ConstEnumOnly */ - // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) - && symbol.constEnumOnlyModule !== false; - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); - return state; - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createSymbolTable(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 270 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 268 /* PropertyAssignment */ || prop.kind === 269 /* ShorthandPropertyAssignment */ || prop.kind === 153 /* MethodDeclaration */ - ? 1 /* Property */ - : 2 /* Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { - symbol.parent = container.symbol; - } - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 237 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 272 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // falls through - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createSymbolTable(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && - !ts.isIdentifierName(node) && - !(node.flags & 2097152 /* Ambient */)) { - // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { - // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its - // UnaryExpression is a direct reference to a variable, function argument, or function name - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES2015 */) { - // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 272 /* SourceFile */ && - blockScopeContainer.kind !== 237 /* ModuleDeclaration */ && - !ts.isFunctionLike(blockScopeContainer)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - // Grammar checking - // The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression - // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - // Grammar checking - if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - // Even though in the AST the jsdoc @typedef node belongs to the current node, - // its symbol might be in the same scope with the current node's symbol. Consider: - // - // /** @typedef {string | number} MyType */ - // function foo(); - // - // Here the current node is "foo", which is a container, but the scope of "MyType" should - // not be inside "foo". Therefore we always bind @typedef before bind the parent node, - // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); - // First we bind declaration nodes to a symbol if possible. We'll both create a symbol - // and then potentially add the symbol to an appropriate symbol table. Possible - // destination symbol tables are: - // - // 1) The 'exports' table of the current container's symbol. - // 2) The 'members' table of the current container's symbol. - // 3) The 'locals' table of the current container. - // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols - // (like TypeLiterals for example) will not be put in any table. - bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain - // symbols we do specialized work when we recurse. For example, we'll keep track of - // the current 'container' node when it changes. This helps us know which symbol table - // a local should go into for example. Since terminal nodes are known not to have - // children, as an optimization we don't process those. - if (node.kind > 144 /* LastToken */) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0 /* None */) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 291 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - /* Strict mode checks */ - case 71 /* Identifier */: - // for typedef type names with namespaces, bind the new jsdoc type symbol here - // because it requires all containing namespaces to be in effect, namely the - // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if (node.isInJSDocNamespace) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 291 /* JSDocTypedefTag */) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - break; - } - // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 269 /* ShorthandPropertyAssignment */)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 183 /* PropertyAccessExpression */: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - if (ts.isSpecialPropertyDeclaration(node)) { - bindSpecialPropertyDeclaration(node); - } - break; - case 198 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1 /* ExportsProperty */: - bindExportsPropertyAssignment(node); - break; - case 2 /* ModuleExports */: - bindModuleExportsAssignment(node); - break; - case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node.left, node); - break; - case 6 /* Prototype */: - bindPrototypeAssignment(node); - break; - case 4 /* ThisProperty */: - bindThisPropertyAssignment(node); - break; - case 5 /* Property */: - bindSpecialPropertyAssignment(node); - break; - case 0 /* None */: - // Nothing to do - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 267 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 192 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 197 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 196 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 224 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 173 /* ThisType */: - seenThisKeyword = true; - return; - case 160 /* TypePredicate */: - break; // Binding the children will handle everything - case 147 /* TypeParameter */: - return bindTypeParameter(node); - case 148 /* Parameter */: - return bindParameter(node); - case 230 /* VariableDeclaration */: - return bindVariableDeclarationOrBindingElement(node); - case 180 /* BindingElement */: - node.flowNode = currentFlow; - return bindVariableDeclarationOrBindingElement(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return bindPropertyWorker(node); - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 271 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 232 /* FunctionDeclaration */: - return bindFunctionDeclaration(node); - case 154 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 155 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 156 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 162 /* FunctionType */: - case 280 /* JSDocFunctionType */: - case 163 /* ConstructorType */: - return bindFunctionOrConstructorType(node); - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 176 /* MappedType */: - return bindAnonymousTypeWorker(node); - case 182 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return bindFunctionExpression(node); - case 185 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - // Members of classes, interfaces, and modules - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 234 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 235 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 236 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - // Jsx-attributes - case 261 /* JsxAttributes */: - return bindJsxAttributes(node); - case 260 /* JsxAttribute */: - return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); - // Imports and exports - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 240 /* NamespaceExportDeclaration */: - return bindNamespaceExportDeclaration(node); - case 243 /* ImportClause */: - return bindImportClause(node); - case 248 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 247 /* ExportAssignment */: - return bindExportAssignment(node); - case 272 /* SourceFile */: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 211 /* Block */: - if (!ts.isFunctionLike(node.parent)) { - return; - } - // falls through - case 238 /* ModuleBlock */: - return updateStrictModeStatementList(node.statements); - case 287 /* JSDocParameterTag */: - if (node.parent.kind !== 283 /* JSDocTypeLiteral */) { - break; - } - // falls through - case 292 /* JSDocPropertyTag */: - var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 279 /* JSDocOptionalType */ ? - 4 /* Property */ | 16777216 /* Optional */ : - 4 /* Property */; - return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 291 /* JSDocTypedefTag */: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - } - break; - } - } - } - function bindPropertyWorker(node) { - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - function bindAnonymousTypeWorker(node) { - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); - } - else { - var flags = node.kind === 247 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - // An export default clause with an EntityNameExpression exports all meanings of that identifier - ? 2097152 /* Alias */ - // An export default clause with any other expression exports a value - : 4 /* Property */; - // If there is an `export default x;` alias declaration, can't `export default` anything else. - // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 272 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - // Export * in some sort of block construct - bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); - } - else if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - // When we create a property via 'exports.foo = bar', the 'exports.foo' property access - // expression is the declaration - setCommonJsModuleIndicator(node); - var lhs = node.left; - var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { - if (!original) { - return undefined; - } - var s = ts.getJSInitializerSymbol(original); - addDeclarationToSymbol(s, id, 1536 /* Module */ | 67108864 /* JSContainer */); - return s; - }); - if (symbol) { - declareSymbol(symbol.exports, symbol, lhs, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); - } - } - function bindModuleExportsAssignment(node) { - // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' - // is still pointing to 'module.exports'. - // We do not want to consider this as 'export=' since a module can have only one of these. - // Similarly we do not want to treat 'module.exports = exports' as an 'export='. - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { - // Mark it as a module in case there are no other exports in the file - setCommonJsModuleIndicator(node); - return; - } - // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */, 0 /* None */); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - // Declare a 'member' if the container is an ES5 class or ES6 constructor - container.symbol.members = container.symbol.members || ts.createSymbolTable(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); - break; - case 154 /* Constructor */: - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var containingClass = container.parent; - var symbolTable = ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; - declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); - break; - } - } - function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { - bindThisPropertyAssignment(node); - } - else if (ts.isEntityNameExpression(node) && node.parent.parent.kind === 272 /* SourceFile */) { - if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.escapedText === "prototype") { - bindPrototypePropertyAssignment(node, node.parent); - } - else { - bindStaticPropertyAssignment(node); - } - } - } - /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ - function bindPrototypeAssignment(node) { - node.left.parent = node; - node.right.parent = node; - var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); - } - /** - * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. - * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. - */ - function bindPrototypePropertyAssignment(lhs, parent) { - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var classPrototype = lhs.expression; - var constructorFunction = classPrototype.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - lhs.parent = parent; - constructorFunction.parent = classPrototype; - classPrototype.parent = lhs; - bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); - } - function bindSpecialPropertyAssignment(node) { - var lhs = node.left; - // Fix up parent pointers since we're going to use these nodes before we bind into them - node.left.parent = node; - node.right.parent = node; - if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindStaticPropertyAssignment(lhs); - } - } - /** - * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. - * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; - */ - function bindStaticPropertyAssignment(node) { - node.expression.parent = node; - bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); - } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name)); - var isToplevelNamespaceableInitializer; - if (ts.isBinaryExpression(propertyAccess.parent)) { - var isPrototypeAssignment = ts.isPropertyAccessExpression(propertyAccess.parent.left) && propertyAccess.parent.left.name.escapedText === "prototype"; - isToplevelNamespaceableInitializer = propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */ && - !!ts.getJavascriptInitializer(propertyAccess.parent.right, isPrototypeAssignment); - } - else { - isToplevelNamespaceableInitializer = propertyAccess.parent.parent.kind === 272 /* SourceFile */; - } - if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { - // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { - if (original) { - // Note: add declaration to original symbol, not the special-syntax's symbol, so that namespaces work for type lookup - addDeclarationToSymbol(original, id, flags_1); - return original; - } - else { - return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); - } - }); - } - if (!symbol || !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */ | 4096 /* ObjectLiteral */))) { - return; - } - // Set up the members collection if it doesn't exist already - var symbolTable = isPrototypeProperty ? - (symbol.members || (symbol.members = ts.createSymbolTable())) : - (symbol.exports || (symbol.exports = ts.createSymbolTable())); - // Declare the method/property - var symbolFlags = 4 /* Property */ | (isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); - var symbolExcludes = 0 /* PropertyExcludes */ & ~(isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); - declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); - } - function lookupSymbolForPropertyAccess(node) { - if (ts.isIdentifier(node)) { - return lookupSymbolForNameWorker(container, node.escapedText); - } - else { - var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); - return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); - } - } - function forEachIdentifierInEntityName(e, action) { - if (isExportsOrModuleExportsOrAlias(file, e)) { - return file.symbol; - } - else if (ts.isIdentifier(e)) { - return action(e, lookupSymbolForPropertyAccess(e)); - } - else { - var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); - return action(e.name, s.exports.get(e.name.escapedText)); - } - } - function bindCallExpression(node) { - // We're only inspecting call expressions to detect CommonJS modules, so we can skip - // this check if we've already seen the module indicator - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 233 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames.set(node.name.escapedText, true); - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); - } - symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration - // because its parent chain has already been set up, since parents are set before descending into children. - // - // If node is a binding element in parameter declaration, we need to use ParameterExcludes. - // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration - // For example: - // function foo([a,a]) {} // Duplicate Identifier error - // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter - // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); - } - } - } - function bindParameter(node) { - if (inStrictMode && !(node.flags & 2097152 /* Ambient */)) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) - checkStrictModeEvalOrArguments(node, node.name); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); - } - // If this is a property-parameter, then also declare the property symbol into the - // containing class. - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */) && ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; - } - function bindTypeParameter(node) { - if (node.parent.kind === 171 /* InferType */) { - var container_1 = getInferTypeContainer(node.parent); - if (container_1) { - if (!container_1.locals) { - container_1.locals = ts.createSymbolTable(); - } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); - } - else { - bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); - } - } - else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); - } - } - // reachability checks - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1 /* Unreachable */)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = - // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 213 /* EmptyStatement */) || - // report error on class declarations - node.kind === 233 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 237 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 236 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 2097152 /* Ambient */) && - (node.kind !== 212 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } + if (lhs.kind === 99 /* ThisKeyword */) { return true; } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); } - /* @internal */ - function isExportsOrModuleExportsOrAlias(sourceFile, node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); - } - ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; - function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { - var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { - return isExportsOrModuleExportsOrAlias(sourceFile, node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); - } - function lookupSymbolForNameWorker(container, name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); - } - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 185 /* CallExpression */: - return computeCallExpression(node, subtreeFlags); - case 186 /* NewExpression */: - return computeNewExpression(node, subtreeFlags); - case 237 /* ModuleDeclaration */: - return computeModuleDeclaration(node, subtreeFlags); - case 189 /* ParenthesizedExpression */: - return computeParenthesizedExpression(node, subtreeFlags); - case 198 /* BinaryExpression */: - return computeBinaryExpression(node, subtreeFlags); - case 214 /* ExpressionStatement */: - return computeExpressionStatement(node, subtreeFlags); - case 148 /* Parameter */: - return computeParameter(node, subtreeFlags); - case 191 /* ArrowFunction */: - return computeArrowFunction(node, subtreeFlags); - case 190 /* FunctionExpression */: - return computeFunctionExpression(node, subtreeFlags); - case 232 /* FunctionDeclaration */: - return computeFunctionDeclaration(node, subtreeFlags); - case 230 /* VariableDeclaration */: - return computeVariableDeclaration(node, subtreeFlags); - case 231 /* VariableDeclarationList */: - return computeVariableDeclarationList(node, subtreeFlags); - case 212 /* VariableStatement */: - return computeVariableStatement(node, subtreeFlags); - case 226 /* LabeledStatement */: - return computeLabeledStatement(node, subtreeFlags); - case 233 /* ClassDeclaration */: - return computeClassDeclaration(node, subtreeFlags); - case 203 /* ClassExpression */: - return computeClassExpression(node, subtreeFlags); - case 266 /* HeritageClause */: - return computeHeritageClause(node, subtreeFlags); - case 267 /* CatchClause */: - return computeCatchClause(node, subtreeFlags); - case 205 /* ExpressionWithTypeArguments */: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 154 /* Constructor */: - return computeConstructor(node, subtreeFlags); - case 151 /* PropertyDeclaration */: - return computePropertyDeclaration(node, subtreeFlags); - case 153 /* MethodDeclaration */: - return computeMethod(node, subtreeFlags); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return computeAccessor(node, subtreeFlags); - case 241 /* ImportEqualsDeclaration */: - return computeImportEquals(node, subtreeFlags); - case 183 /* PropertyAccessExpression */: - return computePropertyAccess(node, subtreeFlags); - case 184 /* ElementAccessExpression */: - return computeElementAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { - // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadElementExpression then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 182 /* ObjectLiteralExpression */) { - // Destructuring object assignments with are ES2015 syntax - // and possibly ESNext if they contain rest - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 181 /* ArrayLiteralExpression */) { - // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript - // syntax. - if (node.questionToken - || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ - || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; - } - // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a parameter has an initializer, a binding pattern or a dotDotDot token, then - // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (expressionKind === 206 /* AsExpression */ - || expressionKind === 188 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - if (ts.hasModifier(node, 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - // An exported declaration may be TypeScript syntax, but is handled by the visitor - // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; - } - function computeClassExpression(node, subtreeFlags) { - // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85 /* ExtendsKeyword */: - // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 108 /* ImplementsKeyword */: - // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (!node.variableDeclaration) { - transformFlags |= 8 /* AssertESNext */; - } - else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the - // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // If an ExpressionWithTypeArguments contains type arguments, then it - // is TypeScript syntax. - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers and overloads are TypeScript syntax - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; - } - function computeMethod(node, subtreeFlags) { - // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and - // overloads are TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type - || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // An async method declaration is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // Decorators, TypeScript-specific modifiers, type annotations, and overloads are - // TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.type - || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; - } - function computePropertyDeclaration(node, subtreeFlags) { - // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor - // so that it handle the transformation. - if (node.initializer) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (modifierFlags & 2270 /* TypeScriptModifier */ - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function declaration is ES2017 syntax. - if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionDeclaration is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function expression is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionExpression is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; - } - function computeArrowFunction(node, subtreeFlags) { - // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async arrow function is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; - } - // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If a PropertyAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; - } - function computeElementAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing - // If an ElementAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // Type annotations are TypeScript syntax. - if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var declarationListTransformFlags = node.declarationList.transformFlags; - // An ambient declaration is TypeScript syntax. - if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ - && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // An ImportEqualsDeclaration with a namespace reference is TypeScript. - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2 /* Ambient */) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. - if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; - } - function computeOther(node, kind, subtreeFlags) { - // Mark transformations needed for each node - var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; - switch (kind) { - case 120 /* AsyncKeyword */: - case 195 /* AwaitExpression */: - // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) - transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; - break; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 295 /* PartiallyEmittedExpression */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; - break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 207 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 256 /* JsxClosingElement */: - case 257 /* JsxFragment */: - case 258 /* JsxOpeningFragment */: - case 259 /* JsxClosingFragment */: - case 260 /* JsxAttribute */: - case 261 /* JsxAttributes */: - case 262 /* JsxSpreadAttribute */: - case 263 /* JsxExpression */: - // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; - break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 200 /* TemplateExpression */: - case 187 /* TaggedTemplateExpression */: - case 269 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 208 /* MetaProperty */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 9 /* StringLiteral */: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 220 /* ForOfStatement */: - // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). - if (node.awaitModifier) { - transformFlags |= 8 /* AssertESNext */; - } - transformFlags |= 192 /* AssertES2015 */; - break; - case 201 /* YieldExpression */: - // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async - // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; - break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 147 /* TypeParameter */: - case 150 /* PropertySignature */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 160 /* TypePredicate */: - case 161 /* TypeReference */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 164 /* TypeQuery */: - case 165 /* TypeLiteral */: - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 170 /* ConditionalType */: - case 171 /* InferType */: - case 172 /* ParenthesizedType */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 173 /* ThisType */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 177 /* LiteralType */: - case 240 /* NamespaceExportDeclaration */: - // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; - break; - case 146 /* ComputedPropertyName */: - // Even though computed property names are ES6, we don't treat them as such. - // This is so that they can flow through PropertyName transforms unaffected. - // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; - } - break; - case 202 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; - break; - case 270 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; - break; - case 97 /* SuperKeyword */: - // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` - break; - case 99 /* ThisKeyword */: - // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; - break; - case 178 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; - } - excludeFlags = 940049729 /* BindingPatternExcludes */; - break; - case 179 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; - break; - case 180 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; - if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; - } - break; - case 149 /* Decorator */: - // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; - break; - case 182 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { - // If an ObjectLiteralExpression contains a ComputedPropertyName, then it - // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { - // If an ObjectLiteralExpression contains a spread element, then it - // is an ES next node. - transformFlags |= 8 /* AssertESNext */; - } - break; - case 181 /* ArrayLiteralExpression */: - case 186 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 272 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 223 /* ReturnStatement */: - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~excludeFlags; - } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - /* @internal */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 160 /* FirstTypeNode */ && kind <= 177 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 181 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 237 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 148 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 191 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 231 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 154 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 147 /* TypeParameter */: - case 150 /* PropertySignature */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 182 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 267 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 295 /* PartiallyEmittedExpression */: - case 189 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; - default: - return 939525441 /* NodeExcludes */; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; - /** - * "Binds" JSDoc nodes in TypeScript code. - * Since we will never create symbols for JSDoc, we just set parent pointers instead. - */ - function setParentPointers(parent, child) { - child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); - } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; })(ts || (ts = {})); -/** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { - return getSymbolWalker; - function getSymbolWalker(accept) { - if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = []; // Sparse array from id to type - var visitedSymbols = []; // Sparse array from id to symbol + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.optionDeclarations = [ + // CommandLine only options + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + }, + { + name: "strictNullChecks", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + 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: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + 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", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]; + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { return { - walkType: function (type) { - try { - visitType(type); - return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; - } - finally { - ts.clear(visitedTypes); - ts.clear(visitedSymbols); - } - }, - walkSymbol: function (symbol) { - try { - visitSymbol(symbol); - return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; - } - finally { - ts.clear(visitedTypes); - ts.clear(visitedSymbols); - } - }, + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] }; - function visitType(type) { - if (!type) { - return; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + if (optionNameMapCache) { + return optionNameMapCache; + } + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + return optionNameMapCache; + } + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLine(commandLine, readFile) { + var options = {}; + var fileNames = []; + var projectReferences = undefined; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); } - if (visitedTypes[type.id]) { - return; - } - visitedTypes[type.id] = 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 & 65536 /* Object */) { - var objectType = type; - var objectFlags = objectType.objectFlags; - if (objectFlags & 4 /* Reference */) { - visitTypeReference(type); + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } } - if (objectFlags & 32 /* Mapped */) { - visitMappedType(type); - } - if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { - visitInterfaceType(type); - } - if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { - visitObjectType(objectType); + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); } } - if (type.flags & 32768 /* TypeParameter */) { - visitTypeParameter(type); - } - if (type.flags & 393216 /* UnionOrIntersection */) { - visitUnionOrIntersectionType(type); - } - if (type.flags & 524288 /* Index */) { - visitIndexType(type); - } - if (type.flags & 1048576 /* IndexedAccess */) { - visitIndexedAccessType(type); + else { + fileNames.push(s); } } - function visitTypeReference(type) { - visitType(type.target); - ts.forEach(type.typeArguments, visitType); + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; } - function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); - } - function visitUnionOrIntersectionType(type) { - ts.forEach(type.types, visitType); - } - 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) { - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - visitType(typePredicate.type); + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } } - ts.forEach(signature.typeParameters, visitType); - 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); - ts.forEach(interfaceT.typeParameters, visitType); - ts.forEach(getBaseTypes(interfaceT), visitType); - 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); + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); } } - function visitSymbol(symbol) { - if (!symbol) { - return; + parseStrings(args); + } + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + ts.getOptionFromName = getOptionFromName; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); } - var symbolId = ts.getSymbolId(symbol); - if (visitedSymbols[symbolId]) { - return; + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 273 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; } - visitedSymbols[symbolId] = symbol; - if (!accept(symbol)) { + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); 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 === 164 /* TypeQuery */) { - var query = d.type; - var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); - visitSymbol(entity); + case 86 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 9 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - }); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 200 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 186 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 185 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + result.set(name, value); + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); } } } - ts.createGetSymbolWalker = createGetSymbolWalker; + /*@internal*/ + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + /*@internal*/ + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); + return undefined; + } + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); + return { + fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + 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 (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. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } })(ts || (ts = {})); -/// -/// var ts; (function (ts) { function trace(host) { @@ -23732,7 +23818,7 @@ var ts; ts.trace = trace; /* @internal */ function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -23749,7 +23835,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { @@ -23789,16 +23876,24 @@ var ts; return path; } } + /* @internal */ function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { // gracefully handle if readFile fails or returns not JSON return {}; } } + ts.readJson = readJson; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -23903,7 +23998,6 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations @@ -23911,7 +24005,7 @@ var ts; trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -23984,7 +24078,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; + return undefined; // TODO: GH#18217 } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { @@ -24056,6 +24150,12 @@ var ts; } } ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -24090,7 +24190,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -24316,7 +24416,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -24339,7 +24443,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -24364,13 +24468,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -24455,6 +24560,10 @@ var ts; * 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. */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -24487,10 +24596,12 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.Json: + return tryExtension(".json" /* Json */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -24539,8 +24650,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; } else { subModuleName = "index.d.ts"; @@ -24573,14 +24687,23 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + // When resolving typescript modules, try resolving using main field as well + file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); if (fromFile) { - var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + var resolved = resolvedIfExtensionMatches(extensions, fromFile); if (resolved) { return resolved; } @@ -24608,6 +24731,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.Json: + return extension === ".json" /* Json */; case Extensions.TypeScript: return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: @@ -24678,7 +24803,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -24805,9 +24930,3644 @@ var ts; return value !== undefined ? { value: value } : undefined; } })(ts || (ts = {})); -/// -/// -/// +/* @internal */ +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) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 241 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 243 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 71 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67216319 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 252 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 147 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 155 /* Constructor */: + return "__constructor" /* Constructor */; + case 163 /* FunctionType */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + return "__call" /* Call */; + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return "__new" /* New */; + case 160 /* IndexSignature */: + return "__index" /* Index */; + case 253 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 277 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 202 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 287 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 149 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else { + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 195 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 277 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 155 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 222 /* WhileStatement */: + bindWhileStatement(node); + break; + case 221 /* DoStatement */: + bindDoStatement(node); + break; + case 223 /* ForStatement */: + bindForStatement(node); + break; + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 220 /* IfStatement */: + bindIfStatement(node); + break; + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 233 /* TryStatement */: + bindTryStatement(node); + break; + case 230 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 244 /* CaseBlock */: + bindCaseBlock(node); + break; + case 269 /* CaseClause */: + bindCaseClause(node); + break; + case 231 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 200 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 201 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 202 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 196 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 203 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 235 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 189 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 277 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 216 /* Block */: + case 243 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 187 /* PropertyAccessExpression */: + return isNarrowableReference(expr); + case 189 /* CallExpression */: + return hasNarrowableArgument(expr); + case 193 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 202 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 200 /* PrefixUnaryExpression */: + return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 /* Identifier */ || + expr.kind === 99 /* ThisKeyword */ || + expr.kind === 97 /* SuperKeyword */ || + expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 92 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 26 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 193 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 202 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(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 }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: + return parent.expression === node; + case 223 /* ForStatement */: + case 203 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 193 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 54 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 193 /* ParenthesizedExpression */ || + node.parent.kind === 200 /* PrefixUnaryExpression */ && + node.parent.operator === 51 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 225 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 228 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 185 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 206 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 186 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 273 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 275 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 187 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 193 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 187 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 266 /* JsxAttributes */: + return 1 /* IsContainer */; + case 239 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 277 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 154 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + case 287 /* JSDocFunctionType */: + case 163 /* FunctionType */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 164 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 243 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 152 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 272 /* CatchClause */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 244 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 216 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 242 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 277 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 241 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 186 /* ObjectLiteralExpression */: + case 239 /* InterfaceDeclaration */: + case 266 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 291 /* JSDocSignature */: + case 160 /* IndexSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 287 /* JSDocFunctionType */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 277 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + 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++) { + var prop = _a[_i]; + if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 242 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 277 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 277 /* SourceFile */ && + blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 145 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 71 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + break; + } + // falls through + case 99 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 187 /* PropertyAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + break; + case 202 /* BinaryExpression */: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 272 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 196 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 201 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 200 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 229 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 176 /* ThisType */: + seenThisKeyword = true; + return; + case 161 /* TypePredicate */: + break; // Binding the children will handle everything + case 148 /* TypeParameter */: + return bindTypeParameter(node); + case 149 /* Parameter */: + return bindParameter(node); + case 235 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 184 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + return bindPropertyWorker(node); + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 276 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + case 237 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 155 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 156 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + case 157 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + case 163 /* FunctionType */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: + case 164 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 179 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 186 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return bindFunctionExpression(node); + case 189 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 239 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + case 240 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + case 241 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 242 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 266 /* JsxAttributes */: + return bindJsxAttributes(node); + case 265 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 245 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 248 /* ImportClause */: + return bindImportClause(node); + case 253 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 252 /* ExportAssignment */: + return bindExportAssignment(node); + case 277 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 216 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 243 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 296 /* JSDocParameterTag */: + if (node.parent.kind === 291 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 302 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 277 /* SourceFile */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 155 /* Constructor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 277 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 99 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && + !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 277 /* SourceFile */; + if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + } + }); + } + if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + // Declare the method/property + var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); + var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; + var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + } + /** + * Javascript containers are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isJavascriptContainer(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 238 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 174 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + // report error on class declarations + node.kind === 238 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 189 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 190 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 242 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 193 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 202 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 219 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 149 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 195 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 194 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 237 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 235 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 236 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 217 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 231 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 238 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 207 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 271 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 272 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 209 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 155 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 152 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 154 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 246 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 187 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 188 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + if (expression.kind === 91 /* ImportKeyword */) { + transformFlags |= 67108864 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ + || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 210 /* AsExpression */ + || expressionKind === 192 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~942011713 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~942011713 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 108 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 8192 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003935041 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003935041 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~977327425 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 939525441 /* NodeExcludes */; + switch (kind) { + case 120 /* AsyncKeyword */: + case 199 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 305 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 211 /* NonNullExpression */: + case 132 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 261 /* JsxClosingElement */: + case 262 /* JsxFragment */: + case 263 /* JsxOpeningFragment */: + case 264 /* JsxClosingFragment */: + case 265 /* JsxAttribute */: + case 266 /* JsxAttributes */: + case 267 /* JsxSpreadAttribute */: + case 268 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 274 /* ShorthandPropertyAssignment */: + case 115 /* StaticKeyword */: + case 212 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 9 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 225 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 205 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + break; + case 119 /* AnyKeyword */: + case 134 /* NumberKeyword */: + case 131 /* NeverKeyword */: + case 135 /* ObjectKeyword */: + case 137 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 138 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 148 /* TypeParameter */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 161 /* TypePredicate */: + case 162 /* TypeReference */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 165 /* TypeQuery */: + case 166 /* TypeLiteral */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 174 /* InferType */: + case 175 /* ParenthesizedType */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: + case 245 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 147 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 206 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + break; + case 275 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 97 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 99 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 16384 /* ContainsLexicalThis */; + break; + case 182 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 940049729 /* BindingPatternExcludes */; + break; + case 183 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 940049729 /* BindingPatternExcludes */; + break; + case 184 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 150 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + break; + case 186 /* ObjectLiteralExpression */: + excludeFlags = 942740801 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 185 /* ArrayLiteralExpression */: + case 190 /* NewExpression */: + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 277 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 228 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 185 /* ArrayLiteralExpression */: + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + case 242 /* ModuleDeclaration */: + return 977327425 /* ModuleExcludes */; + case 149 /* Parameter */: + return 939525441 /* ParameterExcludes */; + case 195 /* ArrowFunction */: + return 1003902273 /* ArrowFunctionExcludes */; + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + return 1003935041 /* FunctionExcludes */; + case 236 /* VariableDeclarationList */: + return 948962625 /* VariableDeclarationListExcludes */; + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 942011713 /* ClassExcludes */; + case 155 /* Constructor */: + return 1003668801 /* ConstructorExcludes */; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return 1003668801 /* MethodOrAccessorExcludes */; + case 119 /* AnyKeyword */: + case 134 /* NumberKeyword */: + case 131 /* NeverKeyword */: + case 137 /* StringKeyword */: + case 135 /* ObjectKeyword */: + case 122 /* BooleanKeyword */: + case 138 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 148 /* TypeParameter */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 186 /* ObjectLiteralExpression */: + return 942740801 /* ObjectLiteralExcludes */; + case 272 /* CatchClause */: + return 940574017 /* CatchClauseExcludes */; + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + return 940049729 /* BindingPatternExcludes */; + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 305 /* PartiallyEmittedExpression */: + case 193 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; + default: + return 939525441 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = 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 & 131072 /* 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 & 65536 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 786432 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 1048576 /* Index */) { + visitIndexType(type); + } + if (type.flags & 2097152 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + 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) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + 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); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + 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 false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + 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 === 165 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -24864,19 +28624,21 @@ var ts; var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var moduleKind = ts.getEmitModuleKind(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -24897,25 +28659,27 @@ var ts; getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: function (symbol, location) { location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, getIndexInfoOfType: getIndexInfoOfType, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: getIndexTypeOfType, getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, getReturnTypeOfSignature: getReturnTypeOfSignature, @@ -24941,8 +28705,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -24950,10 +28714,10 @@ var ts; }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; + return node ? getTypeOfNode(node) : errorType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -24980,44 +28744,43 @@ var ts; writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -25029,7 +28792,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; @@ -25038,15 +28802,15 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -25068,6 +28832,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, + getFalseType: function () { return falseType; }, + getTrueType: function () { return trueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -25075,11 +28841,13 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -25091,13 +28859,48 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, - getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, + getSuggestionDiagnostics: function (file, ct) { + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + } }; - var tupleTypes = []; + var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); @@ -25109,22 +28912,25 @@ var ts; var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(4096 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 /* Undefined */ | 16777216 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(8192 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 /* Null */ | 16777216 /* ContainsWideningType */, "null"); - var stringType = createIntrinsicType(2 /* String */, "string"); - var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(2048 /* Void */, "void"); - var neverType = createIntrinsicType(16384 /* Never */, "never"); - var silentNeverType = createIntrinsicType(16384 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(16384 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(134217728 /* NonPrimitive */, "object"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(16384 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + var booleanType = createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(4096 /* Void */, "void"); + var neverType = createIntrinsicType(32768 /* Never */, "never"); + var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -25134,22 +28940,24 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 67108864 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(32768 /* TypeParameter */); - var markerSubType = createType(32768 /* TypeParameter */); + var markerSuperType = createType(65536 /* TypeParameter */); + var markerSubType = createType(65536 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(32768 /* TypeParameter */); + var markerOtherType = createType(65536 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** @@ -25187,8 +28995,10 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; var deferredNodes; - var deferredUnusedIdentifierNodes; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -25215,17 +29025,6 @@ var ts; var diagnostics = ts.createDiagnosticCollection(); // Suggestion diagnostics must have a file. Keyed by source file name. var suggestionDiagnostics = ts.createMultiMap(); - function addSuggestionDiagnostic(diag) { - suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); - } - function addErrorOrSuggestionDiagnostic(isError, diag) { - if (isError) { - diagnostics.add(diag); - } - else { - addSuggestionDiagnostic(diag); - } - } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -25328,7 +29127,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -25357,168 +29156,21 @@ var ts; ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; })(ExpandingFlags || (ExpandingFlags = {})); - var TypeIncludes; - (function (TypeIncludes) { - TypeIncludes[TypeIncludes["Any"] = 1] = "Any"; - TypeIncludes[TypeIncludes["Undefined"] = 2] = "Undefined"; - TypeIncludes[TypeIncludes["Null"] = 4] = "Null"; - TypeIncludes[TypeIncludes["Never"] = 8] = "Never"; - TypeIncludes[TypeIncludes["NonWideningType"] = 16] = "NonWideningType"; - TypeIncludes[TypeIncludes["String"] = 32] = "String"; - TypeIncludes[TypeIncludes["Number"] = 64] = "Number"; - TypeIncludes[TypeIncludes["ESSymbol"] = 128] = "ESSymbol"; - TypeIncludes[TypeIncludes["LiteralOrUniqueESSymbol"] = 256] = "LiteralOrUniqueESSymbol"; - TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; - TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; - TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; - TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; - })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; - /** - * @deprecated - */ - function getSymbolDisplayBuilder() { - return { - buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { - typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); - }, - buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { - symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); - }, - buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { - signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); - }, - buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { - var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildParameterDisplay: function (symbol, writer, enclosing, flags) { - var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { - var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { - typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - }, - buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { - var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { - var printer = ts.createPrinter({ removeComments: true }); - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { - var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = getTypePredicateOfSignature(signature); - if (predicate) { - return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - } - var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - } - }; - function emitTextWriterWrapper(underlying) { - return { - write: ts.noop, - writeTextOfNode: ts.noop, - writeLine: ts.noop, - increaseIndent: function () { - return underlying.increaseIndent(); - }, - decreaseIndent: function () { - return underlying.decreaseIndent(); - }, - getText: function () { - return ""; - }, - rawWrite: ts.noop, - writeLiteral: function (s) { - return underlying.writeStringLiteral(s); - }, - getTextPos: function () { - return 0; - }, - getLine: function () { - return 0; - }, - getColumn: function () { - return 0; - }, - getIndent: function () { - return 0; - }, - isAtStartOfLine: function () { - return false; - }, - clear: function () { - return underlying.clear(); - }, - writeKeyword: function (text) { - return underlying.writeKeyword(text); - }, - writeOperator: function (text) { - return underlying.writeOperator(text); - }, - writePunctuation: function (text) { - return underlying.writePunctuation(text); - }, - writeSpace: function (text) { - return underlying.writeSpace(text); - }, - writeStringLiteral: function (text) { - return underlying.writeStringLiteral(text); - }, - writeParameter: function (text) { - return underlying.writeParameter(text); - }, - writeProperty: function (text) { - return underlying.writeProperty(text); - }, - writeSymbol: function (text, symbol) { - return underlying.writeSymbol(text, symbol); - }, - trackSymbol: function (symbol, enclosing, meaning) { - return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); - }, - reportInaccessibleThisError: function () { - return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); - }, - reportPrivateInBaseOfClassExpression: function (name) { - return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); - }, - reportInaccessibleUniqueSymbolError: function () { - return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); - } - }; - } - } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -25528,7 +29180,7 @@ var ts; } var jsxPragma = file.pragmas.get("jsx"); if (jsxPragma) { - var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; @@ -25556,11 +29208,48 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); } function createSymbol(flags, name, checkFlags) { symbolCount++; @@ -25629,9 +29318,17 @@ var ts; recordMergedSymbol(result, symbol); return result; } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + target = cloneSymbol(target); + } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -25640,7 +29337,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 237 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 237 /* ModuleDeclaration */))) { + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } @@ -25655,38 +29352,67 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } - if ((source.flags | target.flags) & 67108864 /* JSContainer */) { - var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); - if (sourceInitializer !== source || targetInitializer !== target) { - mergeSymbol(targetInitializer, sourceInitializer); - } - } recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { - var message_2 = target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */ + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + : isEitherBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); + var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; + var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; + var cacheKey = firstFile_1.path + "|" + secondFile.path; + var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; + var symbolName_1 = symbolToString(source); + var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + ts.forEach(source.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); + existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); + amalgamatedDuplicates.set(cacheKey, existing); + return target; + } + var symbolName_2 = symbolToString(source); + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); + } + return target; + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + var err = lookupOrIssueError(errorNode, message, symbolName); + if (relatedNode && ts.length(err.relatedInformation) < 5) { + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } function combineSymbolTables(first, second) { - if (!first || first.size === 0) + if (!ts.hasEntries(first)) return second; - if (!second || second.size === 0) + if (!ts.hasEntries(second)) return first; var combined = ts.createSymbolTable(); mergeSymbolTable(combined, first); @@ -25695,17 +29421,7 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 33554432 /* Transient */)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } + target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -25723,7 +29439,7 @@ var ts; else { // find a module that about to be augmented // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152 /* Ambient */) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); @@ -25733,10 +29449,7 @@ var ts; // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920 /* Namespace */) { - // if module symbol has already been merged - it is safe to use it. - // otherwise clone it - mainModule = mainModule.flags & 33554432 /* Transient */ ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); } else { // moduleName will be a StringLiteral since this is not `declare global`. @@ -25770,7 +29483,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 272 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -25805,16 +29518,16 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - declaration.flags & 2097152 /* Ambient */) { + declaration.flags & 4194304 /* Ambient */) { // nodes are in different files and order cannot be determined return true; } @@ -25828,20 +29541,24 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 180 /* BindingElement */) { + if (declaration.kind === 184 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 180 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 230 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); } - else if (declaration.kind === 230 /* VariableDeclaration */) { + else if (declaration.kind === 235 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } return true; } // declaration is after usage, but it can still be legal if usage is deferred: @@ -25852,22 +29569,23 @@ var ts; // 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 === 250 /* ExportSpecifier */ || (usage.parent.kind === 247 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // 2. inside a jsdoc comment + if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* 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 === 247 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 212 /* VariableStatement */: - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 217 /* VariableStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -25876,7 +29594,8 @@ var ts; break; } // ForIn/ForOf case - use site should not be used in expression part - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -25887,21 +29606,22 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 151 /* PropertyDeclaration */ && + current.parent.kind === 152 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 153 /* MethodDeclaration */) { + if (declaration.kind === 154 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 151 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } } } + return false; }); } } @@ -25937,12 +29657,12 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 148 /* Parameter */ || - lastLocation.kind === 147 /* TypeParameter */ + lastLocation.kind === 149 /* Parameter */ || + lastLocation.kind === 148 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -25952,12 +29672,12 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 148 /* Parameter */ || + lastLocation.kind === 149 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 148 /* Parameter */); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } - else if (location.kind === 170 /* ConditionalType */) { + else if (location.kind === 173 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -25971,14 +29691,14 @@ var ts; } } switch (location.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -26002,21 +29722,27 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 250 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { break; } } - if (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */)) { - break loop; + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -26033,9 +29759,9 @@ var ts; } } break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container @@ -26051,7 +29777,7 @@ var ts; } break loop; } - if (location.kind === 203 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -26059,7 +29785,7 @@ var ts; } } break; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* 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; @@ -26079,9 +29805,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 234 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -26089,19 +29815,19 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -26114,7 +29840,7 @@ var ts; } } break; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -26123,7 +29849,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 148 /* Parameter */) { + if (location.parent && location.parent.kind === 149 /* Parameter */) { location = location.parent; } // @@ -26136,6 +29862,11 @@ var ts; location = location.parent; } break; + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -26146,12 +29877,12 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` 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 (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 272 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -26160,19 +29891,34 @@ var ts; result = lookup(globals, name, meaning); } } + if (!result) { + if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && + originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { + return moduleSymbol; + } + } + } if (!result) { if (nameNotFoundMessage) { if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -26212,10 +29958,10 @@ var ts; } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */) { + if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 240 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } } @@ -26223,12 +29969,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 237 /* ModuleDeclaration */: // For `namespace N { N; }` + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -26240,8 +29986,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 147 /* TypeParameter */ && decl.parent === container) { - return true; + if (decl.kind === 148 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } return false; @@ -26250,7 +29999,7 @@ var ts; if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { return false; } - var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); var location = container; while (location) { if (ts.isClassLike(location.parent)) { @@ -26267,7 +30016,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.hasModifier(location, 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -26280,11 +30029,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } /** * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, @@ -26293,9 +30042,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71 /* Identifier */: - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -26359,17 +30108,26 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 236 /* EnumDeclaration */) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!(declaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } else if (result.flags & 256 /* RegularEnum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -26378,17 +30136,17 @@ var ts; * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 243 /* ImportClause */: + case 248 /* ImportClause */: return node.parent; - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return node.parent.parent; - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -26398,7 +30156,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 252 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -26409,14 +30167,18 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { return false; } // Declaration files (and ambient modules) if (!file || file.isDeclarationFile) { - // Definitely cannot have a synthetic default if they have a default member specified - if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { return false; } // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member @@ -26453,7 +30215,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -26490,7 +30252,7 @@ var ts; return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); result.parent = valueSymbol.parent || typeSymbol.parent; if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; @@ -26509,12 +30271,13 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 } } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { var name = specifier.propertyName || specifier.name; @@ -26524,7 +30287,7 @@ var ts; } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); } else { @@ -26537,15 +30300,19 @@ var ts; if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } - var symbol = symbolFromModule && symbolFromVariable ? + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -26567,36 +30334,51 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 250 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: + case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } /** * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } - return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -26604,7 +30386,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -26637,12 +30420,13 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 247 /* ExportAssignment */) { + if (!node) + return ts.Debug.fail(); + if (node.kind === 252 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 250 /* ExportSpecifier */) { + else if (node.kind === 255 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -26664,13 +30448,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 145 /* QualifiedName */) { + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 241 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -26688,14 +30472,15 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, /*isUse*/ true); + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { - return undefined; + return symbolFromJSPrototype; } } - else if (name.kind === 145 /* QualifiedName */ || name.kind === 183 /* PropertyAccessExpression */) { - var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { + var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -26704,10 +30489,6 @@ var ts; return namespace; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); - if (initializer) { - namespace = getSymbolOfNode(initializer); - } if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -26731,11 +30512,43 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -26759,13 +30572,14 @@ var ts; if (ambientModule) { return ambientModule; } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { - addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -26783,19 +30597,34 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { 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); } else { - addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); } // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; } if (moduleNotFoundError) { - // report errors only if it was requested + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -26812,29 +30641,52 @@ var ts; } return undefined; } - function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId && ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); - return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + var errorInfo = packageId + ? ts.chainDiagnosticMessages( + /*details*/ undefined, typesPackageExists(packageId.name) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 + : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { + return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); + }); }); } - // 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=" /* ExportEquals */), dontResolveAlias)) || moduleSymbol; + return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || moduleSymbol.exports.size === 1) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; } // 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 // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). - function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } if (compilerOptions.esModuleInterop) { - var referenceParent = moduleReferenceExpression.parent; + var referenceParent = referencingLocation.parent; if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || ts.isImportCall(referenceParent)) { var type = getTypeOfSymbol(symbol); @@ -26897,7 +30749,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 16382 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -26946,7 +30798,7 @@ var ts; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -26987,6 +30839,51 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -26999,7 +30896,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 154 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -27017,14 +30914,20 @@ var ts; } function createBooleanType(trueFalseTypes) { var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; + type.flags |= 16 /* Boolean */; type.intrinsicName = "boolean"; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(65536 /* Object */); + var type = createType(131072 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; return type; } function createTypeofType() { @@ -27043,25 +30946,19 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; - type.properties = getNamedMembers(members); + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { @@ -27077,12 +30974,12 @@ var ts; } } switch (location.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -27101,11 +30998,8 @@ var ts; return undefined; } var id = "" + getSymbolId(symbol); - var visitedSymbolTables; - if (visitedSymbolTablesMap.has(id)) { - visitedSymbolTables = visitedSymbolTablesMap.get(id); - } - else { + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { visitedSymbolTablesMap.set(id, visitedSymbolTables = []); } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); @@ -27131,7 +31025,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -27159,6 +31053,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -27166,7 +31065,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -27177,7 +31076,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 250 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -27192,10 +31091,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: continue; default: return false; @@ -27213,6 +31112,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -27222,48 +31169,21 @@ var ts; * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -27271,21 +31191,24 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { return undefined; } return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; @@ -27297,32 +31220,45 @@ var ts; if (anyImportSyntax && !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 - // since we will do the emitting later in trackSymbol. - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); - } - return true; + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); } // Declaration is not visible return false; } return true; } + function addVisibleAlias(declaration, aliasingStatement) { + // 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 + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } } function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 164 /* TypeQuery */ || + if (entityName.parent.kind === 165 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 146 /* ComputedPropertyName */) { + entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 145 /* QualifiedName */ || entityName.kind === 183 /* PropertyAccessExpression */ || - entityName.parent.kind === 241 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || + entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -27355,7 +31291,7 @@ var ts; var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { - var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); @@ -27363,178 +31299,182 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 163 /* ConstructorType */ : 162 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 158 /* ConstructSignature */ : 157 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 return writer; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - ts.Debug.assert(typeNode !== undefined, "should always get typenode"); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); }, symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); }, symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToExpression(symbol, context, meaning); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); }, symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); }, symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToParameterDeclaration(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); }, typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParameterToDeclaration(parameter, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); }, }; - function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { - return { + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, - inferTypeParameters: undefined + visitedSymbols: undefined, + inferTypeParameters: undefined, + approximateLength: 0 }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; } function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } - if (type.flags & 2 /* String */) { + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } - if (type.flags & 4 /* Number */) { + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } - if (type.flags & 8 /* Boolean */) { + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { + if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } - if (type.flags & 272 /* EnumLike */) { + if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (32 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (64 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 128 /* BooleanLiteral */) { + if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 1024 /* UniqueESSymbol */) { + if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319 /* Value */, /*expectsIdentifier*/ false)); + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } - if (type.flags & 2048 /* Void */) { + if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } - if (type.flags & 4096 /* Undefined */) { + if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } - if (type.flags & 8192 /* Null */) { + if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } - if (type.flags & 512 /* ESSymbol */) { + if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } - if (type.flags & 134217728 /* NonPrimitive */) { + if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } - if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { + if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -27543,56 +31483,72 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 65536 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); } - if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { - var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { + var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 /* Union */ ? 168 /* UnionType */ : 169 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } - return undefined; + return undefined; // TODO: GH#18217 } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 524288 /* Index */) { + if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 1048576 /* IndexedAccess */) { + if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 2097152 /* Conditional */) { + if (type.flags & 4194304 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -27600,58 +31556,71 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 4194304 /* Substitution */) { + if (type.flags & 8388608 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67216319 /* Value */); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); + return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -27664,12 +31633,12 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 272 /* SourceFile */ || declaration.parent.kind === 238 /* ModuleBlock */; + return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -27680,16 +31649,17 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 162 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); return signatureNode; } } @@ -27698,17 +31668,9 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { - var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); - return ts.createTypeQueryNode(entityName); - } - function symbolToTypeReferenceName(symbol) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -27721,8 +31683,15 @@ var ts; } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + for (var i = type.target.minLength; i < arity; i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } return ts.createTupleTypeNode(tupleConstituentNodes); } } @@ -27730,17 +31699,18 @@ var ts; return ts.createTupleTypeNode([]); } context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203 /* ClassExpression */) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27754,65 +31724,78 @@ var ts; // the default outer type arguments), we don't show the group. 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); - (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71 /* Identifier */) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71 /* Identifier */) { - rightPart = rightPart.left; + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? @@ -27827,8 +31810,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -27837,49 +31822,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 152 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - typeElements.push(propertySignature); + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } + addPropertyToElementList(propertySymbol, context, typeElements); } return typeElements.length ? typeElements : undefined; } } - function mapToTypeNodes(types, context) { + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + } + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -27897,10 +31929,11 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -27913,7 +31946,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -27939,60 +31972,78 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 180 /* BindingElement */) { + if (clone.kind === 184 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } - function lookupSymbolChain(symbol, context, meaning) { - context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -28002,16 +32053,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -28021,10 +32074,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -28054,6 +32109,120 @@ var ts; } return typeParameterNodes; } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + else { + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 + { importModuleSpecifierPreference: "non-relative" }))[0]; + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67216319 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 @@ -28120,6 +32289,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); @@ -28135,10 +32305,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 12288 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 131072 /* Union */) { + if (!(t.flags & 24576 /* Nullable */)) { + if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { + var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -28150,9 +32320,9 @@ var ts; result.push(t); } } - if (flags & 8192 /* Null */) + if (flags & 16384 /* Null */) result.push(nullType); - if (flags & 4096 /* Undefined */) + if (flags & 8192 /* Undefined */) result.push(undefinedType); return result || types; } @@ -28167,8 +32337,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 172 /* ParenthesizedType */; }); - if (node.kind === 235 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); + if (node.kind === 240 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -28176,14 +32346,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 238 /* ModuleBlock */ && + node.parent.kind === 243 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { - return location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -28208,24 +32375,26 @@ var ts; if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 230 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { - context.encounteredError = true; - } switch (declaration.kind) { - case 203 /* ClassExpression */: - return "(Anonymous class)"; - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return "(Anonymous function)"; + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) { - var stringValue = symbol.nameType.value; - if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { - return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } return ts.symbolName(symbol); @@ -28241,22 +32410,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 180 /* BindingElement */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 184 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 232 /* FunctionDeclaration */: - case 236 /* EnumDeclaration */: - case 241 /* ImportEqualsDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 241 /* EnumDeclaration */: + case 246 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -28264,53 +32438,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 241 /* ImportEqualsDeclaration */ && parent.kind !== 272 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { + !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 154 /* Constructor */: - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - case 148 /* Parameter */: - case 238 /* ModuleBlock */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 165 /* TypeLiteral */: - case 161 /* TypeReference */: - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 172 /* ParenthesizedType */: + case 155 /* Constructor */: + case 159 /* ConstructSignature */: + case 158 /* CallSignature */: + case 160 /* IndexSignature */: + case 149 /* Parameter */: + case 243 /* ModuleBlock */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 166 /* TypeLiteral */: + case 162 /* TypeReference */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 175 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: return false; // Type parameters are always visible - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: // Source file and namespace export are always visible - case 272 /* SourceFile */: - case 240 /* NamespaceExportDeclaration */: + case 277 /* SourceFile */: + case 245 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return false; default: return false; @@ -28319,10 +32493,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 247 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 250 /* ExportSpecifier */) { + else if (node.parent.kind === 255 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -28390,23 +32564,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; } - if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -28416,20 +32586,19 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 230 /* VariableDeclaration */: - case 231 /* VariableDeclarationList */: - case 246 /* ImportSpecifier */: - case 245 /* NamedImports */: - case 244 /* NamespaceImport */: - case 243 /* ImportClause */: + case 235 /* VariableDeclaration */: + case 236 /* VariableDeclarationList */: + case 251 /* ImportSpecifier */: + case 250 /* NamedImports */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: return false; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -28454,14 +32623,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 146 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 12288 /* Nullable */); }); - if (source.flags & 16384 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); + if (source.flags & 32768 /* Never */) { return emptyObjectType; } - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -28476,7 +32645,7 @@ var ts; var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { - members.set(prop.escapedName, prop); + members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -28488,8 +32657,8 @@ var ts; var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); // If parent has the unknown (error) type, then so does this binding element - if (parentType === unknownType) { - return unknownType; + if (parentType === errorType) { + return errorType; } // If no type was specified or inferred for parent, // infer from the initializer of the binding element if one is present. @@ -28501,11 +32670,11 @@ var ts; return parentType; } var type; - if (pattern.kind === 178 /* ObjectBindingPattern */) { + if (pattern.kind === 182 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; + return errorType; } var literalMembers = []; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { @@ -28519,25 +32688,50 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - // computed properties with non-literal names are treated as 'any' - return anyType; + var isLate = isLateBindableName(name); + var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); + if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { + var exprType = checkExpression(name.expression); + if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); + } + return anyType; + } + var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); + if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(parentType, 1 /* Number */)) { + error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); + } + } + return indexerType || anyType; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var text = ts.getTextOfPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; + var text = isLate ? getLateBoundNameFromType(nameType) : + isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : + ts.getTextOfPropertyName(name); // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getConstraintForLocation(propType, declaration.name); + if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); + } + return anyType; + } + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; + return errorType; } } } @@ -28546,33 +32740,38 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); + // If the parent is a tuple type, the rest element has an array type with a union of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = isTupleType(parentType) ? + getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; + var index_1 = pattern.elements.indexOf(declaration); + type = isTupleLikeType(parentType) ? + getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); } - return unknownType; + return errorType; } } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return declaration.initializer ? + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } @@ -28589,7 +32788,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 181 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -28599,11 +32798,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 219 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; + return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 220 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -28614,24 +32813,16 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = false; - if (includeOptionality) { - if (ts.isInJavaScriptFile(declaration) && ts.isParameter(declaration)) { - var parameterTags = ts.getJSDocParameterTags(declaration); - isOptional = !!(parameterTags && parameterTags.length > 0 && ts.find(parameterTags, function (tag) { return tag.isBracketed; })); - } - if (!ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken) { - isOptional = true; - } - } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); // Use type from type annotation if one is present var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 230 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 2097152 /* Ambient */)) { + declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no // initializer or a 'null' or 'undefined' initializer. @@ -28644,11 +32835,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 148 /* Parameter */) { + if (declaration.kind === 149 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 156 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 155 /* GetAccessor */); + if (func.kind === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -28661,13 +32852,7 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } @@ -28696,19 +32881,27 @@ var ts; return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = declaration.kind === 198 /* BinaryExpression */ ? declaration : - declaration.kind === 183 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 198 /* BinaryExpression */) : + var _loop_4 = function (declaration) { + var declarationInConstructor = false; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return unknownType; + return { value: errorType }; } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 154 /* Constructor */) { + var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); + if (special === 4 /* ThisProperty */) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -28722,26 +32915,95 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && + else if (jsDocType !== errorType && declarationType !== errorType && !isTypeIdenticalTo(jsDocType, declarationType) && !(symbol.flags & 67108864 /* JSContainer */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } - else if (!jsDocType) { + else if (!jsDocType && ts.isBinaryExpression(expression)) { // If we don't have an explicit JSDoc type, get the type from the expression. - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type_2); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + symbol.exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + } + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } + } + }; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var state_2 = _loop_4(declaration); + if (typeof state_2 === "object") + return state_2.value; + } + var type = jsDocType; + if (!type) { + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfSpecialPropertyOfBaseType(specialProperty) { + var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); } } - var type = jsDocType || getUnionType(types, 2 /* Subtype */); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - return checkDeclarationInitializer(element); + return addOptionality(checkDeclarationInitializer(element)); } if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -28755,12 +33017,12 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128 /* ObjectLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { // do not include computed properties in the implied type - hasComputedProperties = true; + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; return; } if (e.dotDotDotToken) { @@ -28775,24 +33037,24 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } return result; } // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } - // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; @@ -28807,7 +33069,9 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 178 /* ObjectBindingPattern */ + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -28821,13 +33085,15 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 1024 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -28844,7 +33110,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 148 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -28860,64 +33126,64 @@ var ts; if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol || symbol === moduleSymbol) { + return links.type = anyType; + } // Handle catch clause variables var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 247 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; } - if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + if (declaration.kind === 252 /* ExportAssignment */) { + return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 198 /* BinaryExpression */ || - declaration.kind === 183 /* PropertyAccessExpression */ && declaration.parent.kind === 198 /* BinaryExpression */) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isJSDocPropertyTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); + var type = getJSSpecialType(symbol, declaration); + if (!type) { + if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - } - else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -28926,9 +33192,57 @@ var ts; } return links.type; } + function getJSSpecialType(symbol, decl) { + if (!ts.isInJavaScriptFile(decl)) { + return undefined; + } + else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { + return getTypeFromTypeNode(decl.typeExpression.type); + } + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + else if (ts.isBinaryExpression(decl) || + ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { + return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || + getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else if (ts.isParameter(decl) + || ts.isPropertyDeclaration(decl) + || ts.isPropertySignature(decl) + || ts.isVariableDeclaration(decl) + || ts.isBindingElement(decl)) { + // Use type from type annotation if one is present + var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || + !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; + var declaredType = tryGetTypeFromEffectiveTypeNode(decl); + return declaredType && addOptionality(declaredType, isOptional) || + getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || + getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); + } + } + function getJSInitializerType(decl, symbol, init) { + if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { + var exports_1 = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports_1, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports_1, s.exports); + } + return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + } + } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 155 /* GetAccessor */) { + if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -28949,8 +33263,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 155 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 156 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -28958,7 +33272,7 @@ var ts; } } if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } var type = void 0; // First try to see if the user specified a return type on the get-accessor. @@ -28995,7 +33309,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 155 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); error(getter_1, 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, symbolToString(symbol)); } } @@ -29005,14 +33319,35 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 1081344 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { + var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } + else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || + symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { + links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } else { var type = createObjectType(16 /* Anonymous */, symbol); if (symbol.flags & 32 /* Class */) { @@ -29044,7 +33379,7 @@ var ts; // up recursively calling getTypeOfAlias, causing a stack overflow. links.type = targetSymbol.flags & 67216319 /* Value */ ? getTypeOfSymbol(targetSymbol) - : unknownType; + : errorType; } return links.type; } @@ -29053,11 +33388,11 @@ var ts; if (!links.type) { if (symbolInstantiationDepth === 100) { error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; + links.type = errorType; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -29074,7 +33409,7 @@ var ts; // Check if variable has type annotation that circularly references the variable itself if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; + return errorType; } // Otherwise variable has initializer that circularly references the variable itself if (noImplicitAny) { @@ -29104,7 +33439,7 @@ var ts; if (symbol.flags & 2097152 /* Alias */) { return getTypeOfAlias(symbol); } - return unknownType; + return errorType; } function isReferenceToType(type, target) { return type !== undefined @@ -29115,16 +33450,18 @@ var ts; function getTargetType(type) { return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. function hasBaseType(type, checkBase) { return check(type); function check(type) { if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 262144 /* Intersection */) { - return ts.forEach(type.types, check); + else if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, check); } + return false; } } // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. @@ -29133,46 +33470,47 @@ var ts; function appendTypeParameters(typeParameters, declarations) { for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - typeParameters = ts.appendIfUnique(typeParameters, tp); + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); } return typeParameters; } // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { - node = node.parent; + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead if (!node) { return undefined; } switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 280 /* JSDocFunctionType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 235 /* TypeAliasDeclaration */: - case 290 /* JSDocTemplateTag */: - case 176 /* MappedType */: - case 170 /* ConditionalType */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 287 /* JSDocFunctionType */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 240 /* TypeAliasDeclaration */: + case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 179 /* MappedType */: + case 173 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 176 /* MappedType */) { + if (node.kind === 179 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 170 /* ConditionalType */) { + else if (node.kind === 173 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 233 /* ClassDeclaration */ || node.kind === 203 /* ClassExpression */ || node.kind === 234 /* InterfaceDeclaration */) && + (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -29180,7 +33518,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 234 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -29189,12 +33527,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 234 /* InterfaceDeclaration */ || node.kind === 233 /* ClassDeclaration */ || - node.kind === 203 /* ClassExpression */ || node.kind === 235 /* TypeAliasDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 238 /* ClassDeclaration */ || + node.kind === 207 /* ClassExpression */ || + ts.isTypeAlias(node)) { var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -29218,22 +33556,14 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 1081344 /* TypeVariable */) { + if (type.flags & 2162688 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - var decl = type.symbol.valueDeclaration; - if (ts.isInJavaScriptFile(decl)) { - // Prefer an @augments tag because it may have type parameters. - var tag = ts.getJSDocAugmentsTag(decl); - if (tag) { - return tag.class; - } - } - return ts.getClassExtendsHeritageClauseElement(decl); + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -29256,31 +33586,31 @@ var ts; function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { var decl = type.symbol.valueDeclaration; - var extended = ts.getClassExtendsHeritageClauseElement(decl); + var extended = ts.getEffectiveBaseTypeNode(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { - return unknownType; + return errorType; } var baseConstructorType = checkExpression(baseTypeNode.expression); if (extended && baseTypeNode !== extended) { ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */)) { + if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; + return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; + return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; } @@ -29289,7 +33619,7 @@ var ts; function getBaseTypes(type) { if (!type.resolvedBaseTypes) { if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { if (type.symbol.flags & 32 /* Class */) { @@ -29308,7 +33638,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -29336,7 +33666,7 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - if (baseType === unknownType) { + if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { @@ -29370,18 +33700,18 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 234 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { + if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === ts.emptyArray) { @@ -29413,7 +33743,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 234 /* InterfaceDeclaration */) { + if (declaration.kind === 239 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -29454,7 +33784,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(32768 /* TypeParameter */); + type.thisType = createType(65536 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -29468,14 +33798,14 @@ var ts; // Note that we use the links object as the target here because the symbol object is used as the unique // identity for resolution of the 'type' property in SymbolLinks. if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { - return unknownType; + return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 291 /* JSDocTypedefTag */ || d.kind === 235 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 291 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. - var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -29487,27 +33817,38 @@ var ts; } } else { - type = unknownType; + type = errorType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } links.declaredType = type; } return links.declaredType; } + function isStringConcatExpression(expr) { + if (expr.kind === 9 /* StringLiteral */) { + return true; + } + else if (expr.kind === 202 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !(member.flags & 2097152 /* Ambient */); + return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 71 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 202 /* BinaryExpression */: + return isStringConcatExpression(expr); default: return false; } @@ -29520,7 +33861,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { @@ -29535,7 +33876,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -29547,10 +33888,10 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; memberTypeList.push(memberType); } @@ -29558,14 +33899,14 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 131072 /* Union */) { - enumType_1.flags |= 256 /* EnumLiteral */; + if (enumType_1.flags & 262144 /* Union */) { + enumType_1.flags |= 512 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; } } - var enumType = createType(16 /* Enum */); + var enumType = createType(32 /* Enum */); enumType.symbol = symbol; return links.declaredType = enumType; } @@ -29582,7 +33923,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(32768 /* TypeParameter */); + var type = createType(65536 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -29596,7 +33937,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { - return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; } function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -29627,6 +33968,7 @@ var ts; function isThislessType(node) { switch (node.kind) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 122 /* BooleanKeyword */: @@ -29636,11 +33978,11 @@ var ts; case 140 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 131 /* NeverKeyword */: - case 177 /* LiteralType */: + case 180 /* LiteralType */: return true; - case 166 /* ArrayType */: + case 167 /* ArrayType */: return isThislessType(node.elementType); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -29664,9 +34006,10 @@ var ts; */ function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); - return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } /** * Returns true if the class or interface member given by the symbol is free of "this" references. The @@ -29680,12 +34023,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -29715,6 +34058,9 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -29726,7 +34072,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 1120 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -29741,12 +34087,17 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } /** * Indicates whether a declaration has a dynamic name that cannot be late-bound. @@ -29764,12 +34115,13 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 1024 /* UniqueESSymbol */) { + if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 96 /* StringOrNumberLiteral */) { + if (type.flags & 192 /* StringOrNumberLiteral */) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } /** * Adds a declaration to a late-bound dynamic member. This performs the same function for @@ -29787,8 +34139,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -29844,16 +34195,12 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } - var symbolLinks_1 = getSymbolLinks(lateSymbol); - if (!symbolLinks_1.nameType) { - // Retain link to name type so that it can be reused later - symbolLinks_1.nameType = type; - } + lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); if (lateSymbol.parent) { ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); @@ -29883,8 +34230,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { - var member = members_3[_b]; + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -29936,7 +34283,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -30016,11 +34363,33 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -30092,6 +34461,7 @@ var ts; if (unionSignatures.length > 1) { var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } @@ -30159,7 +34529,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -30182,7 +34552,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_3(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -30192,6 +34562,7 @@ var ts; function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); @@ -30200,6 +34571,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); @@ -30218,7 +34590,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1081344 /* TypeVariable */)) { + if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -30258,6 +34630,7 @@ var ts; var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; members.set(prop.escapedName, inferredProp); @@ -30268,6 +34641,7 @@ var ts; function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; + var numberIndexInfo; // Resolve upfront such that recursive references see an empty object type. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, @@ -30277,35 +34651,30 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } } else { // First, if the constraint type is a type parameter, obtain the base constraint. Then, // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 7372800 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 524288 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } - setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbolOrIndex) { - var propertySymbol; - // forEachType delegates to forEach, which calls with a numeric second argument - // the type system currently doesn't catch this incompatibility, so we annotate - // the function ourselves to indicate the runtime behavior and deal with it here - if (typeof propertySymbolOrIndex === "object") { - propertySymbol = propertySymbolOrIndex; - } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t, _index, origin) { // Create a mapper from T to the current iteration type constituent. Then, if the // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. @@ -30313,7 +34682,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 32 /* StringLiteral */) { + if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -30327,16 +34696,19 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - prop.declarations = propertySymbol.declarations; + if (origin) { + prop.syntheticOrigin = origin; + prop.declarations = origin.declarations; } prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 2 /* String */)) { + else if (t.flags & (1 /* Any */ | 4 /* String */)) { stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } function getTypeParameterFromMappedType(type) { @@ -30345,23 +34717,29 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : - unknownType); + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 177 /* TypeOperator */ && + constraintDeclaration.operator === 128 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -30369,8 +34747,8 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; @@ -30393,11 +34771,11 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -30414,10 +34792,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 131072 /* Union */) { + else if (type.flags & 262144 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -30425,7 +34803,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -30434,7 +34812,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -30458,7 +34836,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { break; } } @@ -30468,13 +34846,24 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 393216 /* UnionOrIntersection */ ? + return type.flags & 786432 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + return obj.properties.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + if (expected && typeIsLiteralType(expected)) { + var actual = getTypeOfNode(property); + return !!actual && !isTypeIdenticalTo(actual, expected); + } + return false; + }); + } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 131072 /* Union */)) { + if (!(unionType.flags & 262144 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -30493,30 +34882,27 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 1048576 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 2097152 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getSimplifiedIndexedAccessType(type); - if (transformed) { - return transformed; - } - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { - // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. - // to avoid this, return `undefined`. - return undefined; - } - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; + var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; + var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; + return constraint && constraint !== errorType ? constraint : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; } function getConstraintOfDistributiveConditionalType(type) { // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained @@ -30525,10 +34911,13 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); - return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 32768 /* Never */)) { + return instantiated; + } } } return undefined; @@ -30536,20 +34925,54 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { - if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 15794176 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 262144 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 16809468 /* DisjointDomains */) { + hasDisjointDomainType = true; } } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 16809468 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; } function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 524288 /* Index */) { - return stringType; + if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -30567,63 +34990,60 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(t); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 32768 /* TypeParameter */) { + if (t.flags & 65536 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 393216 /* UnionOrIntersection */) { + if (t.flags & 786432 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 131072 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 262144 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 524288 /* Index */) { - return stringType; + if (t.flags & 1048576 /* Index */) { + return keyofConstraintType; } - if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getSimplifiedIndexedAccessType(t); - if (transformed) { - return getBaseConstraint(transformed); - } + if (t.flags & 2097152 /* IndexedAccess */) { 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; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 2097152 /* Conditional */) { + if (t.flags & 4194304 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 4194304 /* Substitution */) { + if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } if (isGenericMappedType(t)) { @@ -30684,18 +35104,20 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 7897088 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 262144 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 524322 /* StringLike */ ? globalStringType : - t.flags & 84 /* NumberLike */ ? globalNumberType : - t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 1536 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 134217728 /* NonPrimitive */ ? emptyObjectType : - t; + var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var isUnion = containingType.flags & 131072 /* Union */; + var indexTypes; + var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -30704,7 +35126,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== unknownType) { + if (type !== errorType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -30715,41 +35137,65 @@ var ts; (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); - if (!isMethodLike(prop)) { + if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } - var propTypes = []; - var declarations = []; + var declarations; var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (!commonType) { + if (first) { commonType = type; + nameType = prop.nameType; + first = false; } - else if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } result.declarations = declarations; + result.nameType = nameType; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } @@ -30784,7 +35230,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -30798,13 +35244,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 393216 /* UnionOrIntersection */) { + if (type.flags & 786432 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 458752 /* StructuredType */) { + if (type.flags & 917504 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -30818,7 +35264,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 458752 /* StructuredType */) { + if (type.flags & 917504 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -30856,10 +35302,10 @@ var ts; // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - result = ts.appendIfUnique(result, tp); - }); + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } return result; } function symbolsToArray(symbols) { @@ -30872,23 +35318,13 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279 /* JSDocOptionalType */; - } - } - } - } + return ts.isInJavaScriptFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 286 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -30899,14 +35335,14 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { var signature = getSignatureFromDeclaration(node.parent); var parameterIndex = node.parent.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; + return parameterIndex >= getMinArgumentCount(signature); } var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { @@ -30916,6 +35352,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -30948,14 +35391,6 @@ var ts; } return minTypeArgumentCount; } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { @@ -30973,7 +35408,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -30990,16 +35425,21 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct // signature. for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); @@ -31012,29 +35452,30 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177 /* LiteralType */) { + if (type && type.kind === 180 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 155 /* GetAccessor */ || declaration.kind === 156 /* SetAccessor */) && + if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 155 /* GetAccessor */ ? 156 /* SetAccessor */ : 155 /* GetAccessor */; + var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 154 /* Constructor */ ? + var classType = declaration.kind === 155 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -31051,7 +35492,7 @@ var ts; * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -31059,9 +35500,8 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; - syntheticArgsSymbol.isRestParameter = true; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. parameters.pop(); @@ -31071,7 +35511,7 @@ var ts; } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 } else if (classType) { return classType; @@ -31082,14 +35522,23 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 155 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 156 /* SetAccessor */); + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); return getAnnotatedAccessorType(setter); } + var typeFromTag = getReturnTypeOfTypeTag(declaration); + if (typeFromTag) { + return typeFromTag; + } if (ts.nodeIsMissing(declaration.body)) { return anyType; } } + function getReturnTypeOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signatures = typeTag && typeTag.typeExpression && getSignaturesOfType(getTypeFromTypeNode(typeTag.typeExpression), 0 /* Call */); + return signatures && signatures.length === 1 ? getReturnTypeOfSignature(signatures[0]) : undefined; + } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); if (links.containsArgumentsReference === undefined) { @@ -31107,14 +35556,14 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return node.name.kind === 146 /* ComputedPropertyName */ + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return node.name.kind === 147 /* ComputedPropertyName */ && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -31123,33 +35572,19 @@ var ts; return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* JSDocFunctionType */: - // Don't include signature if node is the implementation of an overloaded function. A node is considered - // an implementation node if it has a body and the previous node is of the same kind and immediately - // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } } + result.push(getSignatureFromDeclaration(decl)); } return result; } @@ -31181,9 +35616,9 @@ var ts; signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; } else { - var declaration = signature.declaration; - signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 160 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type) : noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); @@ -31193,7 +35628,7 @@ var ts; function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { - return unknownType; + return errorType; } var type = void 0; if (signature.target) { @@ -31226,16 +35661,16 @@ var ts; return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + var type = getTypeOfRestParameter(signature); + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -31288,7 +35723,7 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -31307,10 +35742,10 @@ var ts; if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var node = decl; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); if (node.parameters.length === 1) { var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + if (parameter.type && parameter.type.kind === syntaxKind) { return node; } } @@ -31329,44 +35764,54 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return type.symbol && ts.getDeclarationOfKind(type.symbol, 147 /* TypeParameter */).constraint; + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + return decl && decl.constraint; } function getInferredTypeParameterConstraint(typeParameter) { var inferences; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - // When an 'infer T' declaration is immediately contained in a type reference node - // (such as 'Foo'), T's constraint is inferred from the constraint of the - // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are - // present, we form an intersection of the inferred constraint types. - if (declaration.parent.kind === 171 /* InferType */ && declaration.parent.parent.kind === 161 /* TypeReference */) { - var typeReference = declaration.parent.parent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(declaration.parent); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); - if (declaredConstraint) { - // Type parameter constraints can reference other type parameters so - // constraints need to be instantiated. If instantiation produces the - // type parameter itself, we discard that inference. For example, in - // type Foo = [T, U]; - // type Bar = T extends Foo ? Foo : T; - // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); - var constraint = instantiateType(declaredConstraint, mapper); - if (constraint !== typeParameter) { - inferences = ts.append(inferences, constraint); + if (declaration.parent.kind === 174 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 162 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } } } } } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } } } } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -31382,7 +35827,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 147 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -31419,7 +35864,7 @@ var ts; result |= type.flags; } } - return result & 117440512 /* PropagatingFlags */; + return result & 939524096 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -31456,7 +35901,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 285 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -31468,7 +35913,7 @@ var ts; error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) - return unknownType; + return errorType; } } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -31477,7 +35922,7 @@ var ts; var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } - return checkNoTypeArguments(node, symbol) ? type : unknownType; + return checkNoTypeArguments(node, symbol) ? type : errorType; } function getTypeAliasInstantiation(symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); @@ -31505,17 +35950,17 @@ var ts; error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; + return errorType; } return getTypeAliasInstantiation(symbol, typeArguments); } - return checkNoTypeArguments(node, symbol) ? type : unknownType; + return checkNoTypeArguments(node, symbol) ? type : errorType; } function getTypeReferenceName(node) { switch (node.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -31535,7 +35980,7 @@ var ts; function getTypeReferenceType(node, symbol) { var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { - return unknownType; + return errorType; } var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); if (type) { @@ -31545,27 +35990,42 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : - unknownType; + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + errorType; } if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { - return unknownType; + return errorType; } - // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If - // the symbol is a constructor function, return the inferred class type; otherwise, - // the type of this reference is just the type of the value we resolved to. - var assignedType = getAssignedClassType(symbol); - var valueType = getTypeOfSymbol(symbol); - var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); - return valueType; + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -31578,13 +36038,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(4194304 /* Substitution */); + var result = createType(8388608 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 167 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -31593,9 +36053,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (ts.isPartOfTypeNode(node)) { + while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -31606,11 +36066,11 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 1048576 /* JSDoc */ && node.kind === 161 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : ts.declarationNameToString(node.typeName)); + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); return false; } return true; @@ -31653,7 +36113,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -31664,7 +36124,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 8192 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -31697,7 +36157,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -31707,9 +36167,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: return declaration; } } @@ -31718,7 +36178,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 65536 /* Object */)) { + if (!(type.flags & 131072 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -31748,6 +36208,9 @@ var ts; function getGlobalTemplateStringsArrayType() { return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } @@ -31786,6 +36249,9 @@ var ts; var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -31824,18 +36290,26 @@ var ts; // // Note that the generic type created by this function has no symbol associated with it. The same // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(32768 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */, "" + i); - property.type = typeParameter; - properties.push(property); + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); var lengthSymbol = createSymbol(4 /* Property */, "length"); - lengthSymbol.type = getLiteralType(arity); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); properties.push(lengthSymbol); var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; @@ -31845,7 +36319,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(32768 /* TypeParameter */); + type.thisType = createType(65536 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -31853,38 +36327,75 @@ var ts; type.declaredConstructSignatures = ts.emptyArray; type.declaredStringIndexInfo = undefined; type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; return type; } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); } return links.resolvedType; } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } function getTypeId(type) { return type.id; } function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } - // Return true if the given intersection type contains (a) more than one unit type or (b) an object - // type and a nullable type (null or undefined). + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 13536 /* Unit */ && combined & 13536 /* Unit */) { + if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { return true; } combined |= t.flags; - if (combined & 12288 /* Nullable */ && combined & (65536 /* Object */ | 134217728 /* NonPrimitive */)) { + if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || + combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || + combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || + combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || + combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || + combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { return true; } } @@ -31892,41 +36403,31 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 131072 /* Union */) { - includes = addTypesToUnion(typeSet, includes, type.types); + if (flags & 262144 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); } - else if (flags & 1 /* Any */) { - includes |= 1 /* Any */; - if (type === wildcardType) - includes |= 4096 /* Wildcard */; - } - else if (!strictNullChecks && flags & 12288 /* Nullable */) { - if (flags & 4096 /* Undefined */) - includes |= 2 /* Undefined */; - if (flags & 8192 /* Null */) - includes |= 4 /* Null */; - if (!(flags & 16777216 /* ContainsWideningType */)) - includes |= 16 /* NonWideningType */; - } - else if (!(flags & 16384 /* Never */ || flags & 262144 /* Intersection */ && isEmptyIntersectionType(type))) { - // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are - // another form of 'never' (in that they have an empty value domain). We could in theory turn - // intersections of unit types into 'never' upon construction, but deferring the reduction makes it - // easier to reason about their origin. - if (flags & 2 /* String */) - includes |= 32 /* String */; - if (flags & 4 /* Number */) - includes |= 64 /* Number */; - if (flags & 512 /* ESSymbol */) - includes |= 128 /* ESSymbol */; - if (flags & 1120 /* StringOrNumberLiteralOrUnique */) - includes |= 256 /* LiteralOrUniqueESSymbol */; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); - if (index < 0) { - if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } } } } @@ -31963,11 +36464,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 256 /* EnumLiteral */) { + if (first.flags & 512 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -31992,10 +36493,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 32 /* StringLiteral */ && includes & 32 /* String */ || - t.flags & 64 /* NumberLiteral */ && includes & 64 /* Number */ || - t.flags & 1024 /* UniqueESSymbol */ && includes & 128 /* ESSymbol */ || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 8388608 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || + t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -32018,12 +36519,12 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 1 /* Any */) { - return includes & 4096 /* Wildcard */ ? wildcardType : anyType; + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 256 /* LiteralOrUniqueESSymbol */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -32032,11 +36533,11 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 4 /* Null */ ? includes & 16 /* NonWideningType */ ? nullType : nullWideningType : - includes & 2 /* Undefined */ ? includes & 16 /* NonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -32073,7 +36574,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -32083,8 +36584,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(131072 /* Union */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); + type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; /* @@ -32101,35 +36602,29 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Intersection */) { - includes = addTypesToIntersection(typeSet, includes, type.types); + if (flags & 524288 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); } - else if (flags & 1 /* Any */) { - includes |= 1 /* Any */; - if (type === wildcardType) - includes |= 4096 /* Wildcard */; + if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + includes |= 536870912 /* EmptyObject */; } - else if (flags & 16384 /* Never */) { - includes |= 8 /* Never */; - } - else if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 1024 /* EmptyObject */; - } - else if ((strictNullChecks || !(flags & 12288 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (flags & 65536 /* Object */) { - includes |= 512 /* ObjectType */; + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; } - if (flags & 131072 /* Union */) { - includes |= 2048 /* Union */; - } - if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && + !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && + containsIdenticalType(typeSet, type))) { typeSet.push(type); } } @@ -32144,6 +36639,44 @@ var ts; } return includes; } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || + t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // When intersecting unions of unit types we can simply intersect based on type identity. + // Here we remove all unions of unit types from the given list and replace them with a + // a single union containing an intersection of the unit types. + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_6 = function () { + var t = types[i]; + if (t.flags & 67108864 /* UnionOfUnitTypes */) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_6(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + return true; + } // We normalize combinations of intersection and union types based on the distributive property of the '&' // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection // types with union type constituents into equivalent union types with intersection type constituents and @@ -32155,35 +36688,49 @@ var ts; // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 8 /* Never */) { + if (includes & 32768 /* Never */) { return neverType; } if (includes & 1 /* Any */) { - return includes & 4096 /* Wildcard */ ? wildcardType : anyType; + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) { + if (!strictNullChecks && includes & 24576 /* Nullable */) { + return includes & 8192 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || + includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return unknownType; + } if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 2048 /* Union */) { + if (includes & 262144 /* Union */) { + if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(262144 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); + type = createType(524288 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -32194,46 +36741,67 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(524288 /* Index */); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; + function createIndexType(type, stringsOnly) { + var result = createType(1048576 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; } - function getLiteralTypeFromPropertyName(prop) { - var links = getSymbolLinks(getLateBoundSymbol(prop)); - if (!links.nameType) { - if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol) { - ts.Debug.assert(links.target.escapedName === prop.escapedName || links.target.escapedName === "__computed" /* Computed */, "Target symbol and symbol do not have the same name"); - links.nameType = getLiteralTypeFromPropertyName(links.target); + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : + name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : + getLiteralType(ts.symbolName(prop)); } - else { - links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + if (type && type.flags & include) { + return type; } } - return links.nameType; + return neverType; } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + function getLiteralTypeFromPropertyNames(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); } - function getIndexType(type) { - return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : - maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : + getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; } function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType.flags & 16384 /* Never */ ? stringType : indexType; + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 32768 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); @@ -32245,20 +36813,20 @@ var ts; case 141 /* UniqueKeyword */: links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) - : unknownType; + : errorType; break; } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(1048576 /* IndexedAccess */); + var type = createType(2097152 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 184 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : @@ -32270,7 +36838,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; + return errorType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -32278,72 +36846,101 @@ var ts; } return getTypeOfSymbol(prop); } + if (isTupleType(objectType)) { + var restType = getRestTypeOfTupleType(objectType); + if (restType && isNumericLiteralName(propName) && +propName >= 0) { + return restType; + } + } } - if (!(indexType.flags & 12288 /* Nullable */) && isTypeAssignableToKind(indexType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */)) { + if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { if (isTypeAny(objectType)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else 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 indexInfo.type; } + if (indexType.flags & 32768 /* Never */) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } } } return anyType; } } if (accessNode) { - var indexNode = accessNode.kind === 184 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } - else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); } else { error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } - return unknownType; } - return anyType; + return errorType; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */ | 536870912 /* GenericMappedType */); + return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */ | 524288 /* Index */); + return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } // 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 & 65536 /* Object */ && !isGenericMappedType(type)) { + if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedType(type) { + return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return - // undefined if no transformation is possible. + // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type) { - var objectType = type.objectType; - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { // 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 @@ -32360,8 +36957,8 @@ var ts; regularTypes.push(t); } } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + return type.simplified = getUnionType([ + getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); } @@ -32371,22 +36968,23 @@ var ts; // eventually anyway, but it easier to reason about. if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } // If the object type is a mapped type { [P in K]: E }, where K is generic, 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. + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 32768 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + if (objectType.flags & 65536 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return undefined; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -32402,8 +37000,8 @@ var ts; // 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 === 184 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { - if (objectType.flags & 1 /* Any */) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. @@ -32418,13 +37016,13 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 131072 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { + if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === unknownType) { - return unknownType; + if (propType === errorType) { + return errorType; } propTypes.push(propType); } @@ -32438,7 +37036,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 1048576 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -32451,7 +37049,7 @@ var ts; var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; // Eagerly resolve the constraint type which forces an error if the constraint type circularly // references itself through one or more type aliases. @@ -32460,7 +37058,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 4194304 /* Substitution */ ? type.typeVariable : type; + return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -32471,15 +37069,21 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088 /* Instantiable */)) { - var combinedMapper = void 0; - if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); - combinedMapper = combineTypeMappers(mapper, context); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { @@ -32504,13 +37108,14 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(2097152 /* Conditional */); + var result = createType(4194304 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; result.mapper = mapper; + result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } function getTrueTypeFromConditionalType(type) { @@ -32530,24 +37135,39 @@ var ts; } return result; } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 173 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); - var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { node: node, checkType: checkType, extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 32768 /* TypeParameter */), + isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); @@ -32565,6 +37185,78 @@ var ts; } return links.resolvedType; } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol_1; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol_1.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67216319 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67216319 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -32576,7 +37268,7 @@ var ts; else { var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -32586,10 +37278,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 235 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } /** @@ -32601,19 +37292,22 @@ var ts; if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } - if (left.flags & 16384 /* Never */) { + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 32768 /* Never */) { return right; } - if (right.flags & 16384 /* Never */) { + if (right.flags & 32768 /* Never */) { return left; } - if (left.flags & 131072 /* Union */) { + if (left.flags & 262144 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 131072 /* Union */) { + if (right.flags & 262144 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */ | 134217728 /* NonPrimitive */)) { + if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { return left; } var members = ts.createSymbolTable(); @@ -32658,6 +37352,7 @@ var ts; result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; + result.nameType = leftProp.nameType; members.set(leftProp.escapedName, result); } } @@ -32666,7 +37361,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 33554432 /* ContainsObjectLiteral */; + spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } @@ -32678,6 +37373,7 @@ var ts; var result = createSymbol(flags, prop.escapedName); result.type = getTypeOfSymbol(prop); result.declarations = prop.declarations; + result.nameType = prop.nameType; result.syntheticOrigin = prop; return result; } @@ -32697,9 +37393,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 8388608 /* FreshLiteral */)) { + if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 8388608 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32708,7 +37404,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -32719,7 +37417,7 @@ var ts; var key = enumId ? enumId + qualifier + value : qualifier + value; var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; @@ -32732,7 +37430,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(1024 /* UniqueESSymbol */); + var type = createType(2048 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -32747,14 +37445,14 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 234 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 154 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; + return errorType; } function getTypeFromThisTypeNode(node) { var links = getNodeLinks(node); @@ -32766,9 +37464,11 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return anyType; + case 142 /* UnknownKeyword */: + return unknownType; case 137 /* StringKeyword */: return stringType; case 134 /* NumberKeyword */: @@ -32787,61 +37487,67 @@ var ts; return neverType; case 135 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 173 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return getTypeFromTypeReference(node); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return booleanType; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 167 /* TupleType */: + case 168 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 168 /* UnionType */: + case 169 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 171 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 169 /* IntersectionType */: + case 172 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 277 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 279 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 172 /* ParenthesizedType */: - case 278 /* JSDocNonNullableType */: - case 274 /* JSDocTypeExpression */: + case 175 /* ParenthesizedType */: + case 170 /* RestType */: + case 285 /* JSDocNonNullableType */: + case 281 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 280 /* JSDocFunctionType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 176 /* MappedType */: + case 179 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 171 /* InferType */: + case 174 /* InferType */: return getTypeFromInferTypeNode(node); + case 181 /* ImportType */: + return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 71 /* Identifier */: - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 default: - return unknownType; + return errorType; } } function instantiateList(items, mapper, instantiator) { @@ -32918,10 +37624,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 32768 /* TypeParameter */ ? wildcardType : type; + return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(32768 /* TypeParameter */); + var result = createType(65536 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -32967,7 +37673,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 65536 /* Object */ | 7897088 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -32981,7 +37687,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -32989,8 +37695,8 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } - if (symbol.isRestParameter) { - result.isRestParameter = symbol.isRestParameter; + if (symbol.nameType) { + result.nameType = symbol.nameType; } return result; } @@ -33005,10 +37711,24 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJavaScriptConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : - outerTypeParameters; + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; links.outerTypeParameters = typeParameters; if (typeParameters.length) { links.instantiations = ts.createMap(); @@ -33032,27 +37752,32 @@ var ts; } return type; } + function maybeTypeParameterReference(node) { + return !(node.kind === 146 /* QualifiedName */ || + node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_2; })) { - return ts.forEachChild(node, containsReference); + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 173 /* ThisType */: - return tp.isThisType; + case 176 /* ThisType */: + return !!tp.isThisType; case 71 /* Identifier */: - return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; - case 164 /* TypeQuery */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 165 /* TypeQuery */: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -33062,9 +37787,9 @@ var ts; // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a // union type A | undefined, we produce { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 524288 /* Index */) { + if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 32768 /* TypeParameter */) { + if (typeVariable_1.flags & 65536 /* TypeParameter */) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -33079,7 +37804,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (1 /* Any */ | 7372800 /* InstantiableNonPrimitive */ | 65536 /* Object */ | 262144 /* Intersection */); + return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); @@ -33117,7 +37842,7 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } @@ -33125,10 +37850,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { - if (type.flags & 32768 /* TypeParameter */) { + if (type.flags & 65536 /* TypeParameter */) { return mapper(type); } - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need @@ -33145,33 +37870,33 @@ var ts; return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } } - if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { + if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { var types = type.types; var newTypes = instantiateTypes(types, mapper); return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; } - if (type.flags & 262144 /* Intersection */) { + if (type.flags & 524288 /* Intersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; } - if (type.flags & 524288 /* Index */) { + if (type.flags & 1048576 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 1048576 /* IndexedAccess */) { + if (type.flags & 2097152 /* IndexedAccess */) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } - if (type.flags & 2097152 /* Conditional */) { + if (type.flags & 4194304 /* Conditional */) { return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } - if (type.flags & 4194304 /* Substitution */) { + if (type.flags & 8388608 /* Substitution */) { return instantiateType(type.typeVariable, mapper); } } return type; } function getWildcardInstantiation(type) { - return type.flags & (16382 /* Primitive */ | 1 /* Any */ | 16384 /* Never */) ? type : + return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -33180,34 +37905,38 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 182 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); - case 181 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); - case 199 /* ConditionalExpression */: + case 186 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 185 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 203 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 261 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 260 /* JsxAttribute */: + case 266 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive); + case 265 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 263 /* JsxExpression */: + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 268 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -33217,10 +37946,10 @@ var ts; return false; } // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 191 /* ArrowFunction */) { + if (node.kind !== 195 /* 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); @@ -33229,13 +37958,15 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 211 /* Block */ ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -33246,7 +37977,7 @@ var ts; return result; } } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -33276,9 +38007,9 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 131072 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 131072 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 7372800 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : hasBaseType(source, getTargetType(target)); } @@ -33298,8 +38029,206 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeAssignableTo(source, target)) + return true; + if (!elaborateError(expr, source, target)) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function elaborateError(node, source, target) { + if (!node) + return false; + switch (node.kind) { + case 268 /* JsxExpression */: + case 193 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target); + case 202 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return elaborateError(node.right, source, target); + } + break; + case 186 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target); + case 185 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target); + case 266 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target); + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var sourcePropType = getIndexedAccessType(source, nameType); + var targetPropType = getIndexedAccessType(target, nameType); + if (!isTypeAssignableTo(sourcePropType, targetPropType)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target) { + return elaborateElementwise(generateJsxAttributes(node), source, target); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 32768 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 157 /* SetAccessor */: return [3 /*break*/, 2]; + case 156 /* GetAccessor */: return [3 /*break*/, 2]; + case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target); } /** * This is *not* a bi-directional relationship. @@ -33320,16 +38249,23 @@ var ts; if (source === target) { return -1 /* True */; } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } + var sourceCount = getParameterCount(source); + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + return 0 /* False */; + } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 153 /* MethodDeclaration */ && - kind !== 152 /* MethodSignature */ && kind !== 154 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && + kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -33347,14 +38283,11 @@ var ts; result &= related; } } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var paramCount = Math.max(sourceCount, targetCount); + var lastIndex = paramCount - 1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -33366,13 +38299,14 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); + (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return 0 /* False */; } @@ -33389,7 +38323,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -33447,30 +38381,6 @@ var ts; } return false; } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - // If both have rest parameters, get the max and add 1 to - // compensate for the rest parameter. - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - // Return the count for whichever signature doesn't have rest parameters. - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } function isEmptyResolvedType(t) { return t.properties.length === 0 && t.callSignatures.length === 0 && @@ -33479,10 +38389,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 134217728 /* NonPrimitive */ ? true : - type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 /* NonPrimitive */ ? true : + type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -33491,11 +38401,11 @@ var ts; } var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; } if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { - enumRelation.set(id, false); + enumRelation.set(id, 3 /* FailedAndReported */); return false; } var targetEnumType = getTypeOfSymbol(targetSymbol); @@ -33506,55 +38416,58 @@ var ts; if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); } - enumRelation.set(id, false); return false; } } } - enumRelation.set(id, true); + enumRelation.set(id, 1 /* Succeeded */); return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 1 /* Any */ || s & 16384 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) return true; - if (t & 16384 /* Never */) + if (t & 32768 /* Never */) return false; - if (s & 524322 /* StringLike */ && t & 2 /* String */) + if (s & 68 /* StringLike */ && t & 4 /* String */) return true; - if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && - t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && + t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 84 /* NumberLike */ && t & 4 /* Number */) + if (s & 168 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && - t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && + t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) + if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) return true; - if (s & 1536 /* ESSymbolLike */ && t & 512 /* ESSymbol */) + if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) return true; - if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { - if (s & 131072 /* Union */ && t & 131072 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { + if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 224 /* Literal */ && t & 224 /* Literal */ && + if (s & 448 /* Literal */ && t & 448 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 4096 /* Undefined */ && (!strictNullChecks || t & (4096 /* Undefined */ | 2048 /* Void */))) + if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) return true; - if (s & 8192 /* Null */ && (!strictNullChecks || t & 8192 /* Null */)) + if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) return true; - if (s & 65536 /* Object */ && t & 134217728 /* NonPrimitive */) + if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) return true; - if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) + if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -33562,30 +38475,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) + if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { + if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 8388608 /* FreshLiteral */) { + if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { + if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 8355840 /* StructuredOrInstantiable */ || target.flags & 8355840 /* StructuredOrInstantiable */) { + if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -33603,7 +38516,7 @@ var ts; * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. * @param containingMessageChain A chain of errors to prepend any new errors found. */ - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; var maybeKeys; var sourceStack; @@ -33625,18 +38538,24 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement - if (headMessage && errorNode && !result && source.symbol) { - var links = getSymbolLinks(source.symbol); - if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { - var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); - if (helpfulRetry) { - // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import - diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } } } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { @@ -33674,7 +38593,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 393216 /* UnionOrIntersection */)) { + if (!(type.flags & 786432 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -33682,7 +38601,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 12288 /* Nullable */) { + if (t.flags & 24576 /* Nullable */) { continue; } if (seenNonNullable) { @@ -33699,29 +38618,52 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { + if (reportErrors === void 0) { reportErrors = false; } + if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 8388608 /* FreshLiteral */) { + if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } - if (source.flags & 4194304 /* Substitution */) { + if (source.flags & 8388608 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 4194304 /* Substitution */) { + if (target.flags & 8388608 /* Substitution */) { target = target.typeVariable; } + if (source.flags & 2097152 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 2097152 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); + if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + target = nullStrippedTarget; + } + } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 8388608 /* FreshLiteral */) { - var discriminantType = target.flags & 131072 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { + var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -33737,8 +38679,8 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 393216 /* UnionOrIntersection */) && - !(target.flags & 131072 /* Union */) && + !(source.flags & 786432 /* UnionOrIntersection */) && + !(target.flags & 262144 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && @@ -33764,20 +38706,20 @@ var ts; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); } else { - if (target.flags & 131072 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */) && !(target.flags & 16382 /* Primitive */)); + if (target.flags & 262144 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); } - else if (target.flags & 262144 /* Intersection */) { + else if (target.flags & 524288 /* Intersection */) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 262144 /* Intersection */) { + else if (source.flags & 524288 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -33793,20 +38735,47 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 8355840 /* StructuredOrInstantiable */ || target.flags & 8355840 /* StructuredOrInstantiable */)) { + if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } } } + if (!result && source.flags & 524288 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 65536 /* Object */ && target.flags & 16382 /* Primitive */) { + if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 65536 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } + else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } reportRelationError(headMessage, source, target); } return result; @@ -33814,27 +38783,27 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 65536 /* Object */) { + if (flags & 131072 /* Object */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } - if (flags & (131072 /* Union */ | 262144 /* Intersection */)) { + if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 524288 /* Index */) { + if (flags & 1048576 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - if (flags & 1048576 /* IndexedAccess */) { + if (flags & 2097152 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { return result; } } } - if (flags & 2097152 /* Conditional */) { + if (flags & 4194304 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { @@ -33847,13 +38816,13 @@ var ts; } } } - if (flags & 4194304 /* Substitution */) { + if (flags & 8388608 /* Substitution */) { return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { - if (maybeTypeOfKind(target, 65536 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -33863,13 +38832,14 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_4 = function (prop) { + var _loop_7 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. @@ -33883,8 +38853,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -33900,9 +38871,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_4(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -33922,7 +38893,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 131072 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -33933,11 +38904,35 @@ var ts; } } if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 131072 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -33980,7 +38975,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 131072 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -34069,9 +39064,8 @@ var ts; var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2 /* Failed */) { - // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported - // failure and continue computing the relation such that errors get reported. - relation.set(id, 3 /* FailedAndReported */); + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. } else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; @@ -34132,7 +39126,7 @@ var ts; var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 32768 /* TypeParameter */) { + if (target.flags & 65536 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { @@ -34144,25 +39138,28 @@ var ts; } } } - else if (target.flags & 524288 /* Index */) { + else if (target.flags & 1048576 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 524288 /* Index */) { + if (source.flags & 1048576 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the - // constraint of T. - var constraint = getConstraintForRelation(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { + return result; + } } } } - else if (target.flags & 1048576 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of T. + else if (target.flags & 2097152 /* IndexedAccess */) { + // A type S is related to a type T[K] if S is related to C, where C is the + // constraint of T[K] var constraint = getConstraintForRelation(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -34176,7 +39173,7 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 1048576 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } @@ -34191,32 +39188,9 @@ var ts; } } } - if (source.flags & 32768 /* TypeParameter */) { - var constraint = getConstraintForRelation(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 134217728 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - else if (source.flags & 1048576 /* IndexedAccess */) { - // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintForRelation(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 1048576 /* IndexedAccess */) { + if (source.flags & 2162688 /* TypeVariable */) { + if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); } @@ -34225,11 +39199,35 @@ var ts; return result; } } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } - else if (source.flags & 2097152 /* Conditional */) { - if (target.flags & 2097152 /* Conditional */) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { + else if (source.flags & 1048576 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Conditional */) { + if (target.flags & 4194304 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } @@ -34292,14 +39290,14 @@ var ts; } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 16382 /* Primitive */); + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (65536 /* Object */ | 262144 /* Intersection */) && target.flags & 65536 /* Object */) { + if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; // An empty object type is related to any mapped type that includes a '?' modifier. @@ -34342,10 +39340,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -34354,7 +39352,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -34377,6 +39375,33 @@ var ts; } } var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } var properties = getPropertiesOfObjectType(target); for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { var targetProp = properties_3[_b]; @@ -34389,13 +39414,14 @@ var ts; var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } return 0 /* False */; } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (hasDifferingDeclarations) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -34453,14 +39479,14 @@ var ts; * and no required properties, call/construct signatures or index signatures */ function isWeakType(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); } - if (type.flags & 262144 /* Intersection */) { + if (type.flags & 524288 /* Intersection */) { return ts.every(type.types, isWeakType); } return false; @@ -34476,7 +39502,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */)) { + if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -34544,7 +39570,7 @@ var ts; // in the context of the target signature before checking the relationship. Ideally we'd do // this regardless of the number of signatures, but the potential costs are prohibitive due // to the quadratic nature of the logic below. - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -34600,8 +39626,7 @@ var ts; continue; } // Skip over symbol-named members - var nameType = getLiteralTypeFromPropertyName(prop); - if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -34629,7 +39654,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -34641,7 +39666,7 @@ var ts; 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); + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 } if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; @@ -34751,17 +39776,17 @@ var ts; // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 2048 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -34851,13 +39876,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 65536 /* Object */) { + if (depth >= 5 && type.flags & 131072 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 65536 /* Object */ && t.symbol === symbol) { + if (t.flags & 131072 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -34898,20 +39923,26 @@ var ts; return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); // A source signature matches a target signature if the two signatures have the same number of required, // optional, and rest parameters. - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { return true; } // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = sourceHasRestParameter ? 1 : 0; + var targetRestCount = targetHasRestParameter ? 1 : 0; + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { return true; } return false; @@ -34953,10 +39984,10 @@ var ts; } } } - var targetLen = target.parameters.length; + var targetLen = getParameterCount(target); for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); var related = compareTypes(s, t); if (!related) { return 0 /* False */; @@ -34976,9 +40007,6 @@ var ts; function compareTypePredicatesIdentical(source, target, compareTypes) { return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } function literalTypesWithSameBaseType(types) { var commonBaseType; for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { @@ -35005,9 +40033,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -35015,48 +40043,56 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 12288 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + return isTupleType(type) ? + index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : + getTypeOfPropertyOfType(type, "" + index); + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 13536 /* Unit */); + return !!(type.flags & 27072 /* Unit */); } function isLiteralType(type) { - return type.flags & 8 /* Boolean */ ? true : - type.flags & 131072 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + return type.flags & 16 /* Boolean */ ? true : + type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : + type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 1024 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -35072,6 +40108,12 @@ var ts; function isTupleType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } function getFalsyFlagsOfTypes(types) { var result = 0; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { @@ -35084,27 +40126,27 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 131072 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : - type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 14574 /* PossiblyFalsy */; + return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : + type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 14560 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); } function getDefinitelyFalsyPartOfType(type) { - return type.flags & 2 /* String */ ? emptyStringType : - type.flags & 4 /* Number */ ? zeroType : - type.flags & 8 /* Boolean */ || type === falseType ? falseType : - type.flags & (2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */) || - type.flags & 32 /* StringLiteral */ && type.value === "" || - type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : neverType; } /** @@ -35113,15 +40155,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (4096 /* Undefined */ | 8192 /* Null */); + var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); return missing === 0 ? type : - missing === 4096 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 8192 /* Null */ ? getUnionType([type, nullType]) : + missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 16384 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -35131,7 +40173,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -35153,6 +40195,9 @@ var ts; if (source.valueDeclaration) { symbol.valueDeclaration = source.valueDeclaration; } + if (source.nameType) { + symbol.nameType = source.nameType; + } return symbol; } function transformTypeOfMembers(type, f) { @@ -35171,7 +40216,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 8388608 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -35181,13 +40226,13 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~8388608 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } function createWideningContext(parent, propertyName, siblings) { - return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; } function getSiblingsOfContext(context) { if (!context.siblings) { @@ -35207,55 +40252,54 @@ var ts; } return context.siblings; } - function getPropertyNamesOfContext(context) { - if (!context.resolvedPropertyNames) { + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { var names = ts.createMap(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; - names.set(prop.escapedName, true); + names.set(prop.escapedName, prop); } } } - context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + context.resolvedProperties = ts.arrayFrom(names.values()); } - return context.resolvedPropertyNames; + return context.resolvedProperties; } function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } var original = getTypeOfSymbol(prop); var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getUndefinedProperty(name) { - var cached = undefinedProperties.get(name); + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); if (cached) { return cached; } - var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); - result.type = undefinedType; - var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); - if (associatedKeyType.flags & 32 /* StringLiteral */) { - result.nameType = associatedKeyType; - } - undefinedProperties.set(name, result); + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); return result; } function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; - // Since get accessors already widen their return value there is no need to - // widen accessor based properties here. - members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop, context) : prop); + members.set(prop.escapedName, getWidenedProperty(prop, context)); } if (context) { - for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { - var name = _c[_b]; - if (!members.has(name)) { - members.set(name, getUndefinedProperty(name)); + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); } } } @@ -35267,16 +40311,16 @@ var ts; return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (type.flags & 50331648 /* RequiresWidening */) { - if (type.flags & 12288 /* Nullable */) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 24576 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -35301,8 +40345,8 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16777216 /* ContainsWideningType */) { - if (type.flags & 131072 /* Union */) { + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 262144 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -35327,7 +40371,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 16777216 /* ContainsWideningType */) { + if (t.flags & 134217728 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -35342,32 +40386,33 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 202 /* BinaryExpression */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 148 /* Parameter */: + case 149 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 180 /* BindingElement */: + case 184 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 176 /* MappedType */: + case 179 /* MappedType */: error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); return; default: @@ -35376,7 +40421,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 16777216 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -35384,24 +40429,22 @@ var ts; } } function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceHasRest = hasEffectiveRestParameter(source); + var targetHasRest = hasEffectiveRestParameter(target); + var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : + sourceHasRest ? targetCount : + targetHasRest ? sourceCount : + Math.min(sourceCount, targetCount); + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); @@ -35449,26 +40492,26 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 7897088 /* Instantiable */ || + return !!(type.flags & 15794176 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 393216 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 32 /* StringLiteral */)) { + if (!(t.flags & 64 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -35480,7 +40523,7 @@ var ts; } members.set(name, literalProp); }); - var indexInfo = type.flags & 2 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } /** @@ -35508,7 +40551,7 @@ var ts; // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - if (getTypeOfSymbol(prop).flags & 67108864 /* ContainsAnyFunctionType */) { + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } } @@ -35528,7 +40571,7 @@ var ts; return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { @@ -35540,6 +40583,16 @@ var ts; } return undefined; } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : @@ -35576,8 +40629,8 @@ var ts; } return; } - if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || - source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { + if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || + source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -35600,7 +40653,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -35615,7 +40668,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 1081344 /* TypeVariable */) { + if (target.flags & 2162688 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -35623,7 +40676,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 67108864 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); @@ -35643,7 +40696,7 @@ var ts; inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -35665,12 +40718,12 @@ var ts; } } } - else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { + else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -35679,17 +40732,17 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { + else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) { + else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 393216 /* UnionOrIntersection */) { + else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -35714,7 +40767,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 131072 /* Union */) { + else if (source.flags & 262144 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -35723,10 +40776,10 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { + if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { source = getApparentType(source); } - if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { + if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -35736,7 +40789,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 65536 /* Object */ && + var isNonConstructorObject = target.flags & 131072 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -35764,7 +40817,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 1081344 /* TypeVariable */) { + if (type.flags & 2162688 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -35783,7 +40836,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 524288 /* Index */) { + if (constraintType.flags & 1048576 /* Index */) { // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference @@ -35800,7 +40853,7 @@ var ts; } return; } - if (constraintType.flags & 32768 /* TypeParameter */) { + if (constraintType.flags & 65536 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. var savePriority = priority; @@ -35811,9 +40864,8 @@ var ts; return; } } - // 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 (!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) || !getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false)) { + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -35821,12 +40873,33 @@ var ts; } } function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + if (isTupleType(source) && isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + } + else { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } } } } @@ -35892,11 +40965,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 131072 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -35921,10 +40994,12 @@ var ts; // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. @@ -35939,17 +41014,14 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + if (inference.contraCandidates) { + // If we have contravariant inferences we find the best common subtype and treat + // that as a single covariant candidate. + inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + inference.contraCandidates = undefined; + } if (inference.candidates) { inferredType = getCovariantInference(inference, context, signature); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { - inferredType = getContravariantInference(inference); - } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getContravariantInference(inference); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -35975,13 +41047,12 @@ var ts; else { inferredType = getTypeFromInference(inference); } - inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); + inference.inferredType = inferredType = instantiatedConstraint; } } } @@ -36011,7 +41082,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 164 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 145 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -36027,13 +41098,13 @@ var ts; if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 183 /* PropertyAccessExpression */) { + if (node.kind === 187 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 180 /* BindingElement */) { + if (node.kind === 184 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 180 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -36041,12 +41112,13 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 178 /* ObjectBindingPattern */) { + var parent = element.parent; + if (parent.kind === 182 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: return ts.idText(name); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -36057,41 +41129,41 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { switch (source.kind) { case 71 /* Identifier */: return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 230 /* VariableDeclaration */ || target.kind === 180 /* BindingElement */) && + (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99 /* ThisKeyword */: return target.kind === 99 /* ThisKeyword */; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; - case 183 /* PropertyAccessExpression */: - return target.kind === 183 /* PropertyAccessExpression */ && + case 187 /* PropertyAccessExpression */: + return target.kind === 187 /* PropertyAccessExpression */ && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 180 /* BindingElement */: - if (target.kind !== 183 /* PropertyAccessExpression */) + case 184 /* BindingElement */: + if (target.kind !== 187 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 180 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 230 /* VariableDeclaration */) { + if (source.parent.parent.kind === 235 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; } function containsMatchingReference(source, target) { - while (source.kind === 183 /* PropertyAccessExpression */) { + while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -36104,7 +41176,7 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 183 /* PropertyAccessExpression */ && + return target.kind === 187 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -36112,18 +41184,18 @@ var ts; if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 183 /* PropertyAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 131072 /* Union */) { + if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -36156,7 +41228,7 @@ var ts; } } } - if (callExpression.expression.kind === 183 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -36170,7 +41242,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 131072 /* Union */)) { + if (!(source.flags & 262144 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -36186,11 +41258,11 @@ var ts; // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 16384 /* Never */) { + if (assignedType.flags & 32768 /* Never */) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 16384 /* Never */)) { + if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } } @@ -36213,53 +41285,53 @@ var ts; } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2 /* String */) { + if (flags & 4 /* String */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 32 /* StringLiteral */) { + if (flags & 64 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } - if (flags & (4 /* Number */ | 16 /* Enum */)) { + if (flags & (8 /* Number */ | 32 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & 64 /* NumberLiteral */) { + if (flags & 128 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; } - if (flags & 8 /* Boolean */) { + if (flags & 16 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 136 /* BooleanLike */) { + if (flags & 272 /* BooleanLike */) { return strictNullChecks ? type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 65536 /* Object */) { + if (flags & 131072 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { + if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 8192 /* Null */) { + if (flags & 16384 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 1536 /* ESSymbolLike */) { + if (flags & 3072 /* ESSymbolLike */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 134217728 /* NonPrimitive */) { + if (flags & 16777216 /* NonPrimitive */) { return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & 7897088 /* Instantiable */) { + if (flags & 15794176 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 393216 /* UnionOrIntersection */) { + if (flags & 786432 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 4194303 /* All */; @@ -36276,29 +41348,29 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || - unknownType; + errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + return isTupleLikeType(type) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || - unknownType; + errorType; } function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 181 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 268 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 198 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 220 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -36315,29 +41387,29 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return stringType; - case 220 /* ForOfStatement */: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 198 /* BinaryExpression */: + case 225 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 202 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return undefinedType; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } - return unknownType; + return errorType; } function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 178 /* ObjectBindingPattern */ ? + var type = pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -36355,35 +41427,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 219 /* ForInStatement */) { + if (node.parent.parent.kind === 224 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 220 /* ForOfStatement */) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + if (node.parent.parent.kind === 225 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } - return unknownType; + return errorType; } function getInitialType(node) { - return node.kind === 230 /* VariableDeclaration */ ? + return node.kind === 235 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */ ? + return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 230 /* VariableDeclaration */ && node.initializer && + return node.kind === 235 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 180 /* BindingElement */ && node.parent.kind === 198 /* BinaryExpression */ && + node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: return getReferenceCandidate(node.left); @@ -36395,43 +41467,36 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 189 /* ParenthesizedExpression */ || - parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 193 /* ParenthesizedExpression */ || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 264 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; + if (clause.kind === 269 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { - // If all case clauses specify expressions that have unit types, we return an array - // of those unit types. Otherwise we return an empty array. links.switchTypes = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - var type = getTypeOfSwitchClause(clause); - if (type === undefined) { - return links.switchTypes = ts.emptyArray; - } - links.switchTypes.push(type); + links.switchTypes.push(getTypeOfSwitchClause(clause)); } } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 131072 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 131072 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -36440,30 +41505,27 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 131072 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); } return f(type) ? type : neverType; } - // Apply a mapping function to a type and return the resulting type. If the source type - // is a union type, the mapping function is applied to each constituent type and a union - // of the resulting types is returned. function mapType(type, mapper, noReductions) { - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { return type; } - if (!(type.flags & 131072 /* Union */)) { + if (!(type.flags & 262144 /* Union */)) { return mapper(type); } var types = type.types; @@ -36493,11 +41555,11 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : - t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : t; }); } @@ -36532,9 +41594,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 16384 /* Never */ ? + return elementType.flags & 32768 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 131072 /* Union */ ? + createArrayType(elementType.flags & 262144 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -36552,7 +41614,7 @@ var ts; var hasEvolvingArrayType = false; for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { var t = types_14[_i]; - if (!(t.flags & 16384 /* Never */)) { + if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -36574,15 +41636,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 183 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 185 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 184 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 198 /* BinaryExpression */ && + parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -36597,7 +41659,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); } } return false; @@ -36613,9 +41675,9 @@ var ts; var key; var flowDepth = 0; if (flowAnalysisDisabled) { - return unknownType; + return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 142575359 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -36626,7 +41688,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 207 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 16384 /* Never */) { + if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { return declaredType; } return resultType; @@ -36636,7 +41698,7 @@ var ts; // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); - return unknownType; + return errorType; } flowDepth++; while (true) { @@ -36697,7 +41759,7 @@ var ts; else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 183 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && reference.kind !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -36735,7 +41797,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 131072 /* Union */) { + if (declaredType.flags & 262144 /* Union */) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -36753,7 +41815,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 185 /* CallExpression */ ? + var expr = node.kind === 189 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -36761,7 +41823,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 185 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -36769,7 +41831,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36783,7 +41845,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -36800,7 +41862,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 16384 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -36926,8 +41988,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 183 /* PropertyAccessExpression */ && - computedType.flags & 131072 /* Union */ && + return expr.kind === 187 /* PropertyAccessExpression */ && + computedType.flags & 262144 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -36960,7 +42022,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (131072 /* Union */ | 65536 /* Object */)) || (type.flags & 32768 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -36977,10 +42039,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 193 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 193 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -37020,24 +42082,24 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 12288 /* Nullable */) { + if (valueType.flags & 24576 /* Nullable */) { if (!strictNullChecks) { return type; } var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 95 /* NullKeyword */ ? + valueType.flags & 16384 /* Null */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 134283777 /* NotUnionOrUnit */) { + if (type.flags & 16909315 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 16384 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -37059,16 +42121,19 @@ var ts; if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 131072 /* Union */)) { + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + if (assumeTrue && !(type.flags & 262144 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = typeofTypesByName.get(literal.text); + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 7897088 /* Instantiable */) { + if (type.flags & 15794176 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -37090,13 +42155,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : + var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 16384 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -37150,9 +42215,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 16384 /* Never */)) { + if (!(assignableType.flags & 32768 /* Never */)) { return assignableType; } } @@ -37192,7 +42257,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 184 /* ElementAccessExpression */ || invokedExpression.kind === 183 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -37212,15 +42277,15 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -37256,9 +42321,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 238 /* ModuleBlock */ || - node.kind === 272 /* SourceFile */ || - node.kind === 151 /* PropertyDeclaration */; + node.kind === 243 /* ModuleBlock */ || + node.kind === 277 /* SourceFile */ || + node.kind === 152 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. @@ -37280,7 +42345,7 @@ var ts; if (node.kind === 71 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 148 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { symbol.isAssigned = true; } } @@ -37295,28 +42360,28 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 148 /* Parameter */ && + declaration.kind === 149 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 4096 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); + getFalsyFlags(declaredType) & 8192 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 183 /* PropertyAccessExpression */ || - parent.kind === 185 /* CallExpression */ && parent.expression === node || - parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 187 /* PropertyAccessExpression */ || + parent.kind === 189 /* CallExpression */ && parent.expression === node || + parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); + return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; @@ -37329,7 +42394,7 @@ var ts; function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { - return unknownType; + return errorType; } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -37340,7 +42405,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 191 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -37361,7 +42426,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 233 /* ClassDeclaration */ + if (declaration.kind === 238 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -37373,14 +42438,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 203 /* ClassExpression */) { + else if (declaration.kind === 207 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { + while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 151 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -37390,20 +42455,18 @@ var ts; } } } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; + return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; + return errorType; } } var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; @@ -37426,28 +42489,28 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 148 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 190 /* FunctionExpression */ || - flowContainer.kind === 191 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || + flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 250 /* ExportSpecifier */) || - node.parent.kind === 207 /* NonNullExpression */ || - declaration.kind === 230 /* VariableDeclaration */ && declaration.exclamationToken || - declaration.flags & 2097152 /* Ambient */; + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || + node.parent.kind === 211 /* NonNullExpression */ || + declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); @@ -37464,7 +42527,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -37477,7 +42540,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 267 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -37502,8 +42565,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 218 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 231 /* VariableDeclarationList */).parent === container && + if (container.kind === 223 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -37517,7 +42580,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 189 /* ParenthesizedExpression */) { + while (current.parent.kind === 193 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -37525,7 +42588,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 196 /* PrefixUnaryExpression */ || current.parent.kind === 197 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } @@ -37538,7 +42601,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 151 /* PropertyDeclaration */ || container.kind === 154 /* Constructor */) { + if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -37583,7 +42646,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -37606,38 +42669,38 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 154 /* Constructor */) { + if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 191 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 154 /* Constructor */: + case 155 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: 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 } break; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -37658,8 +42721,8 @@ var ts; // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 190 /* FunctionExpression */ && - container.parent.kind === 198 /* BinaryExpression */ && + if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') var className = container.parent // x.prototype.y = f @@ -37683,14 +42746,14 @@ var ts; } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { + if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 280 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -37698,17 +42761,21 @@ var ts; return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 148 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 185 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 191 /* ArrowFunction */) { + while (container && container.kind === 195 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -37721,22 +42788,22 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 146 /* ComputedPropertyName */; }); - if (current && current.kind === 146 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); + if (current && current.kind === 147 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 182 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } - return unknownType; + return errorType; } - if (!isCallExpression && container.kind === 154 /* Constructor */) { + if (!isCallExpression && container.kind === 155 /* 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.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -37802,7 +42869,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 === 153 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -37816,10 +42883,10 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 182 /* ObjectLiteralExpression */) { + if (container.parent.kind === 186 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; + return errorType; } else { // for object literal assume that type of 'super' is 'any' @@ -37828,19 +42895,19 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - return unknownType; + return errorType; } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - return unknownType; + return errorType; } - if (container.kind === 154 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; + return errorType; } return nodeCheckFlag === 512 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) @@ -37852,7 +42919,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 154 /* Constructor */; + return container.kind === 155 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -37860,21 +42927,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - 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 === 182 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 153 /* MethodDeclaration */ || - container.kind === 152 /* MethodSignature */ || - container.kind === 155 /* GetAccessor */ || - container.kind === 156 /* SetAccessor */; + return container.kind === 154 /* MethodDeclaration */ || + container.kind === 153 /* MethodSignature */ || + container.kind === 156 /* GetAccessor */ || + container.kind === 157 /* SetAccessor */; } else { - return container.kind === 153 /* MethodDeclaration */ || - container.kind === 152 /* MethodSignature */ || - container.kind === 155 /* GetAccessor */ || - container.kind === 156 /* SetAccessor */ || - container.kind === 151 /* PropertyDeclaration */ || - container.kind === 150 /* PropertySignature */ || - container.kind === 154 /* Constructor */; + return container.kind === 154 /* MethodDeclaration */ || + container.kind === 153 /* MethodSignature */ || + container.kind === 156 /* GetAccessor */ || + container.kind === 157 /* SetAccessor */ || + container.kind === 152 /* PropertyDeclaration */ || + container.kind === 151 /* PropertySignature */ || + container.kind === 155 /* Constructor */; } } } @@ -37882,10 +42949,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 153 /* MethodDeclaration */ || - func.kind === 155 /* GetAccessor */ || - func.kind === 156 /* SetAccessor */) && func.parent.kind === 182 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 190 /* FunctionExpression */ && func.parent.kind === 268 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 154 /* MethodDeclaration */ || + func.kind === 156 /* GetAccessor */ || + func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -37893,11 +42960,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 262144 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 191 /* ArrowFunction */) { + if (func.kind === 195 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -37924,7 +42991,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 268 /* PropertyAssignment */) { + if (literal.parent.kind !== 273 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -37938,9 +43005,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { var target = parent.left; - if (target.kind === 183 /* PropertyAccessExpression */ || target.kind === 184 /* ElementAccessExpression */) { + if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -37958,47 +43025,42 @@ var ts; // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameter = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. + indexOfParameter -= 1; + } + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + // If last parameter is contextually rest parameter get its type + if (funcHasRestParameter && indexOfParameter === len) { + return getRestTypeAtPosition(contextualSignature, indexOfParameter); } } - return undefined; } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. @@ -38015,7 +43077,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 148 /* Parameter */) { + if (declaration.kind === 149 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -38027,7 +43089,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 180 /* BindingElement */) { + if (parentDeclaration.kind !== 184 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -38083,7 +43145,7 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 154 /* Constructor */ || + if (functionDecl.kind === 155 /* Constructor */ || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -38098,7 +43160,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); + var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -38109,7 +43171,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 187 /* TaggedTemplateExpression */) { + if (template.parent.kind === 191 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -38125,8 +43187,8 @@ var ts; // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, /*cache*/ true) : type; + return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -38152,13 +43214,24 @@ var ts; case 6 /* Prototype */: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; + if (t.flags & 917504 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + } + return undefined; }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { @@ -38166,14 +43239,14 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 131072 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -38187,8 +43260,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_1 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); + var symbolName_3 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); if (propertyType) { return propertyType; } @@ -38241,12 +43314,31 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 187 /* PropertyAccessExpression */: + case 193 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 131072 /* Union */ && ts.isObjectLiteralExpression(node))) { + if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { return contextualType; } // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` @@ -38255,14 +43347,14 @@ var ts; var prop = _a[_i]; if (!prop.symbol) continue; - if (prop.kind !== 268 /* PropertyAssignment */) + if (prop.kind !== 273 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { if (match) { if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine @@ -38294,7 +43386,7 @@ var ts; * @returns the contextual type of an expression. */ function getContextualType(node) { - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -38303,59 +43395,59 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 184 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 191 /* ArrowFunction */: - case 223 /* ReturnStatement */: + case 195 /* ArrowFunction */: + case 228 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 181 /* ArrayLiteralExpression */: { + case 185 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 209 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 200 /* TemplateExpression */); + case 214 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 189 /* ParenthesizedExpression */: { + case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 260 /* JsxAttribute */: - case 262 /* JsxSpreadAttribute */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -38371,16 +43463,16 @@ var ts; } function getJsxSignaturesParameterTypes(valueType, isJs, context) { // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 2 /* String */) { + if (valueType.flags & 4 /* String */) { return anyType; } - else if (valueType.flags & 32 /* StringLiteral */) { + else if (valueType.flags & 64 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { @@ -38402,67 +43494,93 @@ var ts; ctor = false; if (signatures.length === 0) { // We found no signatures at all, which is an error - return unknownType; + return errorType; } } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } function getJsxPropsTypeFromCallSignature(sig, context) { - var propsType = getTypeOfFirstParameterOfSignature(sig); + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); - if (intrinsicAttribs !== unknownType) { + if (intrinsicAttribs !== errorType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { - if (isTypeAny(hostClassType)) { - return hostClassType; + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } } - var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return hostClassType; + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; } else { - var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); } - else if (isTypeAny(attributesType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) - : intrinsicClassAttribs, apparentAttributesType); - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } + return apparentAttributesType; } } - function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { - var hostClassType = getReturnTypeOfSignature(sig); - if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs, context); - } - return getJsxPropsTypeFromCallSignature(sig, context); - } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { @@ -38486,11 +43604,10 @@ var ts; if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { targetParameterCount--; } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 190 /* FunctionExpression */ || node.kind === 191 /* ArrowFunction */; + return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -38509,12 +43626,21 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } - if (!(type.flags & 131072 /* Union */)) { + if (!(type.flags & 262144 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; @@ -38553,18 +43679,19 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 180 /* BindingElement */ && !!node.initializer) || - (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 184 /* BindingElement */ && !!node.initializer) || + (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; - var hasSpreadElement = false; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); var contextualType = getApparentTypeOfContextualType(node); - for (var index = 0; index < elements.length; index++) { + for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 202 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -38589,13 +43716,17 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 202 /* SpreadElement */; + if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } } - if (!hasSpreadElement) { + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } @@ -38603,33 +43734,35 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 179 /* ArrayBindingPattern */ || pattern.kind === 181 /* ArrayLiteralExpression */)) { + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { elementTypes.push(contextualType.typeArguments[i]); } - else { - if (patternElement.kind !== 204 /* OmittedExpression */) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } - if (elementTypes.length) { - return createTupleType(elementTypes); - } + return createTupleType(elementTypes, minLength, hasRestElement); } } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, 2 /* Subtype */) : + getUnionType(elementTypes, unionReduction) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return isNumericComputedName(name); case 71 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -38643,7 +43776,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 isTypeAssignableToKind(checkComputedPropertyName(name), 84 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -38678,9 +43811,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 (links.resolvedType.flags & 12288 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */) && - !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { + if (links.resolvedType.flags & 24576 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -38706,79 +43839,53 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 8388608 /* FreshLiteral */; + var propagatedFlags = 33554432 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 178 /* ObjectBindingPattern */ || contextualType.pattern.kind === 182 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node); + (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - if (isInJSFile && node.properties.length === 0) { - // an empty JS object literal that nonetheless has members is a JS namespace - var symbol = getSymbolOfNode(node); - if (symbol.exports) { - propertiesTable = symbol.exports; - symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); - return createObjectLiteralType(); - } - } propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var literalName = void 0; - if (memberDecl.kind === 268 /* PropertyAssignment */ || - memberDecl.kind === 269 /* ShorthandPropertyAssignment */ || + var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 273 /* PropertyAssignment */ || + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var jsdocType = void 0; + var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); if (isInJSFile) { - jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); - } - var type = void 0; - if (memberDecl.kind === 268 /* PropertyAssignment */) { - if (memberDecl.name.kind === 146 /* ComputedPropertyName */) { - var t = checkComputedPropertyName(memberDecl.name); - if (t.flags & 224 /* Literal */) { - literalName = ts.escapeLeadingUnderscores("" + t.value); - } + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; } - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 153 /* MethodDeclaration */) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 269 /* ShorthandPropertyAssignment */); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - if (jsdocType) { - checkTypeAssignableTo(type, jsdocType, memberDecl); - type = jsdocType; } typeFlags |= type.flags; - var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); - var prop = hasLateBoundName - ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) - : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); - if (hasLateBoundName) { + var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { prop.nameType = nameType; } if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 268 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 269 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } - if (!literalName && ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } } else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the @@ -38800,7 +43907,7 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 270 /* SpreadAssignment */) { + else if (memberDecl.kind === 275 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -38815,7 +43922,7 @@ var ts; var type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; + return errorType; } spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); offset = i + 1; @@ -38827,15 +43934,20 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 155 /* GetAccessor */ || memberDecl.kind === 156 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (!literalName && hasNonBindableDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; + if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } } } else { @@ -38868,8 +43980,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 8388608 /* FreshLiteral */; - result.flags |= 33554432 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 117440512 /* PropagatingFlags */); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -38877,25 +43989,28 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 12288 /* Nullable */)) { - propagatedFlags |= (result.flags & 117440512 /* PropagatingFlags */); + if (!(result.flags & 24576 /* Nullable */)) { + propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 134217728 /* NonPrimitive */) || - getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 65536 /* Object */ && !isGenericMappedType(type) || - type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || + getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 131072 /* Object */ && !isGenericMappedType(type) || + type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } - function checkJsxSelfClosingElement(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxElement(node, checkMode) { + function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -38903,6 +44018,9 @@ var ts; else { checkExpression(node.closingElement.tagName); } + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { @@ -38925,16 +44043,7 @@ var ts; * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ function isJsxIntrinsicIdentifier(tagName) { - // TODO (yuisu): comment - switch (tagName.kind) { - case 183 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: - return false; - case 71 /* Identifier */: - return ts.isIntrinsicJsxName(tagName.escapedText); - default: - ts.Debug.fail(); - } + return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -38977,7 +44086,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 262 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); @@ -39000,7 +44109,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 253 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -39024,7 +44133,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -39032,7 +44144,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* ContainsObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -39066,7 +44178,7 @@ var ts; var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); - return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic @@ -39078,7 +44190,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { // Property case if (!ts.isIdentifier(node.tagName)) return ts.Debug.fail(); @@ -39106,55 +44218,80 @@ var ts; } return links.resolvedSymbol; } - /** - * Given a JSX element that is a class element, finds the Element Instance Type. If the - * element is not a class element, or the class element type cannot be determined, returns 'undefined'. - * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). - */ - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - // Instantiate in context of source type + function instantiateJsxSignatures(node, signatures) { var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); + } + // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } + return instantiatedSignatures; + } + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); } function getJsxNamespaceAt(location) { - var namespaceName = getJsxNamespace(location); - var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); - if (resolvedNamespace) { - var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); - if (candidate) { - return candidate; + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } } } // JSX global fallback - return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -39187,6 +44324,10 @@ var ts; } return undefined; } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), @@ -39202,7 +44343,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 262144 /* Intersection */) { + if (propsType.flags & 524288 /* Intersection */) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -39223,7 +44364,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { @@ -39236,7 +44377,7 @@ var ts; if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== unknownType) { + if (intrinsicAttributes !== errorType) { paramType = intersectTypes(intrinsicAttributes, paramType); } return paramType; @@ -39257,7 +44398,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); @@ -39270,6 +44411,7 @@ var ts; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); + // TODO: GH#18217: callReturnType should always be defined... var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { @@ -39278,7 +44420,7 @@ var ts; var attribute = _b[_a]; if (ts.isJsxAttribute(attribute) && isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { + !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 shouldBeCandidate = false; break; } @@ -39295,7 +44437,7 @@ var ts; } // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== unknownType) { + if (intrinsicAttributes !== errorType) { result = intersectTypes(intrinsicAttributes, result); } return result; @@ -39303,6 +44445,37 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(elementType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + // Instantiate in context of source type + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } /** * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. * For instance: @@ -39322,23 +44495,27 @@ var ts; * emptyObjectType if there is no "prop" in the element instance type */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 131072 /* Union */) { + if (elementType.flags & 262144 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2 /* Subtype */); } + // Shortcircuit any + if (isTypeAny(elementType)) { + return elementType; + } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (elementType.flags & 2 /* String */) { + else if (elementType.flags & 4 /* String */) { return anyType; } - else if (elementType.flags & 32 /* StringLiteral */) { + else if (elementType.flags & 64 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { @@ -39354,7 +44531,11 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); + if (!ts.length(instantiatedSignatures)) { + return errorType; + } + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -39367,7 +44548,8 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); + var isJs = ts.isInJavaScriptFile(openingLikeElement); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -39386,7 +44568,7 @@ var ts; return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; } else { - return links.resolvedJsxElementAttributesType = unknownType; + return links.resolvedJsxElementAttributesType = errorType; } } return links.resolvedJsxElementAttributesType; @@ -39440,7 +44622,7 @@ var ts; } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); - if (type === unknownType) + if (type === errorType) return undefined; return type; } @@ -39513,7 +44695,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 65536 /* Object */) { + if (targetType.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -39523,7 +44705,7 @@ var ts; return true; } } - else if (targetType.flags & 393216 /* UnionOrIntersection */) { + else if (targetType.flags & 786432 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -39531,6 +44713,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -39552,33 +44738,29 @@ var ts; // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. - // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); - } - else { - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } + var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; } } } + else if (!isSourceAttributeTypeAssignableToTarget) { + checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); + } } function checkJsxExpression(node, checkMode) { if (node.expression) { @@ -39589,19 +44771,30 @@ var ts; return type; } else { - return unknownType; + return errorType; } } // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 151 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + } } /** * Check whether the requested property access is valid. @@ -39613,9 +44806,11 @@ var ts; */ function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 183 /* PropertyAccessExpression */ || node.kind === 230 /* VariableDeclaration */ ? + var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? node.name : - node.right; + node.kind === 181 /* ImportType */ ? + node : + node.right; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -39648,7 +44843,7 @@ var ts; if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } } @@ -39679,16 +44874,23 @@ var ts; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 32768 /* TypeParameter */) { + if (type.flags & 65536 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); @@ -39696,24 +44898,32 @@ var ts; } return true; } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } function symbolHasNonMethodDeclaration(symbol) { return forEachProperty(symbol, function (prop) { var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 153 /* MethodDeclaration */ && propKind !== 152 /* MethodSignature */; + return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; if (kind) { - error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; + return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; } return type; } @@ -39743,9 +44953,9 @@ var ts; var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 32768 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } - return unknownType; + return errorType; } if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); @@ -39760,7 +44970,7 @@ var ts; if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); - return unknownType; + return errorType; } } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); @@ -39768,9 +44978,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 183 /* PropertyAccessExpression */ || + if (node.kind !== 187 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 131072 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -39782,14 +44992,14 @@ var ts; var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 154 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { - error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; } @@ -39800,24 +45010,29 @@ var ts; if (!valueDeclaration) { return; } + var diagnosticMessage; + var declarationName = ts.idText(right); if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 233 /* ClassDeclaration */ && - node.parent.kind !== 161 /* TypeReference */ && - !(valueDeclaration.flags & 2097152 /* Ambient */) && + else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && + node.parent.kind !== 162 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return true; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -39835,11 +45050,11 @@ var ts; } var classType = getTypeOfSymbol(prop.parent); while (true) { - classType = getSuperClass(classType); + classType = classType.symbol && getSuperClass(classType); if (!classType) { return false; } - var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + var superProperty = getPropertyOfType(classType, prop.escapedName); if (superProperty && superProperty.valueDeclaration) { return true; } @@ -39850,12 +45065,12 @@ var ts; if (x.length === 0) { return undefined; } - ts.Debug.assert(x.length === 1); - return x[0]; + return getIntersectionType(x); } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 131072 /* Union */ && !(containingType.flags & 16382 /* Primitive */)) { + var relatedInfo; + if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -39864,20 +45079,35 @@ var ts; } } } - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); } - function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -39887,10 +45117,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -39909,86 +45146,14 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestionForName(name, symbols, meaning) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); - var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. - var bestCandidate; - var justCheckExactMatches = false; - var nameLowerCase = name.toLowerCase(); - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var candidate = symbols_3[_i]; + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { - continue; - } - var candidateNameLowerCase = candidateName.toLowerCase(); - if (candidateNameLowerCase === nameLowerCase) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3) { - // Don't bother, user would have noticed a 2-character name having an extra character - continue; - } - // Only care about a result better than the best so far. - var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); - if (distance === undefined) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else { - ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined - bestDistance = distance; - bestCandidate = candidate; - } + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; } - return bestCandidate; - } - function levenshteinWithMax(s1, s2, max) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - /** Represents any value > max. We don't care about the particular value. */ - var big = max + 1; - for (var i = 0; i <= s2.length; i++) { - previous[i] = i; - } - for (var i = 1; i <= s1.length; i++) { - var c1 = s1.charCodeAt(i - 1); - var minJ = i > max ? i - max : 1; - var maxJ = s2.length > max + i ? max + i : s2.length; - current[0] = i; - /** Smallest value of the matrix in the ith column. */ - var colMin = i; - for (var j = 1; j < minJ; j++) { - current[j] = big; - } - for (var j = minJ; j <= maxJ; j++) { - var dist = c1 === s2.charCodeAt(j - 1) - ? previous[j - 1] - : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); - current[j] = dist; - colMin = Math.min(colMin, dist); - } - for (var j = maxJ + 1; j <= s2.length; j++) { - current[j] = big; - } - if (colMin > max) { - // Give up -- everything in this column is > max and it can't get better in future columns. - return undefined; - } - var temp = previous; - previous = current; - current = temp; - } - var res = previous[s2.length]; - return res > max ? undefined : res; } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -40004,15 +45169,21 @@ var ts; (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 183 /* PropertyAccessExpression */ ? node.expression : node.left; - return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + switch (node.kind) { + case 187 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + case 146 /* QualifiedName */: + return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + case 181 /* ImportType */: + return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { - var propType = getTypeOfFuncClassEnumModule(method); + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { @@ -40029,20 +45200,20 @@ var ts; return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } function isValidPropertyAccessWithType(node, left, propertyName, type) { - if (type === unknownType || isTypeAny(type)) { + if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 231 /* VariableDeclarationList */) { + if (initializer.kind === 236 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -40071,7 +45242,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 219 /* ForInStatement */ && + if (node.kind === 224 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -40089,7 +45260,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 186 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -40099,20 +45270,20 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } - return unknownType; + return errorType; } var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { + if (objectType === errorType || objectType === silentNeverType) { return objectType; } if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; + return errorType; } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { + if (expressionType === errorType) { // There is already an error, so no need to report one. return false; } @@ -40120,7 +45291,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 1536 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -40156,10 +45327,10 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 149 /* Decorator */) { + else if (node.kind !== 150 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -40192,7 +45363,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -40222,35 +45393,29 @@ var ts; result.splice(spliceIndex, 0, signature); } } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + } function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 202 /* SpreadElement */) { - return i; - } - } - return -1; + return ts.findIndex(args, isSpreadArgument); } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = undefined; - if (node.template.kind === 200 /* TemplateExpression */) { + if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -40262,47 +45427,43 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 149 /* Decorator */) { - typeArguments = undefined; + else if (node.kind === 150 /* Decorator */) { argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 186 /* NewExpression */); - return signature.minArgumentCount === 0; + ts.Debug.assert(node.kind === 190 /* NewExpression */); + return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + var hasEnoughArguments = argCount >= getMinArgumentCount(signature); + return callIsIncomplete || hasEnoughArguments; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || + return !typeArguments || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || - signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; - } - // Too many arguments implies incorrect arity. - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -40314,9 +45475,10 @@ var ts; // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + inferTypes(context.inferences, source, target); }); if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); @@ -40350,7 +45512,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 149 /* Decorator */) { + if (node.kind !== 150 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -40366,7 +45528,7 @@ var ts; // Above, the type of the 'value' parameter is inferred to be 'A'. var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. @@ -40381,11 +45543,13 @@ var ts; } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - var argCount = getEffectiveArgumentCount(node, args, signature); + var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 204 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type @@ -40399,6 +45563,10 @@ var ts; inferTypes(context.inferences, argType, paramType); } } + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); + } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) @@ -40416,6 +45584,35 @@ var ts; } return getInferredTypes(context); } + function getSpreadArgumentType(node, args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = getEffectiveArgument(node, args, argCount - 1); + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 213 /* SyntheticExpression */ ? + createArrayType(arg.type) : + checkExpressionWithContextualType(arg.expression, restType, context); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = getEffectiveArgumentType(node, i); + if (!argType) { + argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; @@ -40426,7 +45623,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -40475,7 +45672,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 186 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -40483,30 +45680,38 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; var argCount = getEffectiveArgumentCount(node, args, signature); + var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; + var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 204 /* OmittedExpression */) { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { + var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); + return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); + } + else { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } } } } @@ -40516,12 +45721,9 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 185 /* CallExpression */) { - var callee = node.expression; - if (callee.kind === 183 /* PropertyAccessExpression */) { - return callee.expression; - } - else if (callee.kind === 184 /* ElementAccessExpression */) { + if (node.kind === 189 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { return callee.expression; } } @@ -40536,17 +45738,17 @@ var ts; * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; - if (template.kind === 200 /* TemplateExpression */) { + var args_4 = [undefined]; // TODO: GH#18217 + if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 149 /* Decorator */) { + else if (node.kind === 150 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -40556,7 +45758,28 @@ var ts; return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } else { - return node.arguments || ts.emptyArray; + var args = node.arguments || ts.emptyArray; + var length_4 = args.length; + if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length_4 - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { + var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); + arg.parent = spreadArgument_1; + arg.type = t; + arg.isSpread = i === restIndex_2; + return arg; + }); + return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); + } + } + return args; } } /** @@ -40573,19 +45796,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -40595,10 +45818,12 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 148 /* Parameter */: + case 149 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; + default: + return ts.Debug.fail(); } } else { @@ -40619,25 +45844,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -40645,7 +45870,7 @@ var ts; return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective type for the second argument to a decorator. @@ -40664,37 +45889,38 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { node = node.parent; - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } // For a non-constructor parameter decorator, the `propertyKey` will be either // a string or a symbol, based on the name of the parameter's containing method. } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralType(element.name.text); - case 146 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { return nameType; } else { @@ -40702,11 +45928,11 @@ var ts; } default: ts.Debug.fail("Unsupported property name."); - return unknownType; + return errorType; } } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective argument type for the third argument to a decorator. @@ -40718,28 +45944,28 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 151 /* PropertyDeclaration */) { + if (node.kind === 152 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective argument type for the provided argument to a decorator. @@ -40755,7 +45981,7 @@ var ts; return getEffectiveDecoratorThirdArgumentType(node.parent); } ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; + return errorType; } /** * Gets the effective argument type for an argument in a call expression. @@ -40764,10 +45990,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -40779,8 +46005,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 149 /* Decorator */ || - (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */)) { + if (node.kind === 150 /* Decorator */ || + (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -40789,11 +46015,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -40801,15 +46027,62 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 187 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 149 /* Decorator */; + var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -40873,11 +46146,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 185 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -40913,81 +46187,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; - min = Math.min(min, sig.minArgumentCount); - max = Math.max(max, sig.parameters.length); - } - var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min : - min < max ? min + "-" + max : - min; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -40998,7 +46221,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -41024,6 +46247,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -41045,16 +46274,98 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_8 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_8(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(function (n) { return getTypeOfNode(n) || anyType; }); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; for (var i = 0; i < candidates.length; i++) { var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { return i; } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; + if (paramCount > maxParams) { + maxParams = paramCount; maxParamsIndex = i; } } @@ -41063,10 +46374,14 @@ var ts; function resolveCallExpression(node, candidatesOutArray) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { + if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + return anySignature; + } + if (superType !== errorType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); return resolveCall(node, baseConstructors, candidatesOutArray); @@ -41079,7 +46394,7 @@ var ts; return silentNeverSignature; } var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { + if (apparentType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41095,7 +46410,7 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. - if (funcType !== unknownType && node.typeArguments) { + if (funcType !== errorType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); @@ -41121,8 +46436,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 /* Union */ | 16384 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -41141,7 +46456,7 @@ var ts; // signatures for overload resolution. The result type of the function call becomes // the result type of the operation. expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { + if (expressionType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41192,6 +46507,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -41207,16 +46554,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -41230,12 +46571,11 @@ var ts; return true; } function invocationError(node, apparentType, kind) { - error(node, kind === 0 /* Call */ + invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); - invocationErrorRecovery(apparentType, kind); + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); } - function invocationErrorRecovery(apparentType, kind) { + function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { return; } @@ -41246,13 +46586,13 @@ var ts; var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); if (!sigs || !sigs.length) return; - error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { + if (apparentType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41272,17 +46612,19 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 148 /* Parameter */: + case 149 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } /** @@ -41291,7 +46633,7 @@ var ts; function resolveDecorator(node, candidatesOutArray) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { + if (apparentType === errorType) { return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); @@ -41306,11 +46648,11 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - invocationErrorRecovery(apparentType, 0 /* Call */); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -41338,29 +46680,7 @@ var ts; * the function will fill it up with appropriate candidate signatures */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 131072 /* Union */) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -41369,20 +46689,31 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 149 /* Decorator */: + case 150 /* Decorator */: return resolveDecorator(node, candidatesOutArray); - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -41422,15 +46753,11 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } function getJavaScriptClassType(symbol) { - var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); - if (initializer) { - symbol = getSymbolOfNode(initializer); - } var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); @@ -41447,7 +46774,8 @@ var ts; function getAssignedClassType(symbol) { var decl = symbol.valueDeclaration; var assignmentSymbol = decl && decl.parent && - (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); if (assignmentSymbol) { var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); @@ -41461,15 +46789,13 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 183 /* PropertyAccessExpression */) { + while (parent && parent.kind === 187 /* PropertyAccessExpression */) { parent = parent.parent; } - return parent && ts.isBinaryExpression(parent) && - ts.isPropertyAccessExpression(parent.left) && - parent.left.name.escapedText === "prototype" && - parent.operatorToken.kind === 58 /* EqualsToken */ && - ts.isObjectLiteralExpression(parent.right) && - parent.right; + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); @@ -41495,12 +46821,12 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 186 /* NewExpression */) { + if (node.kind === 190 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 154 /* Constructor */ && - declaration.kind !== 158 /* ConstructSignature */ && - declaration.kind !== 163 /* ConstructorType */ && + declaration.kind !== 155 /* Constructor */ && + declaration.kind !== 159 /* ConstructSignature */ && + declaration.kind !== 164 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations @@ -41513,7 +46839,7 @@ var ts; } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { - return type; + return signature.target ? instantiateType(type, signature.mapper) : type; } if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); @@ -41528,10 +46854,20 @@ var ts; var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 1536 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - return returnType; + var jsAssignmentType; + if (ts.isInJavaScriptFile(node)) { + var decl = ts.getDeclarationOfJSInitializer(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; } function isSymbolOrSymbolForCall(node) { if (!ts.isCallExpression(node)) @@ -41559,11 +46895,11 @@ var ts; } var specifier = node.arguments[0]; var specifierType = checkExpressionCached(specifier); - // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 4096 /* Undefined */ || specifierType.flags & 8192 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -41577,7 +46913,7 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { - if (allowSyntheticDefaultImports && type && type !== unknownType) { + if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { var file = ts.find(originalSymbol.declarations, ts.isSourceFile); @@ -41601,34 +46937,34 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { return false; } // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (!resolvedRequire) { - // project does not contain symbol named 'require' - assume commonjs require + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { return true; } - // project includes symbol named 'require' - make sure that it it ambient and local non-alias + // project includes symbol named 'require' - make sure that it is ambient and local non-alias if (resolvedRequire.flags & 2097152 /* Alias */) { return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 232 /* FunctionDeclaration */ + ? 237 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 230 /* VariableDeclaration */ + ? 235 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); // function/variable declaration should be ambient - return !!decl && !!(decl.flags & 2097152 /* Ambient */); + return !!decl && !!(decl.flags & 4194304 /* Ambient */); } return false; } function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); } @@ -41641,7 +46977,7 @@ var ts; var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); checkSourceElement(type); var targetType = getTypeFromTypeNode(type); - if (produceDiagnostics && targetType !== unknownType) { + if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); @@ -41654,12 +46990,21 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); + if (node.keywordToken === 94 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 91 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); if (!container) { error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; + return errorType; } - else if (container.kind === 154 /* Constructor */) { + else if (container.kind === 155 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -41668,6 +47013,15 @@ var ts; return getTypeOfSymbol(symbol); } } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } function getTypeOfParameter(symbol) { var type = getTypeOfSymbol(symbol); if (strictNullChecks) { @@ -41678,13 +47032,116 @@ var ts; } return type; } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + var tupleRestType = getRestTypeOfTupleType(restType); + if (tupleRestType) { + return tupleRestType; + } + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var hasRest = hasEffectiveRestParameter(source); + if (hasRest && pos === paramCount - 1) { + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; + } + } + var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, hasRest, names); + } + function getTypeOfRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + return getRestTypeOfTupleType(restType); + } + return restType; + } + return undefined; + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function getGenericRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (restType.flags & 15794176 /* Instantiable */) { + return restType; + } + } + return undefined; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; } function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); @@ -41717,11 +47174,11 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + if (signature.hasRestParameter) { // parameter might be a transient symbol generated by use of `arguments` in the function body. - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getRestTypeAtPosition(context, len); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -41771,7 +47228,7 @@ var ts; error(func, ts.isImportCall(func) ? ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; + return errorType; } else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { error(func, ts.isImportCall(func) ? @@ -41782,11 +47239,11 @@ var ts; } function getReturnTypeFromBody(func, checkMode) { if (!func.body) { - return unknownType; + return errorType; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 211 /* Block */) { + if (func.body.kind !== 216 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -41875,7 +47332,7 @@ var ts; } function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { var errorNode = node.expression || node; - var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; // A `yield*` expression effectively yields everything that its operand yields var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken @@ -41891,7 +47348,7 @@ var ts; return false; } var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { return false; } return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); @@ -41900,12 +47357,12 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 225 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; } - /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -41922,7 +47379,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -41934,18 +47391,20 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } function mayReturnNever(func) { switch (func.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; - case 153 /* MethodDeclaration */: - return func.parent.kind === 182 /* ObjectLiteralExpression */; + case 154 /* MethodDeclaration */: + return func.parent.kind === 186 /* ObjectLiteralExpression */; default: return false; } @@ -41964,16 +47423,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 2048 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 152 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 211 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 16384 /* Never */) { + if (returnType && returnType.flags & 32768 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -42002,19 +47461,21 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(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 === 190 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } // Check if function expression is contextually typed and assign parameter types if so. if (!(links.flags & 1024 /* ContextChecked */)) { var contextualSignature = getContextualSignature(node); @@ -42045,27 +47506,26 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 153 /* MethodDeclaration */) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } return type; } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); + function getReturnOrPromisedType(node, functionFlags) { var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && + return returnTypeNode && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + checkAsyncFunctionReturnType(node, returnTypeNode) : // Async function + getTypeFromTypeNode(returnTypeNode)) || // AsyncGenerator function, Generator function, or normal function + getReturnTypeOfTypeTag(node); // type from JSDoc @type tag + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -42073,7 +47533,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 211 /* Block */) { + if (node.body.kind === 216 /* Block */) { checkSourceElement(node.body); } else { @@ -42086,18 +47546,17 @@ var ts; if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); } else { // Normal function - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); } } } - registerForUnusedIdentifiersCheck(node); } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 84 /* NumberLike */)) { + if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -42120,11 +47579,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 183 /* PropertyAccessExpression */ || expr.kind === 184 /* ElementAccessExpression */) && + (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && expr.expression.kind === 99 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 154 /* Constructor */)) { + if (!(func && func.kind === 155 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -42137,13 +47596,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 183 /* PropertyAccessExpression */ || expr.kind === 184 /* ElementAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 244 /* NamespaceImport */; + return !!declaration && declaration.kind === 249 /* NamespaceImport */; } } } @@ -42152,7 +47611,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { + if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -42161,7 +47620,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 183 /* PropertyAccessExpression */ && expr.kind !== 184 /* ElementAccessExpression */) { + if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -42211,7 +47670,7 @@ var ts; case 38 /* MinusToken */: case 52 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 1536 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -42229,7 +47688,7 @@ var ts; } return numberType; } - return unknownType; + return errorType; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); @@ -42246,13 +47705,13 @@ var ts; // Return true if type might be of the given kind. A union or intersection type might be of a given // kind if at least one constituent type is of the given kind. function maybeTypeOfKind(type, kind) { - if (type.flags & kind || kind & 536870912 /* GenericMappedType */ && isGenericMappedType(type)) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 393216 /* UnionOrIntersection */) { + if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -42264,26 +47723,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { return false; } - return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 524322 /* StringLike */ && isTypeAssignableTo(source, stringType)) || - (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 131072 /* Union */ ? + return source.flags & 262144 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -42298,7 +47757,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 16382 /* Primitive */)) { + allTypesAssignableToKind(leftType, 32764 /* 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 @@ -42317,10 +47776,10 @@ 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) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { 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; @@ -42338,9 +47797,9 @@ var ts; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 268 /* PropertyAssignment */ || property.kind === 269 /* ShorthandPropertyAssignment */) { + if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -42353,7 +47812,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 269 /* ShorthandPropertyAssignment */) { + if (property.kind === 274 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -42365,7 +47824,7 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 270 /* SpreadAssignment */) { + else if (property.kind === 275 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -42376,6 +47835,7 @@ var ts; } } var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); return checkDestructuringAssignment(property.expression, type); } else { @@ -42383,14 +47843,14 @@ var ts; } } function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - var elements = node.elements; + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; for (var i = 0; i < elements.length; i++) { checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); } @@ -42399,27 +47859,23 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 204 /* OmittedExpression */) { - if (element.kind !== 202 /* SpreadElement */) { + if (element.kind !== 208 /* OmittedExpression */) { + if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; + var type = isTypeAny(sourceType) ? sourceType : + isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); } } else { @@ -42428,11 +47884,15 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 198 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = isTupleType(sourceType) ? + getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -42441,13 +47901,13 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 269 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -42457,25 +47917,25 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 198 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 182 /* ObjectLiteralExpression */) { + if (target.kind === 186 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 181 /* ArrayLiteralExpression */) { + if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 270 /* SpreadAssignment */ ? + var error = target.parent.kind === 275 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); } return sourceType; } @@ -42493,35 +47953,35 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 12 /* RegularExpressionLiteral */: - case 187 /* TaggedTemplateExpression */: - case 200 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 140 /* UndefinedKeyword */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: - case 191 /* ArrowFunction */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 193 /* TypeOfExpression */: - case 207 /* NonNullExpression */: - case 254 /* JsxSelfClosingElement */: - case 253 /* JsxElement */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 197 /* TypeOfExpression */: + case 211 /* NonNullExpression */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: return true; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -42533,15 +47993,15 @@ var ts; } return false; // Some forms listed here for clarity - case 194 /* VoidExpression */: // Explicit opt-out - case 188 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 206 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 198 /* VoidExpression */: // Explicit opt-out + case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { @@ -42551,7 +48011,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 182 /* ObjectLiteralExpression */ || left.kind === 181 /* ArrayLiteralExpression */)) { + if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -42587,8 +48047,8 @@ var ts; var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && + if ((leftType.flags & 272 /* BooleanLike */) && + (rightType.flags & 272 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -42606,24 +48066,24 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 524322 /* StringLike */) && !isTypeAssignableToKind(rightType, 524322 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 84 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 84 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* 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 (isTypeAssignableToKind(leftType, 524322 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 524322 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* 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; + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; } // Symbols are not allowed at all in arithmetic expressions if (resultType && !checkForDisallowedESSymbolOperand(operator)) { @@ -42676,21 +48136,47 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; + checkSpecialAssignment(special, right); + if (isJSSpecialPropertyAssignment(special)) { + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } case 26 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); + } + function checkSpecialAssignment(special, right) { + if (special === 2 /* ModuleExports */) { + var rightType_1 = checkExpression(right, checkMode); + for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } } function isEvalNode(node) { return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 1536 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -42720,15 +48206,48 @@ var ts; // VarExpr = ValueExpr // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) - // and the type of the non - compound operation to be assignable to the type of VarExpr. - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported - checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); } } } + function isJSSpecialPropertyAssignment(special) { + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedJavascriptInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; } } function isYieldExpressionInClass(node) { @@ -42757,7 +48276,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. return anyType; @@ -42776,14 +48297,14 @@ var ts; } } var isAsync = (functionFlags & 2 /* Async */) !== 0; - var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. var returnType = ts.getEffectiveReturnTypeNode(func); if (returnType) { var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; - checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; @@ -42801,12 +48322,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + } }); return stringType; } function getContextNode(node) { - if (node.kind === 261 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -42842,38 +48365,52 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 188 /* TypeAssertionExpression */ || node.kind === 206 /* AsExpression */; + return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var initializer = ts.isInJavaScriptFile(declaration) && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJavaScriptFile(declaration)) { + if (widened.flags & 24576 /* Nullable */) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 /* UnionOrIntersection */) { + if (contextualType.flags & 786432 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 7372800 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); + return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || + contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || + contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || + contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); } return false; } @@ -42889,7 +48426,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -42900,7 +48437,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -42930,7 +48467,7 @@ var ts; function getTypeOfExpression(node, cache) { // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -42956,6 +48493,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -42965,7 +48505,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode) { var type; - if (node.kind === 145 /* QualifiedName */) { + if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -42977,10 +48517,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 184 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 145 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 164 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -43014,77 +48554,79 @@ var ts; return trueType; case 86 /* FalseKeyword */: return falseType; - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 186 /* NewExpression */: + case 190 /* NewExpression */: return checkCallExpression(node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return checkClassExpression(node); - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return checkAssertion(node); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return checkNonNullAssertion(node); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return checkMetaProperty(node); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return checkDeleteExpression(node); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return checkVoidExpression(node); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return checkAwaitExpression(node); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 204 /* OmittedExpression */: + case 208 /* OmittedExpression */: return undefinedWideningType; - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return checkYieldExpression(node); - case 263 /* JsxExpression */: + case 213 /* SyntheticExpression */: + return node.type; + case 268 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return checkJsxElement(node, checkMode); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return checkJsxFragment(node, checkMode); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 255 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } - return unknownType; + return errorType; } // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node) { @@ -43110,6 +48652,9 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } + function isRestParameterType(type) { + return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); + } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -43119,7 +48664,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 154 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -43130,13 +48675,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 154 /* Constructor */ || func.kind === 158 /* ConstructSignature */ || func.kind === 163 /* ConstructorType */) { + if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -43196,13 +48741,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 191 /* ArrowFunction */: - case 157 /* CallSignature */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 162 /* FunctionType */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 195 /* ArrowFunction */: + case 158 /* CallSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 163 /* FunctionType */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -43220,7 +48765,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 179 /* ArrayBindingPattern */ || name.kind === 178 /* ObjectBindingPattern */) { + else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -43229,13 +48774,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 159 /* IndexSignature */) { + if (node.kind === 160 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ || - node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ || - node.kind === 158 /* ConstructSignature */) { + else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || + node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || + node.kind === 159 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -43265,10 +48810,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 157 /* CallSignature */: + case 158 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -43295,11 +48840,11 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); + if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); } } } @@ -43315,7 +48860,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 154 /* Constructor */) { + if (member.kind === 155 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -43326,20 +48871,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { - case 155 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + case 156 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); break; - case 156 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + case 157 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); break; - case 151 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + case 152 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); break; - case 153 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); + case 154 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); break; } } @@ -43401,15 +48947,16 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 150 /* PropertySignature */) { + if (member.kind === 151 /* PropertySignature */) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - memberName = member.name.text; + memberName = name.text; break; case 71 /* Identifier */: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -43425,7 +48972,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 234 /* InterfaceDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -43480,7 +49027,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.hasModifier(node, 128 /* Abstract */) && node.kind === 153 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -43491,7 +49038,6 @@ var ts; if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); // Only type check the symbol once @@ -43506,7 +49052,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 151 /* PropertyDeclaration */ && + return n.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -43514,7 +49060,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -43536,7 +49082,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -43561,8 +49107,8 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 155 /* GetAccessor */) { - if (!(node.flags & 2097152 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (node.kind === 156 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } @@ -43571,13 +49117,13 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 155 /* GetAccessor */ ? 156 /* SetAccessor */ : 155 /* GetAccessor */; + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -43595,12 +49141,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 155 /* GetAccessor */) { + if (node.kind === 156 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); } function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { var firstType = getAnnotatedType(first); @@ -43633,7 +49178,7 @@ var ts; } function getTypeParametersForTypeReference(node) { var type = getTypeFromTypeReference(node); - if (type !== unknownType) { + if (type !== errorType) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || @@ -43644,11 +49189,11 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 161 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); - if (type !== unknownType) { + if (type !== errorType) { if (node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved ts.forEach(node.typeArguments, checkSourceElement); @@ -43659,7 +49204,7 @@ var ts; } } } - if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -43668,7 +49213,7 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -43688,25 +49233,42 @@ var ts; checkSourceElement(node.elementType); } function checkTupleType(node) { - // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 170 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 169 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } } + checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 1048576 /* IndexedAccess */)) { + if (!(type.flags & 2097152 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 184 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -43714,7 +49276,7 @@ var ts; } // 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 */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -43733,7 +49295,7 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -43743,23 +49305,27 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 170 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 2097152 /* Ambient */); + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 234 /* InterfaceDeclaration */ && - n.parent.kind !== 233 /* ClassDeclaration */ && - n.parent.kind !== 203 /* ClassExpression */ && - n.flags & 2097152 /* Ambient */) { - if (!(flags & 2 /* Ambient */)) { + if (n.parent.kind !== 239 /* InterfaceDeclaration */ && + n.parent.kind !== 238 /* ClassDeclaration */ && + n.parent.kind !== 207 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; } @@ -43848,7 +49414,7 @@ var ts; if (node.name && subsequentName && (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 === 153 /* MethodDeclaration */ || node.kind === 152 /* MethodSignature */) && + var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -43886,8 +49452,8 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = node.flags & 2097152 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 234 /* InterfaceDeclaration */ || node.parent.kind === 165 /* TypeLiteral */ || inAmbientContext; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -43898,7 +49464,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 232 /* FunctionDeclaration */ || node.kind === 153 /* MethodDeclaration */ || node.kind === 152 /* MethodSignature */ || node.kind === 154 /* Constructor */) { + if (node.kind === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -44024,37 +49590,46 @@ var ts; DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; })(DeclarationSpaces || (DeclarationSpaces = {})); - function getDeclarationSpaces(d) { + function getDeclarationSpaces(decl) { + var d = decl; switch (d.kind) { - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - // A jsdoc typedef is, by definition, a type alias - case 291 /* JSDocTypedefTag */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 272 /* SourceFile */: + case 277 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 252 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 243 /* ImportClause */: - var result_2 = 0 /* None */; + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 232 /* FunctionDeclaration */: - case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 237 /* FunctionDeclaration */: + case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -44087,7 +49662,7 @@ var ts; if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -44119,7 +49694,7 @@ var ts; * The runtime behavior of the `await` keyword. */ function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; } function getAwaitedType(type, errorNode, diagnosticMessage) { var typeAsAwaitable = type; @@ -44129,7 +49704,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -44208,7 +49783,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -44228,7 +49804,7 @@ var ts; * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -44253,58 +49829,57 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { - if (returnType === unknownType) { - return unknownType; + if (returnType === errorType) { + return errorType; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; + return errorType; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); - if (returnType === unknownType) { - return unknownType; + if (returnType === errorType) { + return errorType; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; + return errorType; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return unknownType; + return errorType; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; + return errorType; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; + return errorType; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return unknownType; + return errorType; } } // Get and return the awaited type of the return type. @@ -44321,26 +49896,30 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 148 /* Parameter */: + case 149 /* Parameter */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -44380,12 +49959,12 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 169 /* IntersectionType */: - case 168 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 172 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -44417,9 +49996,9 @@ var ts; } } return commonEntityName; - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; } } @@ -44443,14 +50022,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -44459,19 +50038,19 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 148 /* Parameter */: + case 149 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -44487,18 +50066,22 @@ var ts; if (produceDiagnostics) { checkFunctionOrMethodDeclaration(node); checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); @@ -44508,13 +50091,17 @@ var ts; // and give a better error message when the host function mentions `arguments` // but the tag doesn't have an array type if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -44525,13 +50112,13 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285 /* JSDocAugmentsTag */); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); ts.Debug.assert(augmentsTags.length > 0); if (augmentsTags.length > 1) { error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(classLike); + var extend = ts.getClassExtendsHeritageElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { @@ -44543,7 +50130,7 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -44556,7 +50143,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -44585,16 +50172,13 @@ var ts; } } } - var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -44607,140 +50191,110 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - registerForUnusedIdentifiersCheck(node); + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); } } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 272 /* SourceFile */: - case 237 /* ModuleDeclaration */: - checkUnusedModuleMembers(node); - break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 234 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node); - break; - case 211 /* Block */: - case 239 /* CaseBlock */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - checkUnusedLocalsAndParameters(node); - break; - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 235 /* TypeAliasDeclaration */: - checkUnusedTypeParameters(node); - break; - default: - ts.Debug.fail("Node should not have been registered for unused identifiers check"); - } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 239 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 277 /* SourceFile */: + case 242 /* ModuleDeclaration */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + if (node.body) { + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 240 /* TypeAliasDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } } } - function checkUnusedLocalsAndParameters(node) { - if (noUnusedIdentifiers && !(node.flags & 2097152 /* Ambient */)) { - node.locals.forEach(function (local) { - // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. - // If it's a type parameter merged with a parameter, check if the parameter-side is used. - if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(declaration, name) { + function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 230 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147 /* TypeParameter */) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { + function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { + function checkUnusedClassMembers(node, addDiagnostic) { + if (!(node.flags & 4194304 /* Ambient */)) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 153 /* MethodDeclaration */: - case 151 /* PropertyDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - if (member.kind === 156 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 154 /* MethodDeclaration */: + case 152 /* PropertyDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 154 /* Constructor */: + case 155 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; - case 159 /* IndexSignature */: - case 210 /* SemicolonClassElement */: + case 160 /* IndexSignature */: + case 215 /* SemicolonClassElement */: // Can't be private break; default: @@ -44749,84 +50303,152 @@ var ts; } } } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedParameters && !(node.flags & 2097152 /* Ambient */)) { - if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); - } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); } } } } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { - errorUnusedLocal(declaration, ts.symbolName(local)); + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name)); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } - }); + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 243 /* ImportClause */ || node.kind === 246 /* ImportSpecifier */ || node.kind === 244 /* NamespaceImport */; + return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 243 /* ImportClause */ ? decl : decl.kind === 244 /* NamespaceImport */ ? decl.parent : decl.parent.parent; - } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 244 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 211 /* Block */) { + if (node.kind === 216 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -44843,7 +50465,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -44856,36 +50478,26 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 152 /* MethodSignature */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 151 /* PropertySignature */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 153 /* MethodSignature */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { // ambient context - no codegen impact return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 148 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } return true; } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } // this function will run after checking the source file so 'CaptureThis' is correct for all nodes function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { @@ -44899,6 +50511,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -44913,31 +50526,12 @@ var ts; } return true; } + return false; }); } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - // bubble up and find containing type - var enclosingClass = ts.getContainingClass(node); - // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || enclosingClass.flags & 2097152 /* Ambient */) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71 /* Identifier */; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -44949,13 +50543,13 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check @@ -44964,7 +50558,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -44999,7 +50593,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 230 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -45011,17 +50605,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 231 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 212 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 211 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 238 /* ModuleBlock */ || - container.kind === 237 /* ModuleDeclaration */ || - container.kind === 272 /* SourceFile */); + (container.kind === 216 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 243 /* ModuleBlock */ || + container.kind === 242 /* ModuleDeclaration */ || + container.kind === 277 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -45036,7 +50630,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 148 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 149 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -45047,7 +50641,7 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 183 /* PropertyAccessExpression */) { + if (n.kind === 187 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } @@ -45066,8 +50660,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 148 /* Parameter */ || - symbol.valueDeclaration.kind === 180 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 149 /* Parameter */ || + symbol.valueDeclaration.kind === 184 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -45081,7 +50675,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 151 /* PropertyDeclaration */ && + (current.parent.kind === 152 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -45114,18 +50708,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 180 /* BindingElement */) { - if (node.parent.kind === 178 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 184 /* BindingElement */) { + if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 146 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -45133,7 +50727,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); @@ -45142,26 +50736,26 @@ var ts; } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 179 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 148 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 219 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); } else { - checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); } checkParameterInitializer(node); } @@ -45172,52 +50766,55 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 219 /* ForInStatement */) { - var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; - checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); - checkParameterInitializer(node); + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && + if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* JSContainer */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 151 /* PropertyDeclaration */ && node.kind !== 150 /* PropertySignature */) { + if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 151 /* PropertyDeclaration */ || nextDeclaration.kind === 150 /* PropertySignature */ + var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 148 /* Parameter */ && right.kind === 230 /* VariableDeclaration */) || - (left.kind === 230 /* VariableDeclaration */ && right.kind === 148 /* Parameter */)) { + if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || + (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -45256,7 +50853,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 213 /* EmptyStatement */) { + if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -45276,12 +50873,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -45299,36 +50896,34 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 220 /* ForOfStatement */) { - if (node.awaitModifier) { - var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { - // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper - checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { - // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled - checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } // Check the LHS and RHS // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 181 /* ArrayLiteralExpression */ || varExpr.kind === 182 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. - checkDestructuringAssignment(varExpr, iteratedType || unknownType); + checkDestructuringAssignment(varExpr, iteratedType || errorType); } else { var leftType = checkExpression(varExpr); @@ -45338,7 +50933,7 @@ var ts; // because we accessed properties from anyType, or it may have led to an error inside // getElementTypeOfIterable. if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); } } } @@ -45356,7 +50951,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -45370,7 +50965,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 181 /* ArrayLiteralExpression */ || varExpr.kind === 182 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -45383,8 +50978,8 @@ 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 (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { - 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); + if (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + 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_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); if (node.locals) { @@ -45415,6 +51010,10 @@ var ts; * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } var uplevelIteration = languageVersion >= 2 /* ES2015 */; var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 @@ -45434,16 +51033,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 131072 /* Union */) { + if (arrayType.flags & 262144 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 524322 /* StringLike */) { + else if (arrayType.flags & 68 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -45456,7 +51055,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 16384 /* Never */) { + if (arrayType.flags & 32768 /* Never */) { return stringType; } } @@ -45468,13 +51067,18 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); var diagnostic = !allowStringInput || hasStringConstituent ? downlevelIteration ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type : downlevelIteration ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); } return hasStringConstituent ? stringType : undefined; @@ -45482,7 +51086,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 524322 /* StringLike */) { + if (arrayElementType.flags & 68 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -45557,17 +51161,15 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; if (!ts.some(signatures)) { if (errorNode) { - error(errorNode, allowAsyncIterables - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); errorNode = undefined; } return undefined; @@ -45587,6 +51189,11 @@ var ts; : typeAsIterable.iteratedTypeOfIterable = iteratedType; } } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } /** * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on * Iterators instead of Iterables. Here is the structure: @@ -45684,14 +51291,14 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 155 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 156 /* SetAccessor */)) !== undefined; + return node.kind === 156 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -45707,7 +51314,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -45716,17 +51323,17 @@ var ts; // for generators. return; } - else if (func.kind === 156 /* SetAccessor */) { + else if (func.kind === 157 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 154 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + else if (func.kind === 155 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func) || getReturnTypeOfTypeTag(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -45738,11 +51345,11 @@ var ts; } } else { - checkTypeAssignableTo(exprType, returnType, node); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); } } } - else if (func.kind !== 154 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -45771,7 +51378,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 265 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -45783,7 +51390,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 264 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -45812,10 +51419,11 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 226 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } // ensure that label is unique @@ -45875,8 +51483,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. @@ -45900,7 +51508,7 @@ var ts; errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { @@ -45909,16 +51517,17 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; } // perform property check if property or indexer is declared in 'type' // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && - (propDeclaration.kind === 198 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 146 /* ComputedPropertyName */ || + if (propDeclaration && name && + (propDeclaration.kind === 202 /* BinaryExpression */ || + name.kind === 147 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -45945,6 +51554,7 @@ var ts; // The predefined type keywords are reserved and cannot be used as names of user defined types. switch (name.escapedText) { case "any": + case "unknown": case "number": case "boolean": case "string": @@ -45954,6 +51564,15 @@ var ts; error(name, message, name.escapedText); } } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } /** * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ @@ -45995,26 +51614,27 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + 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); } } } } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error - var numTypeParameters = ts.length(declaration.typeParameters); + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; + var source = sourceParameters[i]; + var target = targetParameters[i]; // If the type parameter node does not have the same as the resolved type // parameter at this position, we report an error. if (source.name.escapedText !== target.symbol.escapedName) { @@ -46023,7 +51643,7 @@ var ts; // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -46063,12 +51683,13 @@ var ts; checkDecorators(node); if (node.name) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } } - checkTypeParameters(node.typeParameters); + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); var type = getDeclaredTypeOfSymbol(symbol); @@ -46077,10 +51698,10 @@ var ts; checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 2097152 /* Ambient */)) { + if (!(node.flags & 4194304 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); if (baseTypeNode) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); @@ -46092,6 +51713,10 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { @@ -46106,10 +51731,10 @@ var ts; issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 1081344 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked @@ -46132,7 +51757,7 @@ var ts; checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { + if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : @@ -46158,7 +51783,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_5 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -46177,7 +51802,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_5(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -46203,7 +51828,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 233 /* ClassDeclaration */ || d.kind === 234 /* InterfaceDeclaration */; + return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -46228,7 +51853,7 @@ var ts; if (base.flags & 4194304 /* Prototype */) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { @@ -46242,7 +51867,7 @@ var ts; // 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.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 203 /* ClassExpression */) { + if (derivedClassDecl.kind === 207 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -46257,12 +51882,12 @@ var ts; // either base or derived property is private - not override, skip it continue; } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } var errorMessage = void 0; - if (isMethodLike(base)) { + if (isPrototypeProperty(base)) { if (derived.flags & 98304 /* Accessor */) { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } @@ -46270,11 +51895,11 @@ var ts; errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; } } - else if (base.flags & 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } @@ -46314,7 +51939,7 @@ var ts; return ok; } function checkPropertyInitialization(node) { - if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152 /* Ambient */) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { return; } var constructor = findConstructorDeclaration(node); @@ -46324,7 +51949,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 1 /* Any */ || getFalsyFlags(type) & 4096 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -46334,7 +51959,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 151 /* PropertyDeclaration */ && + return node.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -46343,7 +51968,7 @@ var ts; var reference = ts.createPropertyAccess(ts.createThis(), propName); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 4096 /* Undefined */); + return !(getFalsyFlags(flowType) & 8192 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -46356,7 +51981,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 234 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -46419,7 +52044,7 @@ var ts; } // In ambient enum declarations that specify no const modifier, enum member declarations that omit // a value are considered computed members (as opposed to having auto-incremented values). - if (member.parent.flags & 2097152 /* Ambient */ && !ts.isConst(member.parent)) { + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { return undefined; } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -46434,7 +52059,7 @@ var ts; } function computeConstantValue(member) { var enumKind = getEnumKind(getSymbolOfNode(member.parent)); - var isConstEnum = ts.isConst(member.parent); + var isConstEnum = ts.isEnumConst(member.parent); var initializer = member.initializer; var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); if (value !== undefined) { @@ -46451,7 +52076,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (member.parent.flags & 2097152 /* Ambient */) { + else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -46461,7 +52086,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -46471,7 +52096,7 @@ var ts; } } break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -46490,24 +52115,31 @@ var ts; case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + return left + right; + } break; case 9 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); - case 184 /* ElementAccessExpression */: - case 183 /* PropertyAccessExpression */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 183 /* PropertyAccessExpression */) { + if (ex.kind === 187 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -46539,8 +52171,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 184 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { @@ -46550,14 +52182,12 @@ var ts; // Grammar checking checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152 /* Ambient */) { + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } // Spec 2014 - Section 9.3: @@ -46572,7 +52202,7 @@ var ts; if (enumSymbol.declarations.length > 1) { // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); @@ -46580,7 +52210,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 236 /* EnumDeclaration */) { + if (declaration.kind !== 241 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -46601,11 +52231,11 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - if ((declaration.kind === 233 /* ClassDeclaration */ || - (declaration.kind === 232 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 2097152 /* Ambient */)) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 238 /* ClassDeclaration */ || + (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } } @@ -46628,7 +52258,7 @@ var ts; if (produceDiagnostics) { // Grammar checking var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = node.flags & 2097152 /* Ambient */; + var inAmbientContext = node.flags & 4194304 /* Ambient */; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -46646,7 +52276,6 @@ var ts; } } if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } @@ -46656,7 +52285,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -46668,7 +52297,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 233 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 238 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -46718,23 +52347,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 241 /* ImportEqualsDeclaration */: - case 242 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 180 /* BindingElement */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -46745,12 +52374,12 @@ var ts; break; } // falls through - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 232 /* FunctionDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 237 /* FunctionDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -46773,12 +52402,12 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: do { node = node.left; } while (node.kind !== 71 /* Identifier */); return node; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 71 /* Identifier */); @@ -46787,7 +52416,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { // Should be a parse error. return false; } @@ -46795,9 +52424,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 238 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 272 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 248 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 253 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -46830,22 +52459,21 @@ var ts; (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 250 /* ExportSpecifier */ ? + var message = node.kind === 255 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 250 /* ExportSpecifier */ + && node.kind === 255 /* ExportSpecifier */ && !(target.flags & 67216319 /* Value */) - && !(node.flags & 2097152 /* Ambient */)) { + && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } } function checkImportBinding(node) { - checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); @@ -46865,11 +52493,14 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 244 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } } } } @@ -46886,7 +52517,7 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 252 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 67216319 /* Value */) { @@ -46902,7 +52533,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -46922,27 +52553,27 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 238 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 238 /* ModuleBlock */ && - !node.moduleSpecifier && node.flags & 2097152 /* Ambient */; - if (node.parent.kind !== 272 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 272 /* SourceFile */ || node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 237 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -46971,8 +52602,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 272 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 237 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -46995,15 +52626,15 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if ((node.flags & 2097152 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !(node.flags & 2097152 /* Ambient */)) { - if (modulekind >= ts.ModuleKind.ES2015) { + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === ts.ModuleKind.System) { + else if (moduleKind === ts.ModuleKind.System) { // system modules does not support export assignment grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } @@ -47019,14 +52650,14 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_2 = getExportsOfModule(moduleSymbol); + if (exports_2) { + exports_2.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -47043,8 +52674,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -47060,167 +52691,172 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 232 /* FunctionDeclaration */ && declaration.kind !== 153 /* MethodDeclaration */) || + return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return checkTypeParameter(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return checkParameter(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return checkPropertyDeclaration(node); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return checkSignatureDeclaration(node); - case 159 /* IndexSignature */: - return checkSignatureDeclaration(node); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: return checkMethodDeclaration(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return checkConstructorDeclaration(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return checkAccessorDeclaration(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return checkTypeReferenceNode(node); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return checkTypePredicate(node); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return checkTypeQuery(node); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return checkTypeLiteral(node); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return checkArrayType(node); - case 167 /* TupleType */: + case 168 /* TupleType */: return checkTupleType(node); - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: + case 169 /* OptionalType */: + case 170 /* RestType */: return checkSourceElement(node.type); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return checkTypeOperator(node); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return checkConditionalType(node); - case 171 /* InferType */: + case 174 /* InferType */: return checkInferType(node); - case 285 /* JSDocAugmentsTag */: + case 181 /* ImportType */: + return checkImportType(node); + case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 291 /* JSDocTypedefTag */: - return checkJSDocTypedefTag(node); - case 287 /* JSDocParameterTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 299 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 296 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 278 /* JSDocNonNullableType */: - case 277 /* JSDocNullableType */: - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: + case 290 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 274 /* JSDocTypeExpression */: + case 281 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 176 /* MappedType */: + case 179 /* MappedType */: return checkMappedType(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 211 /* Block */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return checkBlock(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return checkVariableStatement(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return checkExpressionStatement(node); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return checkIfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return checkDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return checkWhileStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return checkForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return checkForInStatement(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return checkForOfStatement(node); - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return checkReturnStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return checkWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return checkSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return checkLabeledStatement(node); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return checkThrowStatement(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return checkTryStatement(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return checkBindingElement(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return checkClassDeclaration(node); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return checkImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return checkExportDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return checkExportAssignment(node); - case 213 /* EmptyStatement */: + case 218 /* EmptyStatement */: + case 234 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 229 /* DebuggerStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 251 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -47232,12 +52868,18 @@ var ts; function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - // Only legal location is in the *last* parameter tag. + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -47255,8 +52897,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { @@ -47275,6 +52917,9 @@ var ts; } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } // Function and class expression bodies are checked after all statements in the enclosing body. This is @@ -47288,28 +52933,34 @@ var ts; // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { if (deferredNodes) { - deferredNodes.push(node); + var id = "" + getNodeId(node); + deferredNodes.set(id, node); } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + deferredNodes.forEach(function (node) { switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: checkClassExpressionDeferred(node); break; + case 259 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 258 /* JsxElement */: + checkJsxElementDeferred(node); + break; } - } + }); } function checkSourceFile(node) { ts.performance.mark("beforeCheck"); @@ -47317,6 +52968,19 @@ var ts; ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -47331,19 +52995,20 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - flowAnalysisDisabled = false; + deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); } deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -47410,7 +53075,7 @@ var ts; } // Language service support function getSymbolsInScope(location, meaning) { - if (location.flags & 4194304 /* InWithStatement */) { + if (location.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return []; } @@ -47424,13 +53089,13 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -47438,8 +53103,8 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -47448,7 +53113,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -47496,28 +53161,28 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 147 /* TypeParameter */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: + case 148 /* TypeParameter */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: return true; + default: + return false; } } // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145 /* QualifiedName */) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 161 /* TypeReference */; + return node.parent.kind === 162 /* TypeReference */; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 183 /* PropertyAccessExpression */) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 187 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 205 /* ExpressionWithTypeArguments */; + return node.parent.kind === 209 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -47545,14 +53210,14 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 145 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 241 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 247 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -47571,12 +53236,23 @@ var ts; return getSymbolOfNode(entityName.parent.parent); } } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 183 /* PropertyAccessExpression */ && + entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -47584,23 +53260,35 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 247 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } } - if (entityName.kind !== 183 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 241 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 205 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -47616,10 +53304,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 287 /* JSDocParameterTag */) { + if (entityName.parent.kind === 296 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 290 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -47636,12 +53324,12 @@ var ts; } return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 183 /* PropertyAccessExpression */ || entityName.kind === 145 /* QualifiedName */) { + else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 183 /* PropertyAccessExpression */) { + if (entityName.kind === 187 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -47651,41 +53339,43 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 260 /* JsxAttribute */) { + else if (entityName.parent.kind === 265 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 160 /* TypePredicate */) { + if (entityName.parent.kind === 161 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (node.flags & 4194304 /* InWithStatement */) { + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 180 /* BindingElement */ && - node.parent.parent.kind === 178 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 184 /* BindingElement */ && + grandParent.kind === 182 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -47694,8 +53384,8 @@ var ts; } switch (node.kind) { case 71 /* Identifier */: - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -47709,14 +53399,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 173 /* ThisType */: + case 176 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 97 /* SuperKeyword */: return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 154 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -47725,33 +53415,34 @@ var ts; // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 242 /* ImportDeclaration */ || node.parent.kind === 248 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } // falls through case 8 /* NumericLiteral */: // index access - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); + case 181 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - // The function returns a value symbol of an identifier in the short-hand property assignment. - // This is necessary as an identifier in short-hand property assignment can contains two meaning: - // property name and property value. - if (location && location.kind === 269 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -47763,9 +53454,9 @@ var ts; resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further - return unknownType; + return errorType; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); @@ -47794,7 +53485,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -47803,19 +53494,19 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); if (symbol) { var declaredType = getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); } } - return unknownType; + return errorType; } // Gets the type of object literal or array literal of destructuring assignment. // { a } from @@ -47824,32 +53515,32 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 182 /* ObjectLiteralExpression */ || expr.kind === 181 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 220 /* ForOfStatement */) { + if (expr.parent.kind === 225 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); + return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 198 /* BinaryExpression */) { + if (expr.parent.kind === 202 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); + return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 268 /* PropertyAssignment */) { + if (expr.parent.kind === 273 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 181 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -47920,11 +53611,11 @@ var ts; return target; } // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -47955,13 +53646,12 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum // declaration, we need to start resolution at the declaration's container. @@ -47981,7 +53671,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 272 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -47995,8 +53685,8 @@ var ts; } // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value @@ -48036,7 +53726,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 211 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -48051,9 +53741,9 @@ var ts; // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -48065,8 +53755,8 @@ var ts; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -48077,16 +53767,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 247 /* ExportAssignment */: + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 252 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -48094,9 +53784,9 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 272 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -48110,11 +53800,11 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return target.flags & 67216319 /* Value */ && + return !!(target.flags & 67216319 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -48122,19 +53812,21 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } - var target = getSymbolLinks(symbol).target; + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -48154,9 +53846,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && - parameter.initializer && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { @@ -48166,7 +53859,7 @@ var ts; ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -48174,32 +53867,33 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 271 /* EnumMember */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: + case 276 /* EnumMember */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 271 /* EnumMember */) { + if (node.kind === 276 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & 8 /* EnumMember */)) { // inline property\index accesses only for const enums - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); } } return undefined; } function isFunctionType(type) { - return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { + function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -48223,31 +53917,31 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { return ts.TypeReferenceSerializationKind.Unknown; } - else if (type.flags & 1 /* Any */) { + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 2048 /* Void */ | 12288 /* Nullable */ | 16384 /* Never */)) { + else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 524322 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 1536 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -48260,28 +53954,40 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119 /* AnyKeyword */); + } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (type.flags & 1024 /* UniqueESSymbol */ && + : errorType; + if (type.flags & 2048 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 131072 /* AddUndefined */) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119 /* AnyKeyword */); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(119 /* AnyKeyword */); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -48302,9 +54008,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -48315,15 +54021,18 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { + if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */); + return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -48334,7 +54043,7 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createMap(); resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { return; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); @@ -48359,20 +54068,21 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -48385,26 +54095,44 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { // program does not have any files with type reference directives - bail out if (!fileToDirective) { return undefined; } - // property access can only be used as values + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 183 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 67216319 /* Value */ | 1048576 /* ExportValue */ - : 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -48453,7 +54181,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 272 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -48468,12 +54196,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 272 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -48481,10 +54209,14 @@ var ts; var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); } + amalgamatedDuplicates = ts.createMap(); // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; + if (file.redirectInfo) { + continue; + } if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -48504,7 +54236,7 @@ var ts; }); } } - // We do global augmentations seperately from module augmentations (and before creating global types) because they + // We do global augmentations separately from module augmentations (and before creating global types) because they // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require // checking for an export or property on the module (if export=) which, in turn, can fall back to the @@ -48527,7 +54259,7 @@ var ts; addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedWideningType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); - getSymbolLinks(unknownSymbol).type = unknownType; + getSymbolLinks(unknownSymbol).type = errorType; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); @@ -48558,11 +54290,37 @@ var ts; } } } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; + var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + // If not many things conflict, issue individual errors + if (conflictingKeys.length < 8) { + addErrorsForDuplicates(firstFileInstances, secondFileInstances); + addErrorsForDuplicates(secondFileInstances, firstFileInstances); + return; + } + // Otheriwse issue top-level error since the files appear very identical in terms of what they appear + var list = conflictingKeys.join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + }); + amalgamatedDuplicates = undefined; + function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { + secondFileInstances.forEach(function (locations, symbolName) { + var firstFileEquivalent = firstFileInstances.get(symbolName); + var message = locations.blockScoped + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + locations.instances.forEach(function (node) { + addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); + }); + }); + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152 /* Ambient */)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; @@ -48599,7 +54357,7 @@ var ts; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -48617,14 +54375,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 153 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 155 /* GetAccessor */ || node.kind === 156 /* SetAccessor */) { + else if (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -48642,16 +54400,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 150 /* PropertySignature */ || node.kind === 152 /* MethodSignature */) { + if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 159 /* IndexSignature */) { + if (node.kind === 160 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76 /* ConstKeyword */: - if (node.kind !== 236 /* EnumDeclaration */ && node.parent.kind === 233 /* ClassDeclaration */) { + if (node.kind !== 241 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; @@ -48671,7 +54429,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -48694,10 +54452,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -48710,7 +54468,7 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 151 /* PropertyDeclaration */ && node.kind !== 150 /* PropertySignature */ && node.kind !== 159 /* IndexSignature */ && node.kind !== 148 /* Parameter */) { + else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } @@ -48730,17 +54488,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 233 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 79 /* DefaultKeyword */: - var container = node.parent.kind === 272 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 237 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -48752,13 +54510,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 233 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 2097152 /* Ambient */) && node.parent.kind === 238 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -48768,14 +54526,14 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 233 /* ClassDeclaration */) { - if (node.kind !== 153 /* MethodDeclaration */ && - node.kind !== 151 /* PropertyDeclaration */ && - node.kind !== 155 /* GetAccessor */ && - node.kind !== 156 /* SetAccessor */) { + if (node.kind !== 238 /* ClassDeclaration */) { + if (node.kind !== 154 /* MethodDeclaration */ && + node.kind !== 152 /* PropertyDeclaration */ && + node.kind !== 156 /* GetAccessor */ && + node.kind !== 157 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 233 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 238 /* 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 */) { @@ -48791,10 +54549,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || node.parent.flags & 2097152 /* Ambient */) { + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -48802,12 +54560,12 @@ var ts; break; } } - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); @@ -48815,20 +54573,21 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } - else if ((node.kind === 242 /* ImportDeclaration */ || node.kind === 241 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 148 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 148 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } /** * true | false: Early return this value from checkGrammarModifiers. @@ -48843,37 +54602,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 237 /* ModuleDeclaration */: - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - case 247 /* ExportAssignment */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 148 /* Parameter */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 242 /* ModuleDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 149 /* Parameter */: return false; default: - if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return false; } switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 234 /* InterfaceDeclaration */: - case 212 /* VariableStatement */: - case 235 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 217 /* VariableStatement */: + case 240 /* TypeAliasDeclaration */: return true; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); @@ -48886,20 +54645,20 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); } - function checkGrammarForDisallowedTrailingComma(list) { + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -48907,6 +54666,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -48917,6 +54677,9 @@ var ts; if (i !== (parameterCount - 1)) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } if (ts.isBindingPattern(parameter.name)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } @@ -48984,10 +54747,10 @@ var ts; } if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); - if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -48995,6 +54758,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit @@ -49007,6 +54771,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -49016,11 +54781,12 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 204 /* OmittedExpression */) { + if (arg.kind === 208 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -49034,7 +54800,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -49092,20 +54858,21 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 146 /* ComputedPropertyName */) { + if (node.kind !== 147 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 198 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 232 /* FunctionDeclaration */ || - node.kind === 190 /* FunctionExpression */ || - node.kind === 153 /* MethodDeclaration */); - if (node.flags & 2097152 /* Ambient */) { + ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || + node.kind === 194 /* FunctionExpression */ || + node.kind === 154 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -49114,9 +54881,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -49129,24 +54894,24 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 270 /* SpreadAssignment */) { + if (prop.kind === 275 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 269 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 153 /* MethodDeclaration */) { + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -49161,25 +54926,25 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -49208,10 +54973,11 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 262 /* JsxSpreadAttribute */) { + if (attr.kind === 267 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -49221,7 +54987,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 263 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -49230,12 +54996,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 220 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 231 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -49250,20 +55016,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -49277,7 +55043,7 @@ var ts; if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (accessor.flags & 2097152 /* Ambient */) { + else if (accessor.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { @@ -49290,11 +55056,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 155 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 156 /* SetAccessor */) { + else if (kind === 157 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -49311,16 +55077,17 @@ var ts; } } } + return false; } /** Does the accessor have the right number of parameters? * A get accessor has no parameters or a single `this` parameter. * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 155 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 155 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -49331,7 +55098,7 @@ var ts; } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 71 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -49343,13 +55110,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -49368,8 +55135,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 153 /* MethodDeclaration */) { - if (node.parent.kind === 182 /* ObjectLiteralExpression */) { + if (node.kind === 154 /* MethodDeclaration */) { + if (node.parent.kind === 186 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -49391,17 +55158,17 @@ var ts; // However, property declarations disallow computed names in general, // and accessors are not allowed in ambient contexts in general, // so this error only really matters for methods. - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 153 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 234 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 165 /* TypeLiteral */) { + else if (node.parent.kind === 166 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -49412,11 +55179,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 221 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -49424,8 +55191,8 @@ var ts; return false; } break; - case 225 /* SwitchStatement */: - if (node.kind === 222 /* BreakStatement */ && !node.label) { + case 230 /* SwitchStatement */: + if (node.kind === 227 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -49440,13 +55207,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 222 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 222 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -49458,7 +55225,8 @@ var ts; if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 179 /* ArrayBindingPattern */ || node.name.kind === 178 /* ObjectBindingPattern */) { + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.propertyName) { @@ -49472,14 +55240,14 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 196 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 219 /* ForInStatement */ && node.parent.parent.kind !== 220 /* ForOfStatement */) { - if (node.flags & 2097152 /* Ambient */) { + if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { if (node.initializer) { - if (ts.isConst(node) && !node.type) { + if (ts.isVarConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); } @@ -49490,7 +55258,7 @@ var ts; 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))) { + if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -49500,19 +55268,19 @@ var ts; if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); } - if (ts.isConst(node)) { + if (ts.isVarConst(node)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); } } } - if (node.exclamationToken && (node.parent.parent.kind !== 212 /* VariableStatement */ || !node.type || node.initializer || node.flags & 2097152 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !(node.parent.parent.flags & 2097152 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -49536,6 +55304,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71 /* Identifier */) { @@ -49552,6 +55321,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -49561,18 +55331,19 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return false; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -49582,16 +55353,24 @@ var ts; if (ts.isLet(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (ts.isConst(node.declarationList)) { + else if (ts.isVarConst(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } } function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */) { - if (node.name.escapedText !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); - } + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 94 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 91 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; } } function hasParseDiagnostics(sourceFile) { @@ -49600,10 +55379,11 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -49611,6 +55391,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -49618,11 +55399,12 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); + if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { + var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -49638,7 +55420,7 @@ var ts; return true; } } - else if (node.parent.kind === 234 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -49646,7 +55428,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 165 /* TypeLiteral */) { + else if (node.parent.kind === 166 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -49654,11 +55436,11 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 2097152 /* Ambient */ && node.initializer) { + if (node.flags & 4194304 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || - node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } } @@ -49675,13 +55457,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 234 /* InterfaceDeclaration */ || - node.kind === 235 /* TypeAliasDeclaration */ || - node.kind === 242 /* ImportDeclaration */ || - node.kind === 241 /* ImportEqualsDeclaration */ || - node.kind === 248 /* ExportDeclaration */ || - node.kind === 247 /* ExportAssignment */ || - node.kind === 240 /* NamespaceExportDeclaration */ || + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 240 /* TypeAliasDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 253 /* ExportDeclaration */ || + node.kind === 252 /* ExportAssignment */ || + node.kind === 245 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -49690,18 +55472,19 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 212 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 217 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } } } + return false; } function checkGrammarSourceFile(node) { - return !!(node.flags & 2097152 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { // An accessors is already reported about the ambient context if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; @@ -49716,7 +55499,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 211 /* Block */ || node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -49729,6 +55512,7 @@ var ts; // Debug.assert(isStatement(node.parent)); } } + return false; } function checkGrammarNumericLiteral(node) { // Grammar checking @@ -49737,10 +55521,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 177 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 271 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -49749,14 +55533,16 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -49771,8 +55557,8 @@ var ts; return ambientModulesCache; } function checkGrammarImportCallExpression(node) { - if (modulekind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -49786,14 +55572,15 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -49801,14 +55588,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 243 /* ImportClause */: // For default import - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: // For rename import `x as y` + case 248 /* ImportClause */: // For default import + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 246 /* ImportSpecifier */; + return decl.parent.kind === 251 /* ImportSpecifier */; default: return false; } @@ -49819,16 +55606,18 @@ var ts; JsxNames.JSX = "JSX"; JsxNames.IntrinsicElements = "IntrinsicElements"; JsxNames.ElementClass = "ElementClass"; - JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; JsxNames.Element = "Element"; JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 448 /* Literal */); + } })(ts || (ts = {})); -/// -/// var ts; (function (ts) { function createSynthesizedNode(kind) { @@ -49850,14 +55639,12 @@ var ts; * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ function createNodeArray(elements, hasTrailingComma) { - if (elements) { - if (ts.isNodeArray(elements)) { - return elements; - } - } - else { + if (!elements || elements === ts.emptyArray) { elements = []; } + else if (ts.isNodeArray(elements)) { + return elements; + } var array = elements; array.pos = -1; array.end = -1; @@ -49874,7 +55661,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -49888,7 +55675,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -49896,7 +55683,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -49913,6 +55703,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -49946,7 +55743,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; } return name; } @@ -49969,14 +55766,26 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4 /* Node */; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; - } nextAutoGenerateId++; return name; } @@ -50007,9 +55816,52 @@ var ts; return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(84 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(124 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(79 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(76 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(114 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(112 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(113 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(117 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(115 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(132 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(120 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(145 /* QualifiedName */); + var node = createSynthesizedNode(146 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -50023,13 +55875,12 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { - return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 296 /* CommaListExpression */ ? - createParen(expression) : - expression; + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(146 /* ComputedPropertyName */); + var node = createSynthesizedNode(147 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -50042,7 +55893,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(147 /* TypeParameter */); + var node = createSynthesizedNode(148 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -50058,7 +55909,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148 /* Parameter */); + var node = createSynthesizedNode(149 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -50082,7 +55933,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(149 /* Decorator */); + var node = createSynthesizedNode(150 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -50095,7 +55946,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(150 /* PropertySignature */); + var node = createSynthesizedNode(151 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -50115,7 +55966,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertyDeclaration */); + var node = createSynthesizedNode(152 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50139,7 +55990,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(152 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -50156,7 +56007,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(153 /* MethodDeclaration */); + var node = createSynthesizedNode(154 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -50184,7 +56035,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(154 /* Constructor */); + var node = createSynthesizedNode(155 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -50204,7 +56055,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(155 /* GetAccessor */); + var node = createSynthesizedNode(156 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50227,7 +56078,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(156 /* SetAccessor */); + var node = createSynthesizedNode(157 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50248,7 +56099,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(157 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -50256,7 +56107,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -50264,7 +56115,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(159 /* IndexSignature */); + var node = createSynthesizedNode(160 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -50304,7 +56155,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(160 /* TypePredicate */); + var node = createSynthesizedNode(161 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -50318,7 +56169,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(161 /* TypeReference */); + var node = createSynthesizedNode(162 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -50332,7 +56183,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(162 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -50340,7 +56191,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -50348,7 +56199,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(164 /* TypeQuery */); + var node = createSynthesizedNode(165 /* TypeQuery */); node.exprName = exprName; return node; } @@ -50360,7 +56211,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(165 /* TypeLiteral */); + var node = createSynthesizedNode(166 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -50372,7 +56223,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(166 /* ArrayType */); + var node = createSynthesizedNode(167 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -50384,19 +56235,43 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(167 /* TupleType */); + var node = createSynthesizedNode(168 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { + function updateTupleTypeNode(node, elementTypes) { return node.elementTypes !== elementTypes ? updateNode(createTupleTypeNode(elementTypes), node) : node; } - ts.updateTypleTypeNode = updateTypleTypeNode; + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(169 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(170 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(168 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -50404,7 +56279,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(169 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -50423,7 +56298,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(170 /* ConditionalType */); + var node = createSynthesizedNode(173 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -50441,7 +56316,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(171 /* InferType */); + var node = createSynthesizedNode(174 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -50452,8 +56327,26 @@ var ts; : node; } ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(181 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(172 /* ParenthesizedType */); + var node = createSynthesizedNode(175 /* ParenthesizedType */); node.type = type; return node; } @@ -50465,11 +56358,11 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(173 /* ThisType */); + return createSynthesizedNode(176 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(174 /* TypeOperator */); + var node = createSynthesizedNode(177 /* TypeOperator */); node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; @@ -50480,7 +56373,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(175 /* IndexedAccessType */); + var node = createSynthesizedNode(178 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -50494,7 +56387,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(176 /* MappedType */); + var node = createSynthesizedNode(179 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -50512,7 +56405,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(177 /* LiteralType */); + var node = createSynthesizedNode(180 /* LiteralType */); node.literal = literal; return node; } @@ -50525,7 +56418,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(178 /* ObjectBindingPattern */); + var node = createSynthesizedNode(182 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -50537,7 +56430,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(179 /* ArrayBindingPattern */); + var node = createSynthesizedNode(183 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -50549,7 +56442,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(180 /* BindingElement */); + var node = createSynthesizedNode(184 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -50568,7 +56461,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(181 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -50582,7 +56475,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(182 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -50596,9 +56489,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(183 /* PropertyAccessExpression */); + var node = createSynthesizedNode(187 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); - node.name = asName(name); + node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); return node; } @@ -50613,7 +56506,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(184 /* ElementAccessExpression */); + var node = createSynthesizedNode(188 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -50627,7 +56520,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(185 /* CallExpression */); + var node = createSynthesizedNode(189 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -50643,7 +56536,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(186 /* NewExpression */); + var node = createSynthesizedNode(190 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -50658,22 +56551,31 @@ var ts; : node; } ts.updateNew = updateNew; - function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(187 /* TaggedTemplateExpression */); + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); - node.template = template; + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } return node; } ts.createTaggedTemplate = createTaggedTemplate; - function updateTaggedTemplate(node, tag, template) { + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { return node.tag !== tag - || node.template !== template - ? updateNode(createTaggedTemplate(tag, template), node) + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) : node; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(188 /* TypeAssertionExpression */); + var node = createSynthesizedNode(192 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -50687,7 +56589,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(189 /* ParenthesizedExpression */); + var node = createSynthesizedNode(193 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -50699,7 +56601,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(190 /* FunctionExpression */); + var node = createSynthesizedNode(194 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -50723,7 +56625,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(191 /* ArrowFunction */); + var node = createSynthesizedNode(195 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -50757,7 +56659,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(192 /* DeleteExpression */); + var node = createSynthesizedNode(196 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50769,7 +56671,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(193 /* TypeOfExpression */); + var node = createSynthesizedNode(197 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50781,7 +56683,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(194 /* VoidExpression */); + var node = createSynthesizedNode(198 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50793,7 +56695,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(195 /* AwaitExpression */); + var node = createSynthesizedNode(199 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50805,7 +56707,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(196 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -50818,7 +56720,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(197 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -50831,7 +56733,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(198 /* BinaryExpression */); + var node = createSynthesizedNode(202 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -50848,7 +56750,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(199 /* ConditionalExpression */); + var node = createSynthesizedNode(203 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -50878,7 +56780,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(200 /* TemplateExpression */); + var node = createSynthesizedNode(204 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -50916,7 +56818,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(201 /* YieldExpression */); + var node = createSynthesizedNode(205 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; @@ -50930,7 +56832,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(202 /* SpreadElement */); + var node = createSynthesizedNode(206 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -50942,7 +56844,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(203 /* ClassExpression */); + var node = createSynthesizedNode(207 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50963,11 +56865,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(204 /* OmittedExpression */); + return createSynthesizedNode(208 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(205 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -50981,7 +56883,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(206 /* AsExpression */); + var node = createSynthesizedNode(210 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -50995,7 +56897,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(207 /* NonNullExpression */); + var node = createSynthesizedNode(211 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -51007,7 +56909,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(208 /* MetaProperty */); + var node = createSynthesizedNode(212 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -51021,7 +56923,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(209 /* TemplateSpan */); + var node = createSynthesizedNode(214 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -51035,12 +56937,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(210 /* SemicolonClassElement */); + return createSynthesizedNode(215 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(211 /* Block */); + var block = createSynthesizedNode(216 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -51054,7 +56956,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(212 /* VariableStatement */); + var node = createSynthesizedNode(217 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -51069,23 +56971,27 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(213 /* EmptyStatement */); + return createSynthesizedNode(218 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; - function createStatement(expression) { - var node = createSynthesizedNode(214 /* ExpressionStatement */); + function createExpressionStatement(expression) { + var node = createSynthesizedNode(219 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } - ts.createStatement = createStatement; - function updateStatement(node, expression) { + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { return node.expression !== expression - ? updateNode(createStatement(expression), node) + ? updateNode(createExpressionStatement(expression), node) : node; } - ts.updateStatement = updateStatement; + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(215 /* IfStatement */); + var node = createSynthesizedNode(220 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -51101,7 +57007,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(216 /* DoStatement */); + var node = createSynthesizedNode(221 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -51115,7 +57021,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(217 /* WhileStatement */); + var node = createSynthesizedNode(222 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -51129,7 +57035,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(218 /* ForStatement */); + var node = createSynthesizedNode(223 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -51147,7 +57053,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(219 /* ForInStatement */); + var node = createSynthesizedNode(224 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -51163,7 +57069,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(220 /* ForOfStatement */); + var node = createSynthesizedNode(225 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -51181,7 +57087,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(221 /* ContinueStatement */); + var node = createSynthesizedNode(226 /* ContinueStatement */); node.label = asName(label); return node; } @@ -51193,7 +57099,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(222 /* BreakStatement */); + var node = createSynthesizedNode(227 /* BreakStatement */); node.label = asName(label); return node; } @@ -51205,7 +57111,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(223 /* ReturnStatement */); + var node = createSynthesizedNode(228 /* ReturnStatement */); node.expression = expression; return node; } @@ -51217,7 +57123,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(224 /* WithStatement */); + var node = createSynthesizedNode(229 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -51231,7 +57137,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(225 /* SwitchStatement */); + var node = createSynthesizedNode(230 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -51245,7 +57151,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(226 /* LabeledStatement */); + var node = createSynthesizedNode(231 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -51259,7 +57165,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(227 /* ThrowStatement */); + var node = createSynthesizedNode(232 /* ThrowStatement */); node.expression = expression; return node; } @@ -51271,7 +57177,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(228 /* TryStatement */); + var node = createSynthesizedNode(233 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -51287,11 +57193,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(229 /* DebuggerStatement */); + return createSynthesizedNode(234 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(230 /* VariableDeclaration */); + var node = createSynthesizedNode(235 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -51307,7 +57213,8 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(231 /* VariableDeclarationList */); + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(236 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -51320,7 +57227,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(232 /* FunctionDeclaration */); + var node = createSynthesizedNode(237 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -51346,7 +57253,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(233 /* ClassDeclaration */); + var node = createSynthesizedNode(238 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51368,7 +57275,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(234 /* InterfaceDeclaration */); + var node = createSynthesizedNode(239 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51390,7 +57297,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(235 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51410,7 +57317,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(236 /* EnumDeclaration */); + var node = createSynthesizedNode(241 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51428,7 +57335,8 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(237 /* ModuleDeclaration */); + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(242 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -51447,7 +57355,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(238 /* ModuleBlock */); + var node = createSynthesizedNode(243 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -51459,7 +57367,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(239 /* CaseBlock */); + var node = createSynthesizedNode(244 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -51471,7 +57379,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(240 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -51483,7 +57391,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(241 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51501,7 +57409,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(242 /* ImportDeclaration */); + var node = createSynthesizedNode(247 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -51519,7 +57427,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(243 /* ImportClause */); + var node = createSynthesizedNode(248 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -51533,7 +57441,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(244 /* NamespaceImport */); + var node = createSynthesizedNode(249 /* NamespaceImport */); node.name = name; return node; } @@ -51545,7 +57453,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(245 /* NamedImports */); + var node = createSynthesizedNode(250 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -51557,7 +57465,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246 /* ImportSpecifier */); + var node = createSynthesizedNode(251 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -51571,7 +57479,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(247 /* ExportAssignment */); + var node = createSynthesizedNode(252 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; @@ -51588,7 +57496,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(248 /* ExportDeclaration */); + var node = createSynthesizedNode(253 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -51606,7 +57514,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(249 /* NamedExports */); + var node = createSynthesizedNode(254 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -51618,7 +57526,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(250 /* ExportSpecifier */); + var node = createSynthesizedNode(255 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -51633,7 +57541,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(252 /* ExternalModuleReference */); + var node = createSynthesizedNode(257 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -51646,7 +57554,7 @@ var ts; ts.updateExternalModuleReference = updateExternalModuleReference; // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(253 /* JsxElement */); + var node = createSynthesizedNode(258 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -51661,36 +57569,40 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(254 /* JsxSelfClosingElement */); + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(255 /* JsxOpeningElement */); + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(256 /* JsxClosingElement */); + var node = createSynthesizedNode(261 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -51702,7 +57614,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(257 /* JsxFragment */); + var node = createSynthesizedNode(262 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -51718,7 +57630,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(260 /* JsxAttribute */); + var node = createSynthesizedNode(265 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -51732,7 +57644,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(261 /* JsxAttributes */); + var node = createSynthesizedNode(266 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -51744,7 +57656,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(262 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -51756,7 +57668,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(263 /* JsxExpression */); + var node = createSynthesizedNode(268 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -51770,7 +57682,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(264 /* CaseClause */); + var node = createSynthesizedNode(269 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -51784,7 +57696,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(265 /* DefaultClause */); + var node = createSynthesizedNode(270 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -51796,7 +57708,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(266 /* HeritageClause */); + var node = createSynthesizedNode(271 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -51809,7 +57721,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(267 /* CatchClause */); + var node = createSynthesizedNode(272 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -51824,7 +57736,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(268 /* PropertyAssignment */); + var node = createSynthesizedNode(273 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -51839,7 +57751,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(269 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -51853,8 +57765,8 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(270 /* SpreadAssignment */); - node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + var node = createSynthesizedNode(275 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } ts.createSpreadAssignment = createSpreadAssignment; @@ -51866,7 +57778,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(271 /* EnumMember */); + var node = createSynthesizedNode(276 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -51880,31 +57792,33 @@ var ts; } ts.updateEnumMember = updateEnumMember; // Top-level nodes - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { - var updated = createSynthesizedNode(272 /* SourceFile */); + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(277 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; - if (node.hasNoDefaultLib !== undefined) - updated.hasNoDefaultLib = node.hasNoDefaultLib; if (node.languageVersion !== undefined) updated.languageVersion = node.languageVersion; if (node.scriptKind !== undefined) @@ -51925,6 +57839,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -51967,7 +57883,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(294 /* NotEmittedStatement */); + var node = createSynthesizedNode(304 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -51979,7 +57895,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -51991,7 +57907,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -52006,7 +57922,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(295 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -52022,7 +57938,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 296 /* CommaListExpression */) { + if (node.kind === 306 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -52032,7 +57948,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(296 /* CommaListExpression */); + var node = createSynthesizedNode(306 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -52043,15 +57959,37 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { - var node = ts.createNode(273 /* Bundle */); + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(278 /* Bundle */); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(279 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(280 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -52135,6 +58073,7 @@ var ts; return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; + // Utilities function asName(name) { return ts.isString(name) ? createIdentifier(name) : name; } @@ -52180,7 +58119,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -52323,6 +58262,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; /** * Gets the constant value to emit for an expression. */ @@ -52486,7 +58434,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -52619,7 +58568,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -52630,7 +58579,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -52655,7 +58604,7 @@ var ts; // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*typeNode*/ undefined, boundValue); return ts.setTextRange(ts.createVariableStatement( @@ -52681,7 +58630,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 226 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -52699,19 +58648,20 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; @@ -52731,7 +58681,7 @@ var ts; } else { switch (callee.kind) { - case 183 /* PropertyAccessExpression */: { + case 187 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -52744,7 +58694,7 @@ var ts; } break; } - case 184 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -52801,14 +58751,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 268 /* PropertyAssignment */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 273 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -52822,7 +58772,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, - /*type*/ undefined, getAccessor.body); + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); @@ -52833,7 +58784,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, - /*type*/ undefined, setAccessor.body); + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -52864,7 +58816,8 @@ var ts; return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, - /*type*/ undefined, method.body), + /*type*/ undefined, method.body // TODO: GH#18217 + ), /*location*/ method), /*original*/ method)), /*location*/ method), @@ -52947,6 +58900,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -52990,7 +58944,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -53005,7 +58959,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -53065,15 +59020,9 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -53132,7 +59081,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 189 /* ParenthesizedExpression */) { + if (skipped.kind === 193 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -53166,8 +59115,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(198 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(198 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -53176,7 +59125,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 201 /* YieldExpression */) { + && operand.kind === 205 /* YieldExpression */) { return false; } return true; @@ -53264,7 +59213,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -53279,7 +59228,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(199 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -53293,8 +59242,7 @@ var ts; // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); - return emittedExpression.kind === 198 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 296 /* CommaListExpression */ + return isCommaSequence(emittedExpression) ? ts.createParen(e) : e; } @@ -53312,12 +59260,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return (check.kind === 203 /* ClassExpression */ || - check.kind === 190 /* FunctionExpression */ || - check.kind === 296 /* CommaListExpression */ || - ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -53329,9 +59280,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: return ts.createParen(expression); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -53354,7 +59305,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 186 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -53392,7 +59343,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(198 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -53403,29 +59354,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 190 /* FunctionExpression */ || kind === 191 /* ArrowFunction */) { + if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 182 /* ObjectLiteralExpression */ || leftmostExpressionKind === 190 /* FunctionExpression */) { + if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 170 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -53433,8 +59384,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 164 /* TypeQuery */: - case 174 /* TypeOperator */: + case 165 /* TypeQuery */: + case 177 /* TypeOperator */: + case 174 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -53460,25 +59412,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: node = node.operand; continue; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: node = node.left; continue; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: node = node.condition; continue; - case 185 /* CallExpression */: + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 184 /* ElementAccessExpression */: - case 183 /* PropertyAccessExpression */: - node = node.expression; - continue; - case 295 /* PartiallyEmittedExpression */: + case 210 /* AsExpression */: + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 211 /* NonNullExpression */: + case 305 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -53486,12 +59441,17 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 182 /* ObjectLiteralExpression */) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || + node.kind === 306 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; @@ -53502,13 +59462,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 207 /* NonNullExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -53533,7 +59493,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 207 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { node = node.expression; } return node; @@ -53541,11 +59501,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 189 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 188 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 206 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 207 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 295 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -53563,7 +59523,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 189 /* ParenthesizedExpression */ + return node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -53628,10 +59588,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 242 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 248 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -53646,7 +59606,7 @@ var ts; * Otherwise, a new StringLiteral node representing the module name will be returned. */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { - var moduleName = ts.getExternalModuleName(importNode); + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) @@ -53704,8 +59664,9 @@ var ts; // `1` in `({ a: b = 1 } = ...)` // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` - return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -53749,7 +59710,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -53761,11 +59722,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -53797,12 +59758,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 148 /* Parameter */: - case 180 /* BindingElement */: + case 149 /* Parameter */: + case 184 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 202 /* SpreadElement */: - case 270 /* SpreadAssignment */: + case 206 /* SpreadElement */: + case 275 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -53814,7 +59775,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 180 /* BindingElement */: + case 184 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -53826,7 +59787,7 @@ var ts; : propertyName; } break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -53838,7 +59799,7 @@ var ts; : propertyName; } break; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -53856,13 +59817,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -53902,11 +59863,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 178 /* ObjectBindingPattern */: - case 182 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -53936,9 +59897,6 @@ var ts; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; })(ts || (ts = {})); -/// -/// -/// var ts; (function (ts) { var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); @@ -54033,10 +59991,10 @@ var ts; context.startLexicalEnvironment(); statements = visitNodes(statements, visitor, ts.isStatement, start); if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { - statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; /** @@ -54070,270 +60028,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 144 /* LastToken */) || kind === 173 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { return node; } switch (kind) { // Names case 71 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148 /* Parameter */: + case 149 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* Decorator */: + case 150 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* MethodSignature */: + case 153 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* Constructor */: + case 155 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 157 /* CallSignature */: + case 158 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 162 /* FunctionType */: + case 163 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 163 /* ConstructorType */: + case 164 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 167 /* TupleType */: - return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 168 /* UnionType */: + case 168 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 169 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 170 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 171 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 169 /* IntersectionType */: + case 172 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 171 /* InferType */: + case 174 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 172 /* ParenthesizedType */: + case 181 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 175 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 176 /* MappedType */: + case 179 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 178 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 179 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 187 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 188 /* TypeAssertionExpression */: + case 191 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* AsExpression */: + case 210 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 211 /* Block */: + case 216 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 214 /* ExpressionStatement */: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 215 /* IfStatement */: + case 219 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 220 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 245 /* NamedImports */: + case 250 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 249 /* NamedExports */: + case 254 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 250 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 253 /* JsxElement */: + case 258 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxSelfClosingElement */: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 255 /* JsxOpeningElement */: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 256 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 260 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 261 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 264 /* CaseClause */: + case 269 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 271 /* EnumMember */: + case 276 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -54375,58 +60339,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 144 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 160 /* TypePredicate */ && kind <= 177 /* LiteralType */)) { + if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 210 /* SemicolonClassElement */: - case 213 /* EmptyStatement */: - case 204 /* OmittedExpression */: - case 229 /* DebuggerStatement */: - case 294 /* NotEmittedStatement */: + case 215 /* SemicolonClassElement */: + case 218 /* EmptyStatement */: + case 208 /* OmittedExpression */: + case 234 /* DebuggerStatement */: + case 304 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 148 /* Parameter */: + case 149 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149 /* Decorator */: + case 150 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54435,12 +60399,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154 /* Constructor */: + case 155 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54448,7 +60412,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54456,49 +60420,49 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 180 /* BindingElement */: + case 184 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 185 /* CallExpression */: + case 189 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 186 /* NewExpression */: + case 190 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -54506,123 +60470,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 189 /* ParenthesizedExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 195 /* AwaitExpression */: - case 201 /* YieldExpression */: - case 202 /* SpreadElement */: - case 207 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 206 /* AsExpression */: + case 210 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 211 /* Block */: + case 216 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 215 /* IfStatement */: + case 220 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 216 /* DoStatement */: + case 221 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 217 /* WhileStatement */: - case 224 /* WithStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 218 /* ForStatement */: + case 223 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* TryStatement */: + case 233 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54631,7 +60595,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54639,139 +60603,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 243 /* ImportClause */: + case 248 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 253 /* JsxElement */: + case 258 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 264 /* CaseClause */: + case 269 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 267 /* CatchClause */: + case 272 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 271 /* EnumMember */: + case 276 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 272 /* SourceFile */: + case 277 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -54785,8 +60749,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -54844,7 +60808,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 205 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -54863,9 +60827,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } - : ts.noop; // TODO: GH#22091 + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; @@ -54893,7 +60858,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 65536 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -54929,22 +60894,297 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + if (!file) { + // Otherwise check the cache (which may hit disk) + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + /*@internal*/ + function decodeMappings(map) { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + decodingIndex: 0 + }; + function captureSpan() { + return { + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + }; + } + return { + get decodingIndex() { return state.decodingIndex; }, + get error() { return state.error; }, + get lastSpan() { return captureSpan(); }, + next: function () { + if (hasCompletedDecoding(state) || state.error) + return { done: true, value: undefined }; + if (!decodeSinglePosition(state)) + return { done: true, value: undefined }; + return { done: false, value: captureSpan() }; + } + }; + } + sourcemaps.decodeMappings = decodeMappings; + function calculateDecodedMappings(map, processPosition, host) { + var decoder = decodeMappings(map); + var positions = ts.arrayFrom(decoder, processPosition); + if (decoder.error) { + if (host && host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + return []; + } + return positions; + } + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return false; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return false; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return false; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return false; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return false; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return false; + } + // Entry should be complete + return true; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return false; + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return undefined; // TODO: GH#18217 + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { function getOriginalNodeId(node) { node = ts.getOriginalNode(node); return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -54953,14 +61193,42 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -54976,21 +61244,21 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); - hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 241 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 252 /* ExternalModuleReference */) { + case 246 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -55020,13 +61288,13 @@ var ts; } } break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -55034,7 +61302,7 @@ var ts; } } break; - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -55054,7 +61322,7 @@ var ts; } } break; - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -55128,9 +61396,27 @@ var ts; ts.isIdentifier(expression); } ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -55161,7 +61447,7 @@ var ts; value = node.right; } else { - return value; + return ts.visitNode(value, visitor, ts.isExpression); } } } @@ -55169,7 +61455,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -55230,7 +61516,7 @@ var ts; } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; function bindingOrAssignmentElementAssignsToName(element, escapedName) { - var target = ts.getTargetOfBindingOrAssignmentElement(element); + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); } @@ -55261,13 +61547,14 @@ var ts; * @param level Indicates the extent to which flattening should occur. */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -55295,7 +61582,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -55349,7 +61636,7 @@ var ts; value = ts.createVoidZero(); } } - var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } @@ -55357,7 +61644,7 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 } } /** @@ -55409,7 +61696,7 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); bindingElements = undefined; } - var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } @@ -55605,9 +61892,6 @@ var ts; ]); } })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -55654,13 +61938,14 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; - var currentScope; + var currentLexicalScope; + var currentNameScope; var currentScopeFirstDeclarationsOfName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -55682,7 +61967,21 @@ var ts; * at the next execution site, in document order */ var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 278 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } /** * Transform TypeScript-specific syntax in a SourceFile. * @@ -55705,16 +62004,18 @@ var ts; */ function saveStateAndInvoke(node, f) { // Save state - var savedCurrentScope = currentScope; + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state - if (currentScope !== savedCurrentScope) { + if (currentLexicalScope !== savedCurrentScope) { currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } - currentScope = savedCurrentScope; + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; return visited; } /** @@ -55724,15 +62025,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 272 /* SourceFile */: - case 239 /* CaseBlock */: - case 238 /* ModuleBlock */: - case 211 /* Block */: - currentScope = node; + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 243 /* ModuleBlock */: + case 216 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 233 /* ClassDeclaration */: - case 232 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -55744,7 +62046,11 @@ var ts; // 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 === 233 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; } break; } @@ -55788,10 +62094,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -55812,13 +62118,13 @@ var ts; return node; } switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -55838,11 +62144,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 248 /* ExportDeclaration */ || - node.kind === 242 /* ImportDeclaration */ || - node.kind === 243 /* ImportClause */ || - (node.kind === 241 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 252 /* ExternalModuleReference */)) { + if (node.kind === 253 /* ExportDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 248 /* ImportClause */ || + (node.kind === 246 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 257 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -55872,23 +62178,22 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 151 /* PropertyDeclaration */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: + case 152 /* PropertyDeclaration */: + case 160 /* IndexSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 210 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -55924,52 +62229,55 @@ var ts; case 124 /* DeclareKeyword */: case 132 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 165 /* TypeLiteral */: - case 160 /* TypePredicate */: - case 147 /* TypeParameter */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 166 /* TypeLiteral */: + case 161 /* TypePredicate */: + case 148 /* TypeParameter */: case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 122 /* BooleanKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: case 105 /* VoidKeyword */: case 138 /* SymbolKeyword */: - case 163 /* ConstructorType */: - case 162 /* FunctionType */: - case 164 /* TypeQuery */: - case 161 /* TypeReference */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 170 /* ConditionalType */: - case 172 /* ParenthesizedType */: - case 173 /* ThisType */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 177 /* LiteralType */: + case 164 /* ConstructorType */: + case 163 /* FunctionType */: + case 165 /* TypeQuery */: + case 162 /* TypeReference */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 175 /* ParenthesizedType */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: // TypeScript type nodes are elided. - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: // TypeScript index signatures are elided. - case 149 /* Decorator */: + case 150 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 154 /* Constructor */: + case 155 /* Constructor */: return visitConstructor(node); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -55980,7 +62288,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -55991,35 +62299,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 148 /* Parameter */: + case 149 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -56029,43 +62337,45 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 207 /* NonNullExpression */: + case 191 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 211 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -56091,7 +62401,7 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) @@ -56134,7 +62444,7 @@ var ts; var statements = [classStatement]; // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { - statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); } pendingExpressions = savedPendingExpressions; // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -56172,7 +62482,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -56377,7 +62687,7 @@ var ts; // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent @@ -56495,7 +62805,7 @@ var ts; // // super(...arguments); // - statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } // Add the property initializers. Transforms this: @@ -56537,7 +62847,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -56574,7 +62884,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); ts.setEmitFlags(localName, 1536 /* NoComments */); - return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -56608,7 +62918,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 151 /* PropertyDeclaration */ + return member.kind === 152 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -56621,7 +62931,7 @@ var ts; function addInitializedPropertyStatements(statements, properties, receiver) { for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { var property = properties_10[_i]; - var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); statements.push(statement); @@ -56654,7 +62964,7 @@ var ts; function transformInitializedProperty(property, receiver) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -56746,12 +63056,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -56845,8 +63155,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -56904,7 +63214,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 151 /* PropertyDeclaration */ + ? member.kind === 152 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -56924,7 +63234,7 @@ var ts; function addConstructorDecorationStatement(statements, node) { var expression = generateConstructorDecorationExpression(node); if (expression) { - statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); } } /** @@ -57027,10 +63337,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 151 /* PropertyDeclaration */; + return kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 152 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -57040,7 +63350,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 153 /* MethodDeclaration */; + return node.kind === 154 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -57051,12 +63361,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; } return false; @@ -57068,15 +63378,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 151 /* PropertyDeclaration */: - case 148 /* Parameter */: - case 155 /* GetAccessor */: + case 152 /* PropertyDeclaration */: + case 149 /* Parameter */: + case 156 /* GetAccessor */: return serializeTypeNode(node.type); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 153 /* MethodDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 154 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -57113,7 +63423,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 155 /* GetAccessor */) { + if (container && node.kind === 156 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -57163,22 +63473,22 @@ var ts; case 95 /* NullKeyword */: case 131 /* NeverKeyword */: return ts.createVoidZero(); - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return ts.createIdentifier("Function"); - case 166 /* ArrayType */: - case 167 /* TupleType */: + case 167 /* ArrayType */: + case 168 /* TupleType */: return ts.createIdentifier("Array"); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: case 122 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); case 137 /* StringKeyword */: return ts.createIdentifier("String"); case 135 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 177 /* LiteralType */: + case 180 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); @@ -57188,32 +63498,31 @@ var ts; case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134 /* NumberKeyword */: return ts.createIdentifier("Number"); case 138 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return serializeTypeReferenceNode(node); - case 169 /* IntersectionType */: - case 168 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: return serializeUnionOrIntersectionType(node); - case 164 /* TypeQuery */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 165 /* TypeLiteral */: + case 165 /* TypeQuery */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 166 /* TypeLiteral */: case 119 /* AnyKeyword */: - case 173 /* ThisType */: + case 142 /* UnknownKeyword */: + case 176 /* ThisType */: + case 181 /* ImportType */: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -57223,7 +63532,7 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 172 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -57262,13 +63571,14 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -57288,18 +63598,40 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -57307,13 +63639,10 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8 /* Synthesized */; name.original = undefined; - name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 145 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + case 146 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); } } /** @@ -57323,19 +63652,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -57641,7 +63959,7 @@ var ts; // elide statement if there are no initialized variables. return undefined; } - return ts.setTextRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } else { return ts.visitEachChild(node, visitor, context); @@ -57687,6 +64005,11 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -57707,13 +64030,17 @@ var ts; return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } /** * Determines whether to emit an enum declaration. * * @param node The enum declaration node. */ function shouldEmitEnumDeclaration(node) { - return !ts.isConst(node) + return !ts.isEnumConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } @@ -57737,7 +64064,7 @@ var ts; // enum body. if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -57762,7 +64089,7 @@ var ts; // x[x["y"] = 0] = "y"; // ... // })(x || (x = {})); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -57788,8 +64115,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); @@ -57809,7 +64137,7 @@ var ts; var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); - return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -57837,7 +64165,7 @@ var ts; * @param node The module declaration node. */ function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -57887,12 +64215,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentScope.kind === 272 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 236 /* EnumDeclaration */) { + if (node.kind === 241 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -57954,7 +64282,7 @@ var ts; // module body. if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -57978,7 +64306,7 @@ var ts; // (function (x_1) { // x_1.y = ...; // })(x || (x = {})); - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -58011,7 +64339,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 238 /* ModuleBlock */) { + if (body.kind === 243 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -58029,7 +64357,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -58057,13 +64385,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 238 /* ModuleBlock */) { + if (body.kind !== 243 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 237 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -58104,7 +64432,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 244 /* NamespaceImport */) { + if (node.kind === 249 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -58259,17 +64587,17 @@ var ts; * Creates a statement for the provided expression. This is used in calls to `map`. */ function expressionToStatement(expression) { - return ts.createStatement(expression); + return ts.createExpressionStatement(expression); } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); - var statement = ts.createStatement(expression); + var statement = ts.createExpressionStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); } function createNamespaceExportExpression(exportName, exportValue, location) { return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); @@ -58336,16 +64664,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(237 /* ModuleDeclaration */); + context.enableEmitNotification(242 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 237 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 236 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; } /** * Hook for node emit. @@ -58406,9 +64734,9 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -58428,7 +64756,7 @@ var ts; // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { - var classAlias = classAliases[declaration.id]; + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { var clone_1 = ts.getSynthesizedClone(classAlias); ts.setSourceMapRange(clone_1, node); @@ -58446,9 +64774,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 272 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 237 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 236 /* EnumDeclaration */); + if (container && container.kind !== 277 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -58536,8 +64864,6 @@ var ts; text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" }; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -58568,7 +64894,7 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -58585,15 +64911,15 @@ var ts; case 120 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -58602,27 +64928,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 211 /* Block */: - case 225 /* SwitchStatement */: - case 239 /* CaseBlock */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 228 /* TryStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 215 /* IfStatement */: - case 224 /* WithStatement */: - case 226 /* LabeledStatement */: + case 216 /* Block */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 229 /* WithStatement */: + case 231 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -58632,7 +64958,7 @@ var ts; } function visitCatchClauseInAsyncBody(node) { var catchClauseNames = ts.createUnderscoreEscapedMap(); - recordDeclarationName(node.variableDeclaration, catchClauseNames); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 // names declared in a catch variable are block scoped var catchClauseUnshadowedNames; catchClauseNames.forEach(function (_, escapedName) { @@ -58657,7 +64983,7 @@ var ts; function visitVariableStatementInAsyncBody(node) { if (isVariableDeclarationListWithCollidingName(node.declarationList)) { var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); - return expression ? ts.createStatement(expression) : undefined; + return expression ? ts.createExpressionStatement(expression) : undefined; } return ts.visitEachChild(node, visitor, context); } @@ -58672,8 +64998,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } /** @@ -58765,10 +65092,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -58822,7 +65149,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 191 /* ArrowFunction */; + var isArrowFunction = node.kind === 195 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -58840,7 +65167,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -58862,7 +65189,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -58895,15 +65222,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(185 /* CallExpression */); - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(233 /* ClassDeclaration */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(154 /* Constructor */); + context.enableEmitNotification(238 /* ClassDeclaration */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(155 /* Constructor */); } } /** @@ -58943,11 +65270,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -58979,19 +65306,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 233 /* ClassDeclaration */ - || kind === 154 /* Constructor */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */; + return kind === 238 /* ClassDeclaration */ + || kind === 155 /* Constructor */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -59024,17 +65351,14 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);\n " + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -59055,7 +65379,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -59081,45 +65405,47 @@ var ts; return node; } switch (node.kind) { - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 226 /* LabeledStatement */: + case 228 /* ReturnStatement */: + return visitReturnStatement(node); + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return visitVoidExpression(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return visitConstructorDeclaration(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitParameter(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -59133,16 +65459,27 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); } return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 220 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -59154,7 +65491,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 270 /* SpreadAssignment */) { + if (e.kind === 275 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -59163,7 +65500,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 268 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -59181,7 +65518,7 @@ var ts; // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 182 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -59260,6 +65597,11 @@ var ts; bodyLocation = node.statement; statementsLocation = node.statement.statements; } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), @@ -59310,18 +65652,18 @@ var ts; ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -59432,7 +65774,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -59457,11 +65799,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -59489,15 +65831,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(185 /* CallExpression */); - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(233 /* ClassDeclaration */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(154 /* Constructor */); + context.enableEmitNotification(238 /* ClassDeclaration */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(155 /* Constructor */); } } /** @@ -59537,11 +65879,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -59573,11 +65915,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 233 /* ClassDeclaration */ - || kind === 154 /* Constructor */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */; + return kind === 238 /* ClassDeclaration */ + || kind === 155 /* Constructor */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -59595,7 +65937,7 @@ var ts; name: "typescript:assign", scoped: false, priority: 1, - text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" }; function createAssignHelper(context, attributesSegments) { if (context.getCompilerOptions().target >= 2 /* ES2015 */) { @@ -59610,7 +65952,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -59619,7 +65961,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -59636,7 +65978,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -59647,7 +65989,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59655,16 +65997,13 @@ var ts; /*typeArguments*/ undefined, [expression]), location); } })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transform JSX-specific syntax in a SourceFile. * @@ -59689,13 +66028,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -59705,17 +66044,16 @@ var ts; switch (node.kind) { case 10 /* JsxText */: return visitJsxText(node); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -59753,14 +66091,16 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -59785,14 +66125,14 @@ var ts; literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 263 /* JsxExpression */) { + else if (node.kind === 268 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -59879,7 +66219,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 253 /* JsxElement */) { + if (node.kind === 258 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -60168,14 +66508,12 @@ var ts; diams: 0x2666 }); })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60187,7 +66525,7 @@ var ts; return node; } switch (node.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -60237,9 +66575,6 @@ var ts; } ts.transformES2016 = transformES2016; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -60386,7 +66721,7 @@ var ts; * be reset. */ var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60422,14 +66757,14 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ - && node.kind === 223 /* ReturnStatement */ + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 228 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 211 /* Block */))) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } @@ -60457,63 +66792,63 @@ var ts; switch (node.kind) { case 115 /* StaticKeyword */: return undefined; // elide static keyword - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return visitClassExpression(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitParameter(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); case 71 /* Identifier */: return visitIdentifier(node); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 211 /* Block */: + case 216 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); case 13 /* NoSubstitutionTemplateLiteral */: case 14 /* TemplateHead */: @@ -60524,28 +66859,28 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitTemplateExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return visitSpreadElement(node); case 97 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return visitMetaProperty(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -60562,7 +66897,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -60584,7 +66919,7 @@ var ts; return updated; } function returnCapturedThis(node) { - return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); } function visitReturnStatement(node) { if (convertedLoopState) { @@ -60632,13 +66967,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 222 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { - if (node.kind === 222 /* BreakStatement */) { + var label = node.label; + if (!label) { + if (node.kind === 227 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -60649,13 +66985,13 @@ var ts; } } else { - if (node.kind === 222 /* BreakStatement */) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); + if (node.kind === 227 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -60766,12 +67102,12 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -60816,7 +67152,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -60830,7 +67166,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -60874,7 +67210,7 @@ var ts; // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } /** @@ -60910,7 +67246,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -60927,9 +67263,9 @@ var ts; if (isDerivedClass && superCaptureStatus !== 2 /* ReplaceWithReturn */ && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createIdentifier("_this"))); + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -60949,11 +67285,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 223 /* ReturnStatement */) { + if (statement.kind === 228 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 215 /* IfStatement */) { + else if (statement.kind === 220 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -60961,7 +67297,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 211 /* Block */) { + else if (statement.kind === 216 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -61019,7 +67355,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -61029,8 +67365,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 198 /* BinaryExpression */ - || superCallExpression.left.kind !== 185 /* CallExpression */) { + if (superCallExpression.kind !== 202 /* BinaryExpression */ + || superCallExpression.left.kind !== 189 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -61050,7 +67386,7 @@ var ts; return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } function createDefaultSuperCallOrThis() { - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createIdentifier("_super"), ts.createNull()), ts.createFunctionApply(ts.createIdentifier("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); } /** * Visits a parameter declaration. @@ -61145,7 +67481,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } /** @@ -61159,7 +67495,7 @@ var ts; function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ - ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); @@ -61211,7 +67547,7 @@ var ts; var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ - ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), /*location*/ parameter)) @@ -61227,7 +67563,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 191 /* ArrowFunction */) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -61235,7 +67571,7 @@ var ts; enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); @@ -61247,33 +67583,32 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return statements; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 154 /* Constructor */: + case 155 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_newTarget", + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); if (copyOnWrite) { @@ -61294,20 +67629,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 210 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 154 /* Constructor */: + case 155 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -61338,7 +67673,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); ts.setEmitFlags(memberFunction, 1536 /* NoComments */); ts.setSourceMapRange(memberFunction, sourceMapRange); - var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)), + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), /*location*/ member); ts.setOriginalNode(statement, member); ts.setCommentRange(statement, commentRange); @@ -61356,7 +67691,7 @@ var ts; * @param accessors The set of related get/set accessors. */ function transformAccessorsToStatement(receiver, accessors, container) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. @@ -61377,7 +67712,7 @@ var ts; // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); - ts.setSourceMapRange(target, firstAccessor.name); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); @@ -61499,7 +67834,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 232 /* FunctionDeclaration */ || node.kind === 190 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -61520,6 +67855,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; @@ -61527,18 +67863,14 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -61547,7 +67879,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 191 /* ArrowFunction */); + ts.Debug.assert(node.kind === 195 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -61565,6 +67897,7 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom @@ -61572,13 +67905,13 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -61614,10 +67947,10 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 189 /* ParenthesizedExpression */: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 198 /* BinaryExpression */: - return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + case 193 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 202 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); } @@ -61635,9 +67968,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -61679,7 +68012,7 @@ var ts; } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -61710,13 +68043,12 @@ 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.last(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); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -61839,14 +68171,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -61870,11 +68202,12 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -61883,9 +68216,7 @@ var ts; ts.setOriginalNode(declarationList, node.initializer); // Adjust the source map range for the first declaration to align with the old // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -61896,42 +68227,39 @@ var ts; /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), /*type*/ undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); - statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - // The old emitter does not emit source maps for the block. - // We add the location to preserve comments. - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), - /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { // The following ES6 code: @@ -62001,13 +68329,13 @@ var ts; return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -62034,7 +68362,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 146 /* ComputedPropertyName */) { + if (property.name.kind === 147 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -62106,11 +68434,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 231 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -62156,7 +68484,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -62274,7 +68602,7 @@ var ts; function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); } } function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { @@ -62291,7 +68619,7 @@ var ts; ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); + statements.push(ts.createExpressionStatement(callResult)); copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); } else { @@ -62390,20 +68718,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -62510,18 +68838,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155 /* GetAccessor */) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 156 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -62559,7 +68884,7 @@ var ts; function visitArrayLiteralExpression(node) { if (node.transformFlags & 64 /* ES2015 */) { // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -62612,11 +68937,13 @@ var ts; // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - // The class statements are the statements generated by visiting the first statement of the + // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; @@ -62625,6 +68952,7 @@ var ts; // we see as an assignment, for example: // // (function () { + // var C_1; // var C = C_1 = (function () { // function C() { // } @@ -62633,7 +68961,6 @@ var ts; // }()); // C = C_1 = __decorate([dec], C); // return C; - // var C_1; // }()) // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -62656,7 +68983,7 @@ var ts; statements.push(funcStatements[classBodyStart]); classBodyStart++; // Add the class alias following the declaration. - statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { @@ -62733,7 +69060,7 @@ var ts; ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; } return ts.setOriginalNode(resultingCall, node); @@ -62793,7 +69120,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 181 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -62987,14 +69314,14 @@ var ts; */ function addTemplateSpans(expressions, node) { for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { - var span_6 = _a[_i]; - expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); // Only emit if the literal is non-empty. // The binary '+' operator is left-associative, so the first string concatenation // with the head will force the result up to this point to be a string. // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -63004,8 +69331,8 @@ var ts; function visitSuperKeyword(isExpressionOfCall) { return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall - ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") - : ts.createIdentifier("_super"); + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { @@ -63015,7 +69342,7 @@ var ts; else { hierarchyFacts |= 16384 /* NewTarget */; } - return ts.createIdentifier("_newTarget"); + return ts.createFileLevelUniqueName("_newTarget"); } return node; } @@ -63056,13 +69383,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(154 /* Constructor */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(191 /* ArrowFunction */); - context.enableEmitNotification(190 /* FunctionExpression */); - context.enableEmitNotification(232 /* FunctionDeclaration */); + context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(195 /* ArrowFunction */); + context.enableEmitNotification(194 /* FunctionExpression */); + context.enableEmitNotification(237 /* FunctionDeclaration */); } } /** @@ -63102,14 +69429,13 @@ var ts; * @param node An original source tree node. */ function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { - case 180 /* BindingElement */: - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 230 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + switch (node.parent.kind) { + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 235 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -63172,7 +69498,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && hierarchyFacts & 16 /* CapturesThis */) { - return ts.setTextRange(ts.createIdentifier("_this"), node); + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); } return node; } @@ -63189,11 +69515,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 214 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 185 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -63201,7 +69527,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 202 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -63214,7 +69540,7 @@ var ts; return ts.createCall(ts.getHelperName("__extends"), /*typeArguments*/ undefined, [ name, - ts.createIdentifier("_super") + ts.createFileLevelUniqueName("_super") ]); } function createTemplateObjectHelper(context, cooked, raw) { @@ -63229,7 +69555,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -63238,8 +69564,6 @@ var ts; text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" }; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -63256,16 +69580,16 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(255 /* JsxOpeningElement */); - context.enableEmitNotification(256 /* JsxClosingElement */); - context.enableEmitNotification(254 /* JsxSelfClosingElement */); + context.enableEmitNotification(260 /* JsxOpeningElement */); + context.enableEmitNotification(261 /* JsxClosingElement */); + context.enableEmitNotification(259 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(268 /* PropertyAssignment */); - return transformSourceFile; + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(273 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. * @@ -63283,9 +69607,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -63342,7 +69666,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -63350,8 +69674,6 @@ var ts; } ts.transformES5 = transformES5; })(ts || (ts = {})); -/// -/// // Transforms generator functions into a compatible ES5 representation with similar runtime // semantics. This is accomplished by first transforming the body of each generator // function into an intermediate representation that is the compiled into a JavaScript @@ -63529,6 +69851,7 @@ var ts; case 4 /* Yield */: return "yield"; case 5 /* YieldStar */: return "yield*"; case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 } } function transformGenerators(context) { @@ -63579,7 +69902,7 @@ var ts; var exceptionBlockStack; // A stack of containing exception blocks. var currentExceptionBlock; // The current exception block. var withBlockStack; // A stack containing `with` blocks. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; @@ -63618,13 +69941,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -63637,24 +69960,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return visitBreakStatement(node); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return visitContinueStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 16777216 /* ContainsYield */) { @@ -63675,21 +69998,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitConditionalExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -63702,13 +70025,12 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } /** @@ -63837,7 +70159,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -63881,7 +70203,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } /** @@ -63893,13 +70215,14 @@ var ts; * @param node The node to visit. */ function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -63932,7 +70255,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -63944,7 +70267,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -64068,7 +70391,7 @@ var ts; } else { if (containsYield(node) && pendingExpressions.length > 0) { - emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); pendingExpressions = []; } pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); @@ -64221,7 +70544,7 @@ var ts; return ts.inlineExpressions(expressions); function reduceProperty(expressions, property) { if (containsYield(property) && expressions.length > 0) { - emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); expressions = []; } var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); @@ -64320,35 +70643,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 211 /* Block */: + case 216 /* Block */: return transformAndEmitBlock(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return transformAndEmitIfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return transformAndEmitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return transformAndEmitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return transformAndEmitWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -64385,7 +70708,7 @@ var ts; pendingExpressions.push(transformInitializedVariable(variable)); } if (pendingExpressions.length) { - emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); variablesWritten += pendingExpressions.length; pendingExpressions = []; } @@ -64536,7 +70859,7 @@ var ts; transformAndEmitVariableDeclarationList(initializer); } else { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); } } markLabel(conditionLabel); @@ -64546,7 +70869,7 @@ var ts; transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); if (node.incrementor) { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); } emitBreak(conditionLabel); endLoopBlock(); @@ -64607,7 +70930,7 @@ var ts; var initializer = node.initializer; hoistVariableDeclaration(keysIndex); emitAssignment(keysArray, ts.createArrayLiteral()); - emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, ts.createLiteral(0)); var conditionLabel = defineLabel(); @@ -64630,7 +70953,7 @@ var ts; emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); - emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); emitBreak(conditionLabel); endLoopBlock(); } @@ -64778,7 +71101,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 265 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -64791,7 +71114,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 264 /* CaseClause */) { + if (clause.kind === 269 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -64907,7 +71230,7 @@ var ts; beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { - beginCatchBlock(node.catchClause.variableDeclaration); + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 transformAndEmitEmbeddedStatement(node.catchClause.block); } if (node.finallyBlock) { @@ -64921,7 +71244,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -65022,7 +71345,8 @@ var ts; */ function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -65355,7 +71679,7 @@ var ts; * @param label A label. */ function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -65653,7 +71977,7 @@ var ts; // indicate entry into a protected region by pushing the label numbers // for each block in the protected region. var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; - statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), /*typeArguments*/ undefined, [ ts.createArrayLiteral([ createLabel(startLabel), @@ -65667,7 +71991,7 @@ var ts; if (markLabelEnd) { // The case clause for the last label falls through to this label, so we // add an assignment statement to reflect the change in labels. - statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); } } clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); @@ -65825,7 +72149,7 @@ var ts; * @param operationLocation The source map location for the operation. */ function writeAssign(left, right, operationLocation) { - writeStatement(ts.setTextRange(ts.createStatement(ts.createAssignment(left, right)), operationLocation)); + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); } /** * Writes a Throw operation to the current label's statement list. @@ -65994,12 +72318,9 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -66022,18 +72343,18 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(198 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(196 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(197 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(272 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -66076,7 +72397,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -66119,7 +72440,7 @@ var ts; // // define(moduleName?, ["module1", "module2"], function ... var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(define, + ts.createExpressionStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: // @@ -66170,9 +72491,9 @@ var ts; ts.createIdentifier("exports") ])) ]), - ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -66196,7 +72517,7 @@ var ts; // } // })(function ...) var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(umdHeader, + ts.createExpressionStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: // @@ -66270,12 +72591,12 @@ var ts; if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { return undefined; } - var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 var expr = getHelperExpressionForImport(node, name); if (expr === name) { return undefined; } - return ts.createStatement(ts.createAssignment(name, expr)); + return ts.createExpressionStatement(ts.createAssignment(name, expr)); } /** * Transforms a SourceFile into an AMD or UMD module body. @@ -66299,7 +72620,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -66321,7 +72642,7 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -66330,7 +72651,7 @@ var ts; statements.push(statement); } else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); ts.setTextRange(statement, currentModuleInfo.exportEquals); ts.setEmitFlags(statement, 1536 /* NoComments */); statements.push(statement); @@ -66348,43 +72669,98 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 307 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 308 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - // This visitor does not need to descend into the tree if there is no dynamic import, + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 273 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 274 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 275 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -66440,7 +72816,7 @@ var ts; ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("require"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) ]); var func; @@ -66535,7 +72911,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createStatement(createRequireCall(node)), node); + return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); } else { var variables = []; @@ -66603,7 +72979,7 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); } else { statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( @@ -66616,7 +72992,7 @@ var ts; } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -66655,13 +73031,13 @@ var ts; for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } /** @@ -66678,10 +73054,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -66695,13 +73071,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), - /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66723,10 +73099,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66767,11 +73143,11 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66783,6 +73159,21 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } /** * Transforms an exported variable with an initializer into an expression. * @@ -66790,13 +73181,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), /*visitor*/ undefined, context, 0 /* All */, - /*needsValue*/ false, createExportExpression); + /*needsValue*/ false, createAllExportExpressions); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } /** @@ -66813,7 +73204,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 212 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -66868,10 +73259,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 245 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -67001,10 +73392,10 @@ var ts; function createUnderscoreUnderscoreESModule() { var statement; if (languageVersion === 0 /* ES3 */) { - statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); } else { - statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ ts.createIdentifier("exports"), ts.createLiteral("__esModule"), @@ -67025,7 +73416,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, location, allowComments) { - var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -67070,7 +73461,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -67134,10 +73525,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 197 /* PostfixUnaryExpression */: - case 196 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -67158,7 +73549,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 272 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -67200,8 +73591,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, /*location*/ node); @@ -67233,12 +73624,12 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 197 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); @@ -67269,7 +73660,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -67296,9 +73687,6 @@ var ts; text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -67312,11 +73700,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(198 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(196 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(197 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(272 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -67328,7 +73716,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; // Set of nodes for which substitution rules should be ignored. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -67378,7 +73766,7 @@ var ts; var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) @@ -67501,8 +73889,8 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addRange(statements, endLexicalEnvironment()); - var exportStarFunction = addExportStarIfNeeded(statements); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), ts.createPropertyAssignment("execute", ts.createFunctionExpression( @@ -67537,7 +73925,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 248 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -67562,7 +73950,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 248 /* ExportDeclaration */) { + if (externalImport.kind !== 253 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -67616,9 +74004,9 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) ])), - ts.createStatement(ts.createCall(exportFunction, + ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exports])) ], /*multiline*/ true)); } @@ -67631,28 +74019,28 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; + var group_1 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -67668,7 +74056,7 @@ var ts; var e = _d[_c]; properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } - statements.push(ts.createStatement(ts.createCall(exportFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); } else { @@ -67677,7 +74065,7 @@ var ts; // emit as: // // exportStar(foo_1_1); - statements.push(ts.createStatement(ts.createCall(exportStarFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, /*typeArguments*/ undefined, [parameterName]))); } break; @@ -67702,15 +74090,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -67724,7 +74112,7 @@ var ts; function visitImportDeclaration(node) { var statements; if (node.importClause) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -67744,7 +74132,7 @@ var ts; function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -67811,7 +74199,7 @@ var ts; var name = ts.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -67848,7 +74236,7 @@ var ts; } var statements; if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); } if (isMarkedDeclaration) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -67886,7 +74274,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 272 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -67950,7 +74338,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 212 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -67981,6 +74369,12 @@ var ts; delete deferredExports[id]; return ts.append(statements, node); } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } return node; } /** @@ -68006,10 +74400,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 245 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -68161,7 +74555,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, allowComments) { - var statement = ts.createStatement(createExportExpression(name, value)); + var statement = ts.createExpressionStatement(createExportExpression(name, value)); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -68189,43 +74583,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return visitWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 264 /* CaseClause */: + case 269 /* CaseClause */: return visitCaseClause(node); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return visitDefaultClause(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return visitTryStatement(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 211 /* Block */: + case 216 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 307 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 308 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -68239,7 +74633,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -68283,9 +74677,6 @@ var ts; * @param node The node to visit. */ function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -68411,7 +74802,7 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 198 /* BinaryExpression */) { + && node.kind === 202 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -68476,7 +74867,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 272 /* SourceFile */; + return container !== undefined && container.kind === 277 /* SourceFile */; } else { return false; @@ -68509,7 +74900,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -68557,7 +74948,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -68593,10 +74984,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -68658,8 +75049,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -68689,14 +75080,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 197 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 197 /* PostfixUnaryExpression */) { + if (node.kind === 201 /* PostfixUnaryExpression */) { expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -68718,7 +75109,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 272 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -68748,8 +75139,6 @@ var ts; } ts.transformSystemModule = transformSystemModule; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -68759,10 +75148,10 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(272 /* SourceFile */); + context.enableEmitNotification(277 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -68788,10 +75177,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -68848,19 +75237,1496 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || + (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 157 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 159 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 158 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 237 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 155 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 159 /* ConstructSignature */: + case 164 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 158 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 237 /* FunctionDeclaration */: + case 163 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 239 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 159 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 158 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 237 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 240 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + }; + var errorNameNode; + var currentSourceFile; + var refs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function transformRoot(node) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 278 /* Bundle */) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeRefernces = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71 /* Identifier */) { + return name; + } + else { + if (name.kind === 183 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 208 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 149 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (node.kind === 157 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 149 /* Parameter */ + || node.kind === 152 /* PropertyDeclaration */ + || node.kind === 151 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 235 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 209 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 162 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 159 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 155 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 154 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 156 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 157 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 152 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 151 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 158 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 160 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + } + case 235 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 148 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 173 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 163 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 164 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 181 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 253 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 252 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 71 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 246 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 247 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 239 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 237 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + return cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + } + case 242 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 243 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 238 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 217 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 241 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 242 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 208 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 277 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_10 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_10(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 239 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 156 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 149 /* Parameter */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 217 /* VariableStatement */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 159 /* ConstructSignature */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 160 /* IndexSignature */: + case 235 /* VariableDeclaration */: + case 148 /* TypeParameter */: + case 209 /* ExpressionWithTypeArguments */: + case 162 /* TypeReference */: + case 173 /* ConditionalType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 181 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -68931,7 +76797,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(309 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -68942,6 +76808,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0 /* Uninitialized */; + var diagnostics = []; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { @@ -68971,6 +76838,9 @@ var ts; ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; // Ensure the parse tree is clean before applying transformations @@ -68993,7 +76863,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -69184,20 +77055,19 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, + emittedLine: 0, + emittedColumn: 0, + sourceLine: 0, + sourceColumn: 0, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -69210,11 +77080,11 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -69235,13 +77105,14 @@ var ts; * @param sourceMapFilePath The path to the output source map file. * @param sourceFileOrBundle The input source file or bundle for the program. */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { - if (disabled) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { + if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list @@ -69261,7 +77132,6 @@ var ts; sourceMapNames: [], sourceMapMappings: "", sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - sourceMapDecodedMappings: [] }; // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the // relative paths of the sources list in the sourcemap @@ -69271,10 +77141,10 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file + if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -69299,6 +77169,10 @@ var ts; if (disabled) { return; } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -69306,12 +77180,28 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; + } + function captureSection() { + return { + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent, + }; } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { return; } + ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { @@ -69325,7 +77215,7 @@ var ts; for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { sourceMapData.sourceMapMappings += ";"; } - prevEncodedEmittedColumn = 1; + prevEncodedEmittedColumn = 0; } // 1. Relative Column 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); @@ -69342,7 +77232,6 @@ var ts; lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } /** * Emits a mapping. @@ -69353,16 +77242,13 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; var emittedLine = writer.getLine(); var emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span @@ -69394,6 +77280,9 @@ var ts; ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } + function isPossiblySourceMap(x) { + return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; + } /** * Emits a node with possible leading and trailing source maps. * @@ -69402,21 +77291,66 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + var _a; + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var text = node.sourceMapText; + var parsed = void 0; + try { + parsed = JSON.parse(text); + } + catch (_b) { + // empty + } + if (!parsed || !isPossiblySourceMap(parsed)) { + return emitCallback(hint, node); + } + var offsetLine = writer.getLine(); + var firstLineColumnOffset = writer.getColumn(); + // First, decode the old component sourcemap + var originalMap = parsed; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var resolvedPathCache = ts.createMap(); + var absolutePathCache = ts.createMap(); + var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); + for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { + var pathCacheKey = "" + raw.sourceIndex; + // Apply offsets to each position and fixup source entries + if (!resolvedPathCache.has(pathCacheKey)) { + var rawPath = originalMap.sources[raw.sourceIndex]; + var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); + var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + resolvedPathCache.set(pathCacheKey, resolvedPath_1); + absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); + } + var resolvedPath = resolvedPathCache.get(pathCacheKey); + var absolutePath = absolutePathCache.get(pathCacheKey); + // tslint:disable-next-line:no-null-keyword + setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? + var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); + // Then reencode all the updated spans into the overall map + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); + } + // And actually emit the text these sourcemaps are for + return emitCallback(hint, node); + } var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; - var _a = range || node, pos = _a.pos, end = _a.end; + var _d = range || node, pos = _d.pos, end = _d.end; var source = range && range.source; var oldSource = currentSource; if (source === oldSource) source = undefined; if (source) setSourceFile(source); - if (node.kind !== 294 /* NotEmittedStatement */ + if (node.kind !== 304 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -69433,7 +77367,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 294 /* NotEmittedStatement */ + if (node.kind !== 304 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -69451,11 +77385,11 @@ var ts; * @param emitCallback The callback used to emit the token. */ function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { @@ -69469,6 +77403,9 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } /** * Set the current source file. * @@ -69480,20 +77417,28 @@ var ts; } currentSource = sourceFile; currentSourceText = currentSource.text; - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); + if (isJsonSourceMapSource(sourceFile)) { + return; + } + setupSourceEntry(sourceFile.fileName, sourceFile.text); + } + function setupSourceEntry(fileName, content, source) { + if (!source) { + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(currentSource.fileName); + sourceMapData.inputSourceFileNames.push(fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSource.text); + sourceMapData.sourceMapSourcesContent.push(content); } } } @@ -69501,30 +77446,22 @@ var ts; * Gets the text for the source map. */ function getText() { - if (disabled) { - return; + if (disabled || isJsonSourceMapSource(currentSource)) { + return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); - return JSON.stringify({ - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }); + return JSON.stringify(captureSection()); } /** * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { - if (disabled) { - return; + if (disabled || isJsonSourceMapSource(currentSource)) { + return undefined; // TODO: GH#18217 } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -69566,7 +77503,6 @@ var ts; return encodedStr; } })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -69582,7 +77518,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -69600,7 +77536,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. @@ -69610,7 +77546,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 294 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -69631,7 +77567,7 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 231 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -69778,7 +77714,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -69806,6 +77750,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -69878,11 +77824,11 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { // get the leading comments from detachedPos - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -69903,6 +77849,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -69920,1840 +77868,9 @@ var ts; } ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var needsDeclare = true; - var moduleElementDeclarationEmitInfo = []; - var asynchronousSubModuleDeclarationEmitInfo; - // Contains the reference paths that needs to go in the declaration file. - // Collecting this separately because reference paths need to be first thing in the declaration file - // and we could be collecting these paths from multiple files into single one with --out option - var referencesOutput = ""; - var usedTypeDirectiveReferences; - // Emit references corresponding to each file - var emittedReferencedFiles = []; - var addedGlobalFileReference = false; - var allSourcesModuleElementDeclarationEmitInfo = []; - ts.forEach(sourceFiles, function (sourceFile) { - // Dont emit for javascript file - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // Emit reference in dts, if the file reference was not already emitted - if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - // Add a reference to generated dts file, - // global file reference is added only - // - if it is not bundled emit (because otherwise it would be self reference) - // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { - addedGlobalFileReference = true; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - } - // create asynchronous output for the importDeclarations - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 242 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { - // if file was external module this fact should be preserved in .d.ts as well. - // in case if we didn't write any external module specifiers in .d.ts we need to emit something - // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. - write("export {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - var writer = ts.createTextWriter(newLine); - writer.trackSymbol = trackSymbol; - writer.reportInaccessibleThisError = reportInaccessibleThisError; - writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; - writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; - writer.writeKeyword = writer.write; - writer.writeOperator = writer.write; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230 /* VariableDeclaration */) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 /* NamedImports */ || declaration.kind === 246 /* ImportSpecifier */ || declaration.kind === 243 /* ImportClause */) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { - moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - } - // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration - // then we don't need to write it at this point. We will write it when we actually see its declaration - // Eg. - // export function bar(a: foo.Foo) { } - // import foo = require("foo"); - // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, - // we would write alias foo declaration when we visit it since it would now be marked as visible - if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 242 /* ImportDeclaration */) { - // we have to create asynchronous output only after we have collected complete information - // because it is possible to enable multiple bindings as asynchronously visible - moduleElementEmitInfo.isVisible = true; - } - else { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { - var directive = typeReferenceDirectives_2[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { - // write the aliases - if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); - } - } - else { - // Report error - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); - } - } - function reportInaccessibleUniqueSymbolError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); - } - } - function reportInaccessibleThisError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - // use the checker's type, not the declared type, - // for optional parameter properties - // and also for non-optional initialized parameters that aren't a parameter property - // these types may need to add `undefined`. - var shouldUseResolverType = declaration.kind === 148 /* Parameter */ && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | - 2048 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 135 /* ObjectKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 173 /* ThisType */: - case 177 /* LiteralType */: - return writeTextOfNode(currentText, type); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(type); - case 161 /* TypeReference */: - return emitTypeReference(type); - case 164 /* TypeQuery */: - return emitTypeQuery(type); - case 166 /* ArrayType */: - return emitArrayType(type); - case 167 /* TupleType */: - return emitTupleType(type); - case 168 /* UnionType */: - return emitUnionType(type); - case 169 /* IntersectionType */: - return emitIntersectionType(type); - case 170 /* ConditionalType */: - return emitConditionalType(type); - case 171 /* InferType */: - return emitInferType(type); - case 172 /* ParenthesizedType */: - return emitParenType(type); - case 174 /* TypeOperator */: - return emitTypeOperator(type); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(type); - case 176 /* MappedType */: - return emitMappedType(type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 165 /* TypeLiteral */: - return emitTypeLiteral(type); - case 71 /* Identifier */: - return emitEntityName(type); - case 145 /* QualifiedName */: - return emitEntityName(type); - case 160 /* TypePredicate */: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71 /* Identifier */) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 145 /* QualifiedName */ ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 241 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeEntityName(entityName); - } - function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 183 /* PropertyAccessExpression */); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 /* PlusToken */ ? "+readonly " : - node.readonlyToken.kind === 38 /* MinusToken */ ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 /* PlusToken */ ? "+?" : - node.questionToken.kind === 38 /* MinusToken */ ? "-?" : - "?"); - } - write(": "); - if (node.type) { - emitType(node.type); - } - else { - write("any"); - } - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComments*/ true); - emitLines(node.statements); - } - // Return a temp variable name to be used in `export default`/`export class ... extends` statements. - // The temp name will be of the form _default_counter. - // Note that export default is only allowed at most once in a module, so we - // do not need to keep track of created temp names. - function getExportTempVariableName(baseName) { - if (!currentIdentifiers.has(baseName)) { - return baseName; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === 71 /* Identifier */) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - // Make all the declarations visible for the export name - if (node.expression.kind === 71 /* Identifier */) { - var nodes = resolver.collectLinkedAliases(node.expression); - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective - else if (node.kind === 241 /* ImportEqualsDeclaration */ || - (node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272 /* SourceFile */) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242 /* ImportDeclaration */) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - return writeFunctionDeclaration(node); - case 212 /* VariableStatement */: - return writeVariableStatement(node); - case 234 /* InterfaceDeclaration */: - return writeInterfaceDeclaration(node); - case 233 /* ClassDeclaration */: - return writeClassDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return writeTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return writeEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return writeModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return writeImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - function emitModuleElementDeclarationFlags(node) { - // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 272 /* SourceFile */) { - var modifiers = ts.getModifierFlags(node); - // If the node is exported - if (modifiers & 1 /* Export */) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - if (modifiers & 512 /* Default */) { - write("default "); - } - else if (node.kind !== 234 /* InterfaceDeclaration */ && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8 /* Private */) { - write("private "); - } - else if (flags & 16 /* Protected */) { - write("protected "); - } - if (flags & 32 /* Static */) { - write("static "); - } - if (flags & 64 /* Readonly */) { - write("readonly "); - } - if (flags & 128 /* Abstract */) { - write("abstract "); - } - } - function writeImportEqualsDeclaration(node) { - // note usage of writer. methods instead of aliases created, just to make sure we are using - // correct writer especially to handle asynchronous alias writing - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { - if (currentWriterPos !== writer.getTextPos()) { - // If the default binding was emitted, write the separated - write(", "); - } - if (node.importClause.namedBindings.kind === 244 /* NamespaceImport */) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). - // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered - // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' - // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237 /* ModuleDeclaration */; - var moduleSpecifier = parent.kind === 241 /* ImportEqualsDeclaration */ ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 /* ModuleDeclaration */ ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - function emitExportSpecifier(node) { - emitImportOrExportSpecifier(node); - // Make all the declarations visible for the export name - var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - function emitExportDeclaration(node) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16 /* Namespace */) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentText, node.name); - // If there is constraint present and this is not a type parameter of the private method emit the constraint - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError() { - // Type parameter constraints are named by user so we should always be able to name it - var diagnosticMessage; - switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 232 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235 /* TypeAliasDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - // Class or Interface implemented/extended is inaccessible - diagnosticMessage = isImplementsList ? - ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : - ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; - } - else { - // interface is inaccessible - diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? - "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { - diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, - errorNode: baseTypeNode, - typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 237 /* ModuleDeclaration */; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128 /* Abstract */)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - write(";"); - writeLine(); - } - function bindingNameContainsVisibleBindingElement(node) { - return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); - } - function isVariableDeclarationVisible(node) { - return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); - } - function emitVariableDeclaration(node) { - // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted - // so there is no check needed to see if declaration is visible - if (node.kind !== 230 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); - // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor - // we don't want to emit property declaration with "?" - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */) && node.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230 /* VariableDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } - // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { - // TODO(jfreeman): Deal with computed properties in error reporting. - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */ || node.kind === 148 /* Parameter */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function emitBindingPattern(bindingPattern) { - // Only select visible, non-omitted expression from the bindingPattern's elements. - // We have to do this to avoid emitting trailing commas. - // For example: - // original: var [, c,,] = [ 2,3,4] - // emitted: declare var c: number; // instead of declare var c:number, ; - var elements = []; - for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 204 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); - } - } - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - // if this is property of type literal, - // or is parameter of method/call/construct/index signature of type literal - // emit only if type is specified - if (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(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)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); - writeNameOfDeclaration(node, getAccessorNameVisibilityError); - if (!ts.hasModifier(node, 8 /* Private */)) { - accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 155 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 /* GetAccessor */ - ? accessor.type // Getter - return type - : accessor.parameters.length > 0 - ? accessor.parameters[0].type // Setter parameter type - : undefined; - } - } - function getAccessorNameVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 156 /* SetAccessor */) { - // Getters can infer the return type from the returned expression, but setters cannot, so the - // "_from_external_module_1_but_cannot_be_named" case cannot occur. - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting - // so no need to verify if the declaration is visible - if (!resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 232 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 /* MethodDeclaration */ || node.kind === 154 /* Constructor */) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154 /* Constructor */) { - write("constructor"); - } - else { - writeNameOfDeclaration(node, getMethodNameVisibilityError); - if (ts.hasQuestionToken(node)) { - write("?"); - } - } - emitSignatureDeclaration(node); - } - function getMethodNameVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { - if (ts.hasDynamicName(node)) { - // If this node has a dynamic name, it can only be an identifier or property access because - // we've already skipped it otherwise. - ts.Debug.assert(resolver.isLateBound(node)); - writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); - } - else { - // If this node is a computed name, it can only be a symbol, because we've already skipped - // it if it's not a well known symbol. In that case, the text of the name will be exactly - // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentText, node.name); - } - } - function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - var entityName = node.name.expression; - var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeTextOfNode(currentText, node.name); - } - function emitSignatureDeclarationWithJsDocComments(node) { - emitJsDocComments(node); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159 /* IndexSignature */) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === 158 /* ConstructSignature */ || node.kind === 163 /* ConstructorType */) { - write("new "); - } - else if (node.kind === 162 /* FunctionType */) { - var currentOutput = writer.getText(); - // Do not generate incorrect type when function type with type parameters is type argument - // This could happen if user used space between two '<' making it error free - // e.g var x: A< (a: Tany)=>Tany>; - if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { - closeParenthesizedFunctionType = true; - write("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 162 /* FunctionType */ || node.kind === 163 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165 /* TypeLiteral */) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158 /* ConstructSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 157 /* CallSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 159 /* IndexSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; - } - else { - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; - } - break; - case 232 /* FunctionDeclaration */: - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - // For bindingPattern, we can't simply writeTextOfNode from the source file - // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. - // Therefore, we will have to recursively emit each element in the bindingPattern. - emitBindingPattern(node.name); - } - else { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154 /* Constructor */: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 158 /* ConstructSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157 /* CallSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 159 /* IndexSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - case 232 /* FunctionDeclaration */: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 178 /* ObjectBindingPattern */) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179 /* ArrayBindingPattern */) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204 /* OmittedExpression */) { - // If bindingElement is an omittedExpression (i.e. containing elision), - // we will emit blank space (although this may differ from users' original code, - // it allows emitSeparatedList to write separator appropriately) - // Example: - // original: function foo([, x, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === 180 /* BindingElement */) { - if (bindingElement.propertyName) { - // bindingElement has propertyName property in the following case: - // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" - // We have to explicitly emit the propertyName before descending into its binding elements. - // Example: - // original: function foo({y: [a,b,c]}) {} - // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentText, bindingElement.propertyName); - write(": "); - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - // If it is a nested binding pattern, we will recursively descend into each element and emit each one separately. - // In the case of rest element, we will omit rest element. - // Example: - // original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {} - // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; - // original with rest: function foo([a, ...c]) {} - // emit : declare function foo([a, ...c]): void; - emitBindingPattern(bindingElement.name); - } - else { - ts.Debug.assert(bindingElement.name.kind === 71 /* Identifier */); - // If the node is just an identifier, we will simply emit the text associated with the node's name - // Example: - // original: function foo({y = 10, x}) {} - // emit : declare function foo({y, x}: {number, any}): void; - if (bindingElement.dotDotDotToken) { - write("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212 /* VariableStatement */: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242 /* ImportDeclaration */: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return writeFunctionDeclaration(node); - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 271 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 272 /* SourceFile */: - return emitSourceFile(node); - } - } - /** - * Adds the reference to referenced file, returns true if global file reference was emitted - * @param referencedFile - * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not - */ - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { - var declFileName; - var addedBundledEmitReference = false; - if (referencedFile.isDeclarationFile) { - // Declaration file, use declaration file name - declFileName = referencedFile.fileName; - } - else { - // Get the declaration file path - ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); - } - if (declFileName) { - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencesOutput += "/// " + newLine; - } - return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFileOrBundle) { - // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); - var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { - var appliedSyncOutputPos = 0; - var declarationOutput = ""; - // apply asynchronous additions to the synchronous output - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); -/// -/// -/// -/// -/// var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); /*@internal*/ /** @@ -71766,14 +77883,13 @@ var ts; * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -71782,10 +77898,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -71793,13 +77906,45 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 278 /* Bundle */) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { @@ -71813,71 +77958,39 @@ var ts; } return ".js" /* Js */; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273 /* Bundle */) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); - } - return ts.getOriginalSourceFile(sourceFileOrBundle); - } + ts.getOutputExtension = getOutputExtension; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); - var moduleKind = ts.getEmitModuleKind(compilerOptions); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); - var currentSourceFile; - var bundledHelpers; - var isOwnFileEmit; - var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - // Transform the source files - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); - // Create a printer to print the nodes - var printer = createPrinter(compilerOptions, { - // resolver hooks - hasGlobalName: resolver.hasGlobalName, - // transform hooks - onEmitNode: transform.emitNodeWithNotification, - substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onEmitHelpers: emitHelpers, - onSetSourceFile: setSourceFile, + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; // Emit each output file ts.performance.mark("beforePrint"); - forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -71888,96 +78001,145 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 272 /* SourceFile */ ? sourceFileOrBundle : undefined; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + // Create a printer to print the nodes + var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + // sourcemap hooks + onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: sourceMap.emitPos, + // emitter hooks + onSetSourceFile: setSourceFile, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // sourcemap hooks + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 71 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { + var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - bundledHelpers = ts.createMap(); - isOwnFileEmit = false; - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { - isOwnFileEmit = true; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (sourceMappingURL) { writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment } // Write the source map - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } // Reset state - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); - currentSourceFile = undefined; - bundledHelpers = undefined; - isOwnFileEmit = false; + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { - currentSourceFile = node; sourceMap.setSourceFile(node); } - function emitHelpers(node, writeLines) { - var helpersEmitted = false; - var bundle = node.kind === 273 /* Bundle */ ? node : undefined; - if (bundle && moduleKind === ts.ModuleKind.None) { - return; - } - var numNodes = bundle ? bundle.sourceFiles.length : 1; - for (var i = 0; i < numNodes; i++) { - var currentNode = bundle ? bundle.sourceFiles[i] : node; - var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; - var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; - var helpers = ts.getEmitHelpers(currentNode); - if (helpers) { - for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { - var helper = _b[_a]; - if (!helper.scoped) { - // Skip the helper if it can be skipped and the noEmitHelpers compiler - // option is set, or if it can be imported and the importHelpers compiler - // option is set. - if (shouldSkip) - continue; - // Skip the helper if it can be bundled but hasn't already been emitted and we - // are emitting a bundled module. - if (shouldBundle) { - if (bundledHelpers.get(helper.name)) { - continue; - } - bundledHelpers.set(helper.name, true); - } - } - else if (bundle) { - // Skip the helper if it is scoped and we are emitting bundled helpers - continue; - } - writeLines(helper.text); - helpersEmitted = true; - } - } - } - return helpersEmitted; + function setSourceFileForDeclarationSourceMaps(node) { + declarationSourceMap.setSourceFile(node); } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -72000,6 +78162,9 @@ var ts; writeSemicolon = deferWriteSemicolon; } var syntheticParent = { pos: -1, end: -1 }; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var isOwnFileEmit; reset(); return { // public API @@ -72026,8 +78191,9 @@ var ts; break; } switch (node.kind) { - case 272 /* SourceFile */: return printFile(node); - case 273 /* Bundle */: return printBundle(node); + case 277 /* SourceFile */: return printFile(node); + case 278 /* Bundle */: return printBundle(node); + case 279 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -72044,6 +78210,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -72061,20 +78231,38 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { + isOwnFileEmit = false; var previousWriter = writer; setWriter(output); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); - emitHelpersIndirect(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { + isOwnFileEmit = true; var previousWriter = writer; setWriter(output); emitShebangIfNeeded(sourceFile); @@ -72095,7 +78283,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -72105,7 +78294,7 @@ var ts; } } function setWriter(output) { - writer = output; + writer = output; // TODO: GH#18217 comments.setWriter(output); } function reset() { @@ -72118,63 +78307,416 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } - // TODO: Should this just be `emit`? - // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4 /* Unspecified */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2 /* IdentifierName */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1 /* Expression */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Comments */: + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2 /* SourceMaps */: + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + return pipelineEmitWithSourceMap; + } + // falls through + case 3 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0 /* SourceFile */); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assert(hint !== 0 /* SourceFile */); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0 /* SourceFile */: return pipelineEmitSourceFile(node); - case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); - case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4 /* Unspecified */: return pipelineEmitUnspecified(node); + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + return emitLiteral(node); + case 279 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 146 /* QualifiedName */: + return emitQualifiedName(node); + case 147 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 148 /* TypeParameter */: + return emitTypeParameter(node); + case 149 /* Parameter */: + return emitParameter(node); + case 150 /* Decorator */: + return emitDecorator(node); + // Type members + case 151 /* PropertySignature */: + return emitPropertySignature(node); + case 152 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 153 /* MethodSignature */: + return emitMethodSignature(node); + case 154 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 155 /* Constructor */: + return emitConstructor(node); + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 158 /* CallSignature */: + return emitCallSignature(node); + case 159 /* ConstructSignature */: + return emitConstructSignature(node); + case 160 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 161 /* TypePredicate */: + return emitTypePredicate(node); + case 162 /* TypeReference */: + return emitTypeReference(node); + case 163 /* FunctionType */: + return emitFunctionType(node); + case 287 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 164 /* ConstructorType */: + return emitConstructorType(node); + case 165 /* TypeQuery */: + return emitTypeQuery(node); + case 166 /* TypeLiteral */: + return emitTypeLiteral(node); + case 167 /* ArrayType */: + return emitArrayType(node); + case 168 /* TupleType */: + return emitTupleType(node); + case 169 /* OptionalType */: + return emitOptionalType(node); + case 171 /* UnionType */: + return emitUnionType(node); + case 172 /* IntersectionType */: + return emitIntersectionType(node); + case 173 /* ConditionalType */: + return emitConditionalType(node); + case 174 /* InferType */: + return emitInferType(node); + case 175 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 209 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 176 /* ThisType */: + return emitThisType(); + case 177 /* TypeOperator */: + return emitTypeOperator(node); + case 178 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 179 /* MappedType */: + return emitMappedType(node); + case 180 /* LiteralType */: + return emitLiteralType(node); + case 181 /* ImportType */: + return emitImportTypeNode(node); + case 282 /* JSDocAllType */: + write("*"); + return; + case 283 /* JSDocUnknownType */: + write("?"); + return; + case 284 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 285 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 286 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 170 /* RestType */: + case 288 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 182 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 183 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 184 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 214 /* TemplateSpan */: + return emitTemplateSpan(node); + case 215 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 216 /* Block */: + return emitBlock(node); + case 217 /* VariableStatement */: + return emitVariableStatement(node); + case 218 /* EmptyStatement */: + return emitEmptyStatement(); + case 219 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 220 /* IfStatement */: + return emitIfStatement(node); + case 221 /* DoStatement */: + return emitDoStatement(node); + case 222 /* WhileStatement */: + return emitWhileStatement(node); + case 223 /* ForStatement */: + return emitForStatement(node); + case 224 /* ForInStatement */: + return emitForInStatement(node); + case 225 /* ForOfStatement */: + return emitForOfStatement(node); + case 226 /* ContinueStatement */: + return emitContinueStatement(node); + case 227 /* BreakStatement */: + return emitBreakStatement(node); + case 228 /* ReturnStatement */: + return emitReturnStatement(node); + case 229 /* WithStatement */: + return emitWithStatement(node); + case 230 /* SwitchStatement */: + return emitSwitchStatement(node); + case 231 /* LabeledStatement */: + return emitLabeledStatement(node); + case 232 /* ThrowStatement */: + return emitThrowStatement(node); + case 233 /* TryStatement */: + return emitTryStatement(node); + case 234 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 235 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 236 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 237 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 238 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 239 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 240 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 241 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 242 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 243 /* ModuleBlock */: + return emitModuleBlock(node); + case 244 /* CaseBlock */: + return emitCaseBlock(node); + case 245 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 246 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 247 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 248 /* ImportClause */: + return emitImportClause(node); + case 249 /* NamespaceImport */: + return emitNamespaceImport(node); + case 250 /* NamedImports */: + return emitNamedImports(node); + case 251 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 252 /* ExportAssignment */: + return emitExportAssignment(node); + case 253 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 254 /* NamedExports */: + return emitNamedExports(node); + case 255 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 256 /* MissingDeclaration */: + return; + // Module references + case 257 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 10 /* JsxText */: + return emitJsxText(node); + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 261 /* JsxClosingElement */: + case 264 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 265 /* JsxAttribute */: + return emitJsxAttribute(node); + case 266 /* JsxAttributes */: + return emitJsxAttributes(node); + case 267 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 268 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 269 /* CaseClause */: + return emitCaseClause(node); + case 270 /* DefaultClause */: + return emitDefaultClause(node); + case 271 /* HeritageClause */: + return emitHeritageClause(node); + case 272 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 273 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 274 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 275 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 276 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + node = trySubstituteNode(1 /* Expression */, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 185 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 186 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 187 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 188 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 189 /* CallExpression */: + return emitCallExpression(node); + case 190 /* NewExpression */: + return emitNewExpression(node); + case 191 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 192 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 193 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 194 /* FunctionExpression */: + return emitFunctionExpression(node); + case 195 /* ArrowFunction */: + return emitArrowFunction(node); + case 196 /* DeleteExpression */: + return emitDeleteExpression(node); + case 197 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 198 /* VoidExpression */: + return emitVoidExpression(node); + case 199 /* AwaitExpression */: + return emitAwaitExpression(node); + case 200 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 201 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 202 /* BinaryExpression */: + return emitBinaryExpression(node); + case 203 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 204 /* TemplateExpression */: + return emitTemplateExpression(node); + case 205 /* YieldExpression */: + return emitYieldExpression(node); + case 206 /* SpreadElement */: + return emitSpreadExpression(node); + case 207 /* ClassExpression */: + return emitClassExpression(node); + case 208 /* OmittedExpression */: + return; + case 210 /* AsExpression */: + return emitAsExpression(node); + case 211 /* NonNullExpression */: + return emitNonNullExpression(node); + case 212 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 258 /* JsxElement */: + return emitJsxElement(node); + case 259 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 262 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 305 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 306 /* CommaListExpression */: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); @@ -72183,358 +78725,55 @@ var ts; writeSpace(); emit(node.constraint); } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - // Reserved words - // Strict mode reserved words - // Contextual keywords - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Parse tree nodes - // Names - case 145 /* QualifiedName */: - return emitQualifiedName(node); - case 146 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 147 /* TypeParameter */: - return emitTypeParameter(node); - case 148 /* Parameter */: - return emitParameter(node); - case 149 /* Decorator */: - return emitDecorator(node); - // Type members - case 150 /* PropertySignature */: - return emitPropertySignature(node); - case 151 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 152 /* MethodSignature */: - return emitMethodSignature(node); - case 153 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 154 /* Constructor */: - return emitConstructor(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 157 /* CallSignature */: - return emitCallSignature(node); - case 158 /* ConstructSignature */: - return emitConstructSignature(node); - case 159 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 160 /* TypePredicate */: - return emitTypePredicate(node); - case 161 /* TypeReference */: - return emitTypeReference(node); - case 162 /* FunctionType */: - return emitFunctionType(node); - case 280 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 163 /* ConstructorType */: - return emitConstructorType(node); - case 164 /* TypeQuery */: - return emitTypeQuery(node); - case 165 /* TypeLiteral */: - return emitTypeLiteral(node); - case 166 /* ArrayType */: - return emitArrayType(node); - case 167 /* TupleType */: - return emitTupleType(node); - case 168 /* UnionType */: - return emitUnionType(node); - case 169 /* IntersectionType */: - return emitIntersectionType(node); - case 170 /* ConditionalType */: - return emitConditionalType(node); - case 171 /* InferType */: - return emitInferType(node); - case 172 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 173 /* ThisType */: - return emitThisType(); - case 174 /* TypeOperator */: - return emitTypeOperator(node); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 176 /* MappedType */: - return emitMappedType(node); - case 177 /* LiteralType */: - return emitLiteralType(node); - case 275 /* JSDocAllType */: - write("*"); - return; - case 276 /* JSDocUnknownType */: - write("?"); - return; - case 277 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 278 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 279 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 281 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); - // Binding patterns - case 178 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 179 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 180 /* BindingElement */: - return emitBindingElement(node); - // Misc - case 209 /* TemplateSpan */: - return emitTemplateSpan(node); - case 210 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Statements - case 211 /* Block */: - return emitBlock(node); - case 212 /* VariableStatement */: - return emitVariableStatement(node); - case 213 /* EmptyStatement */: - return emitEmptyStatement(); - case 214 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 215 /* IfStatement */: - return emitIfStatement(node); - case 216 /* DoStatement */: - return emitDoStatement(node); - case 217 /* WhileStatement */: - return emitWhileStatement(node); - case 218 /* ForStatement */: - return emitForStatement(node); - case 219 /* ForInStatement */: - return emitForInStatement(node); - case 220 /* ForOfStatement */: - return emitForOfStatement(node); - case 221 /* ContinueStatement */: - return emitContinueStatement(node); - case 222 /* BreakStatement */: - return emitBreakStatement(node); - case 223 /* ReturnStatement */: - return emitReturnStatement(node); - case 224 /* WithStatement */: - return emitWithStatement(node); - case 225 /* SwitchStatement */: - return emitSwitchStatement(node); - case 226 /* LabeledStatement */: - return emitLabeledStatement(node); - case 227 /* ThrowStatement */: - return emitThrowStatement(node); - case 228 /* TryStatement */: - return emitTryStatement(node); - case 229 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 230 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 231 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 232 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 234 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 238 /* ModuleBlock */: - return emitModuleBlock(node); - case 239 /* CaseBlock */: - return emitCaseBlock(node); - case 240 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 243 /* ImportClause */: - return emitImportClause(node); - case 244 /* NamespaceImport */: - return emitNamespaceImport(node); - case 245 /* NamedImports */: - return emitNamedImports(node); - case 246 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 249 /* NamedExports */: - return emitNamedExports(node); - case 250 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 251 /* MissingDeclaration */: - return; - // Module references - case 252 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX (non-expression) - case 10 /* JsxText */: - return emitJsxText(node); - case 255 /* JsxOpeningElement */: - case 258 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 256 /* JsxClosingElement */: - case 259 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 260 /* JsxAttribute */: - return emitJsxAttribute(node); - case 261 /* JsxAttributes */: - return emitJsxAttributes(node); - case 262 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 263 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 264 /* CaseClause */: - return emitCaseClause(node); - case 265 /* DefaultClause */: - return emitDefaultClause(node); - case 266 /* HeritageClause */: - return emitHeritageClause(node); - case 267 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 268 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 269 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 270 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 271 /* EnumMember */: - return emitEnumMember(node); - // JSDoc nodes (ignored) - // Transformation nodes (ignored) - } - // If the node is an expression, try to emit it as an expression with - // substitution. - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - // Literals - case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; - // Expressions - case 181 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 182 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 183 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 185 /* CallExpression */: - return emitCallExpression(node); - case 186 /* NewExpression */: - return emitNewExpression(node); - case 187 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 188 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 189 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 190 /* FunctionExpression */: - return emitFunctionExpression(node); - case 191 /* ArrowFunction */: - return emitArrowFunction(node); - case 192 /* DeleteExpression */: - return emitDeleteExpression(node); - case 193 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 194 /* VoidExpression */: - return emitVoidExpression(node); - case 195 /* AwaitExpression */: - return emitAwaitExpression(node); - case 196 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 197 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 198 /* BinaryExpression */: - return emitBinaryExpression(node); - case 199 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 200 /* TemplateExpression */: - return emitTemplateExpression(node); - case 201 /* YieldExpression */: - return emitYieldExpression(node); - case 202 /* SpreadElement */: - return emitSpreadExpression(node); - case 203 /* ClassExpression */: - return emitClassExpression(node); - case 204 /* OmittedExpression */: - return; - case 206 /* AsExpression */: - return emitAsExpression(node); - case 207 /* NonNullExpression */: - return emitNonNullExpression(node); - case 208 /* MetaProperty */: - return emitMetaProperty(node); - // JSX - case 253 /* JsxElement */: - return emitJsxElement(node); - case 254 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 257 /* JsxFragment */: - return emitJsxFragment(node); - // Transformation nodes - case 295 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 296 /* CommaListExpression */: - return emitCommaList(node); - } - } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; } - function emitHelpersIndirect(node) { - if (onEmitHelpers) { - onEmitHelpers(node, writeLines); + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; } // // Literals/Pseudo-literals @@ -72560,6 +78799,10 @@ var ts; writeStringLiteral(text); } } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } // // Identifiers // @@ -72610,12 +78853,10 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 280 /* JSDocFunctionType */ && !node.name) { + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -72635,7 +78876,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -72643,28 +78884,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -72675,20 +78918,23 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 155 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -72697,6 +78943,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -72723,12 +78970,14 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); @@ -72749,6 +78998,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -72757,6 +79007,7 @@ var ts; writePunctuation("=>"); writeSpace(); emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -72765,7 +79016,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); writePunctuation("}"); } @@ -72774,15 +79025,19 @@ var ts; writePunctuation("["); writePunctuation("]"); } - function emitJSDocVariadicType(node) { + function emitRestOrJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } + function emitOptionalType(node) { + emit(node.type); + write("?"); + } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); } @@ -72846,7 +79101,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -72870,6 +79126,21 @@ var ts; function emitLiteralType(node) { emitExpression(node.literal); } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } // // Binding patterns // @@ -72884,7 +79155,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -72902,12 +79173,13 @@ var ts; emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -72957,9 +79229,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); + emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -72975,6 +79247,7 @@ var ts; } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); } @@ -72990,6 +79263,7 @@ var ts; emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -73045,7 +79319,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 196 /* PrefixUnaryExpression */ + return operand.kind === 200 /* PrefixUnaryExpression */ && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } @@ -73097,6 +79371,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -73150,7 +79425,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); @@ -73162,7 +79439,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 215 /* IfStatement */) { + if (node.elseStatement.kind === 220 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -73225,7 +79502,7 @@ var ts; emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -73233,7 +79510,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 231 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { emit(node); } else { @@ -73252,13 +79529,13 @@ var ts; writeSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { - var node = contextNode && ts.getParseTreeNode(contextNode); + var node = ts.getParseTreeNode(contextNode); var isSimilarNode = node && node.kind === contextNode.kind; var startPos = pos; if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - if (emitLeadingCommentsOfPosition && isSimilarNode) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); if (needsIndent) { increaseIndent(); @@ -73269,7 +79546,7 @@ var ts; } } pos = writeTokenText(token, writer, pos); - if (emitTrailingCommentsOfPosition && isSimilarNode) { + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; @@ -73335,7 +79612,7 @@ var ts; emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { - writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } @@ -73346,9 +79623,9 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name); + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } function emitBlockCallback(_hint, body) { @@ -73363,6 +79640,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4 /* Unspecified */, body, emitBlockCallback); @@ -73444,7 +79723,7 @@ var ts; // Emit all the prologue directives (like "use strict"). var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); var pos = writer.getTextPos(); - emitHelpersIndirect(body); + emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); @@ -73458,6 +79737,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -73470,7 +79750,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); @@ -73523,7 +79803,9 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 237 /* ModuleDeclaration */) { + if (!body) + return writeSemicolon(); + while (body.kind === 242 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -73533,6 +79815,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); popNameGenerationScope(node); } @@ -73567,7 +79850,7 @@ var ts; if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -73619,7 +79902,7 @@ var ts; if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } @@ -73643,7 +79926,7 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { @@ -73676,10 +79959,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -73691,11 +79971,10 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -73715,7 +79994,7 @@ var ts; } function emitJsxAttribute(node) { emit(node.name); - emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); @@ -73725,7 +80004,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -73848,11 +80127,52 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + if (hasNoDefaultLib) { + write("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + write("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + write("/// "); + } + else { + write("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + write("/// "); + writeLine(); + } + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); - emitHelpersIndirect(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -73926,6 +80246,8 @@ var ts; // Helpers // function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -74034,7 +80356,7 @@ var ts; emitNodeList(emit, parentNode, children, format, start, count); } function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { switch (format & 28 /* DelimitersMask */) { @@ -74060,7 +80382,7 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -74072,7 +80394,8 @@ var ts; } if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -74092,7 +80415,7 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } @@ -74105,7 +80428,7 @@ var ts; } // Emit each child. var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -74182,7 +80505,8 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - if (isEmpty) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -74281,9 +80605,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -74292,21 +80616,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { - if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { - if (indentation === undefined || i < indentation) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -74421,7 +80730,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -74430,7 +80739,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { @@ -74482,6 +80791,113 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 216 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 231 /* LabeledStatement */: + case 229 /* WithStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + generateNames(node.statement); + break; + case 220 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 230 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 244 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 272 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 217 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 236 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 237 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 247 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 248 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 249 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 250 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 251 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } /** * Generate the text for a generated identifier. */ @@ -74489,17 +80905,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { - var savedTempFlags = tempFlags; - popNameGenerationScope(/*node*/ undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(/*node*/ undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -74508,20 +80914,25 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } /** * Returns a value indicating whether a name is unique globally, within the current file, * or within the NameGenerator. */ function isUniqueName(name) { - return !(hasGlobalName && hasGlobalName(name)) - && !currentSourceFile.identifiers.has(name) + return isFileLevelUniqueName(name) && !generatedNames.has(name) && !(reservedNames && reservedNames.has(name)); } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } /** * Returns a value indicating whether a name is unique within a container. */ @@ -74575,8 +80986,21 @@ var ts; * in global scope. The name is formed by adding an '_n' suffix to the specified base name, * where n is a positive integer. Note that names generated by makeTempVariableName and * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; @@ -74584,13 +81008,21 @@ var ts; var i = 1; while (true) { var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, true); + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; } } + function makeFileLevelOptmiisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } /** * Generates a unique name for a ModuleDeclaration or EnumDeclaration. */ @@ -74603,7 +81035,7 @@ var ts; * Generates a unique name for an ImportDeclaration or ExportDeclaration. */ function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); @@ -74629,25 +81061,25 @@ var ts; /** * Generates a unique name from a node. */ - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71 /* Identifier */: - return makeUniqueName(getTextOfNode(node)); - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - case 247 /* ExportAssignment */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 252 /* ExportAssignment */: return generateNameForExportDefault(); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return generateNameForClassExpression(); - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -74659,13 +81091,13 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 3 /* Unique */: - return makeUniqueName(ts.idText(name)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } /** * Gets the node from which a name should be generated. @@ -74679,7 +81111,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 /* Node */ + && !!(node.autoGenerateFlags & 4 /* Node */) && node.autoGenerateId !== autoGenerateId) { break; } @@ -74712,2788 +81144,6 @@ var ts; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); })(ts || (ts = {})); -/// -/// -/// -var ts; -(function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } - return ts.forEachAncestorDirectory(searchPath, function (ancestor) { - var fileName = ts.combinePaths(ancestor, configName); - return fileExists(fileName) ? fileName : undefined; - }); - } - ts.findConfigFile = findConfigFile; - function resolveTripleslashReference(moduleName, containingFile) { - var basePath = ts.getDirectoryPath(containingFile); - var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); - return ts.normalizePath(referencedFileName); - } - ts.resolveTripleslashReference = resolveTripleslashReference; - /* @internal */ - function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { - var commonPathComponents; - var failed = ts.forEach(fileNames, function (sourceFile) { - // Each file contributes into common source file path - var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); - sourcePathComponents.pop(); // The base file name is not part of the common directory path - if (!commonPathComponents) { - // first file - commonPathComponents = sourcePathComponents; - return; - } - var n = Math.min(commonPathComponents.length, sourcePathComponents.length); - for (var i = 0; i < n; i++) { - if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { - if (i === 0) { - // Failed to find any common path component - return true; - } - // New common path found that is 0 -> i-1 - commonPathComponents.length = i; - break; - } - } - // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents - if (sourcePathComponents.length < commonPathComponents.length) { - commonPathComponents.length = sourcePathComponents.length; - } - }); - // A common path can not be found when paths span multiple drives on windows, for example - if (failed) { - return ""; - } - if (!commonPathComponents) { // Can happen when all input files are .d.ts files - return currentDirectory; - } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); - } - ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } - function getSourceFile(fileName, languageVersion, onError) { - var text; - try { - ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - text = ""; - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; - } - function directoryExists(directoryPath) { - if (existingDirectories.has(directoryPath)) { - return true; - } - if (ts.sys.directoryExists(directoryPath)) { - existingDirectories.set(directoryPath, true); - return true; - } - return false; - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); - } - } - var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { - if (!outputFingerprints) { - outputFingerprints = ts.createMap(); - } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); - } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); - return { - getSourceFile: getSourceFile, - getDefaultLibLocation: getDefaultLibLocation, - getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, - writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath - }; - } - ts.createCompilerHost = createCompilerHost; - function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { - ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); - } - return ts.sortAndDeduplicateDiagnostics(diagnostics); - } - ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - output += formatDiagnostic(diagnostic, host); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; - function formatDiagnostic(diagnostic, host) { - var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; - } - return errorMessage; - } - ts.formatDiagnostic = formatDiagnostic; - /** @internal */ - var ForegroundColorEscapeSequences; - (function (ForegroundColorEscapeSequences) { - ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; - ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; - ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; - ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; - ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; - })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; - var gutterSeparator = " "; - var resetEscapeSequence = "\u001b[0m"; - var ellipsis = "..."; - function getCategoryFormat(category) { - switch (category) { - case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; - case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); - case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; - } - } - /** @internal */ - function formatColorAndReset(text, formatStyle) { - return formatStyle + text + resetEscapeSequence; - } - ts.formatColorAndReset = formatColorAndReset; - function padLeft(s, length) { - while (s.length < length) { - s = " " + s; - } - return s; - } - function formatDiagnosticsWithColorAndContext(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - var context = ""; - if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; - var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); - // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, - // so we'll skip ahead to the second-to-last line. - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces - // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); - // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; - if (i === firstLine) { - // If we're on the last line, then limit it to the last character of the last line. - // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); - } - context += resetEscapeSequence; - } - output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); - output += ":"; - output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); - output += ":"; - output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); - output += " - "; - } - output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); - output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); - output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); - if (diagnostic.file) { - output += host.getNewLine(); - output += context; - } - output += host.getNewLine(); - } - return output + host.getNewLine(); - } - ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; - function flattenDiagnosticMessageText(messageText, newLine) { - if (ts.isString(messageText)) { - return messageText; - } - else { - var diagnosticChain = messageText; - var result = ""; - var indent = 0; - while (diagnosticChain) { - if (indent) { - result += newLine; - for (var i = 0; i < indent; i++) { - result += " "; - } - } - result += diagnosticChain.messageText; - indent++; - diagnosticChain = diagnosticChain.next; - } - return result; - } - } - ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { - if (names.length === 0) { - return []; - } - var resolutions = []; - var cache = ts.createMap(); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name = names_1[_i]; - var result = void 0; - if (cache.has(name)) { - result = cache.get(name); - } - else { - cache.set(name, result = loader(name, containingFile)); - } - resolutions.push(result); - } - return resolutions; - } - /** - * Determines if program structure is upto date or needs to be recreated - */ - /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { - // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date - if (!program || hasChangedAutomaticTypeDirectiveNames) { - return false; - } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { - return false; - } - // If any file is not up-to-date, then the whole program is not up-to-date - if (program.getSourceFiles().some(sourceFileNotUptoDate)) { - return false; - } - // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { - return false; - } - var currentOptions = program.getCompilerOptions(); - // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - // If everything matches but the text of config file is changed, - // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); - } - } - ts.isProgramUptoDate = isProgramUptoDate; - /** - * Determined if source file needs to be re-created even if its text hasn't changed - */ - function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); - } - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @returns A 'Program' object. - */ - function createProgram(rootNames, options, host, oldProgram) { - var program; - var files = []; - var commonSourceDirectory; - var diagnosticsProducingTypeChecker; - var noDiagnosticsTypeChecker; - var classifiableNames; - var modifiedFilePaths; - var cachedSemanticDiagnosticsForFile = {}; - var cachedDeclarationDiagnosticsForFile = {}; - var resolvedTypeReferenceDirectives = ts.createMap(); - var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. - // This works as imported modules are discovered recursively in a depth first manner, specifically: - // - For each root file, findSourceFile is called. - // - This calls processImportedModules for each module imported in the source file. - // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. - // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. - // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; - // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track - // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = ts.createMap(); - // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); - var skipDefaultLib = options.noLib; - var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); - var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); - var programDiagnostics = ts.createDiagnosticCollection(); - var currentDirectory = host.getCurrentDirectory(); - var supportedExtensions = ts.getSupportedExtensions(options); - // Map storing if there is emit blocking diagnostics for given input - var hasEmitBlockingDiagnostics = ts.createMap(); - var _compilerOptionsObjectLiteralSyntax; - var moduleResolutionCache; - var resolveModuleNamesWorker; - var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; - if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { - // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. - if (!resolved || resolved.extension !== undefined) { - return resolved; - } - var withExtension = ts.clone(resolved); - withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); - return withExtension; - }); }; - } - else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; - } - var resolveTypeReferenceDirectiveNamesWorker; - if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; - } - else { - 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(); - var missingFilePaths; - // stores 'filename -> file association' ignoring case - // used to track cases when two file names differ only in casing - var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; - var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - var structuralIsReused = tryReuseStructureFromOldProgram(); - if (structuralIsReused !== 2 /* Completely */) { - ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); - if (typeReferences.length) { - // This containingFilename needs to match with the one used in managed-side - var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); - for (var i = 0; i < typeReferences.length; i++) { - processTypeReferenceDirective(typeReferences[i], resolutions[i]); - } - } - // Do not process the default library if: - // - The '--noLib' flag is used. - // - A 'no-default-lib' reference comment is encountered in - // processing the root files. - if (!skipDefaultLib) { - // If '--lib' is not specified, include default library file according to '--target' - // otherwise, using options specified in '--lib' instead of '--target' default library file - if (!options.lib) { - processRootFile(getDefaultLibraryFileName(), /*isDefaultLib*/ true); - } - else { - ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true); - }); - } - } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); - } - ts.Debug.assert(!!missingFilePaths); - // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks - moduleResolutionCache = undefined; - // Release any files we have acquired in the old program but are - // not part of the new program. - if (oldProgram && host.onReleaseOldSourceFile) { - var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); - } - } - } - // unconditionally set oldProgram to undefined to prevent it from being captured in closure - oldProgram = undefined; - program = { - getRootFileNames: function () { return rootNames; }, - getSourceFile: getSourceFile, - getSourceFileByPath: getSourceFileByPath, - getSourceFiles: function () { return files; }, - getMissingFilePaths: function () { return missingFilePaths; }, - getCompilerOptions: function () { return options; }, - getSyntacticDiagnostics: getSyntacticDiagnostics, - getOptionsDiagnostics: getOptionsDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getSemanticDiagnostics: getSemanticDiagnostics, - getDeclarationDiagnostics: getDeclarationDiagnostics, - getTypeChecker: getTypeChecker, - getClassifiableNames: getClassifiableNames, - getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: getCommonSourceDirectory, - emit: emit, - getCurrentDirectory: function () { return currentDirectory; }, - getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, - getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, - getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, - getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, - getSourceFileFromReference: getSourceFileFromReference, - sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - isEmittedFile: isEmittedFile - }; - verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); - return program; - function toPath(fileName) { - return ts.toPath(fileName, currentDirectory, getCanonicalFileName); - } - function getCommonSourceDirectory() { - if (commonSourceDirectory === undefined) { - var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); - if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; - } - } - return commonSourceDirectory; - } - function getClassifiableNames() { - if (!classifiableNames) { - // Initialize a checker so that all our files are bound. - getTypeChecker(); - classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; - ts.copyEntries(sourceFile.classifiableNames, classifiableNames); - } - } - return classifiableNames; - } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { - // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, - // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); - if (oldSourceFile !== file && file.resolvedModules) { - // `file` was created for the new program. - // - // We only set `file.resolvedModules` via work from the current function, - // so it is defined iff we already called the current function on `file`. - // That call happened no later than the creation of the `file` object, - // which per above occured during the current program creation. - // Since we assume the filesystem does not change during program creation, - // it is safe to reuse resolutions from the earlier call. - var result_3 = []; - for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { - var moduleName = moduleNames_1[_i]; - var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); - } - return result_3; - } - // At this point, we know at least one of the following hold: - // - file has local declarations for ambient modules - // - old program state is available - // With this information, we can infer some module resolutions without performing resolution. - /** An ordered list of module names for which we cannot recover the resolution. */ - var unknownModuleNames; - /** - * The indexing of elements in this list matches that of `moduleNames`. - * - * Before combining results, result[i] is in one of the following states: - * * undefined: needs to be recomputed, - * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. - * Needs to be reset to undefined before returning, - * * ResolvedModuleFull instance: can be reused. - */ - var result; - var reusedNames; - /** A transient placeholder used to mark predicted resolution in the result list. */ - var predictedToResolveToAmbientModuleMarker = {}; - for (var i = 0; i < moduleNames.length; i++) { - var moduleName = moduleNames[i]; - // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions - if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { - var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); - if (oldResolvedModule) { - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); - } - (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; - (reusedNames || (reusedNames = [])).push(moduleName); - continue; - } - } - // We know moduleName resolves to an ambient module provided that moduleName: - // - is in the list of ambient modules locally declared in the current source file. - // - resolved to an ambient module in the old program whose declaration is in an unmodified file - // (so the same module declaration will land in the new program) - var resolvesToAmbientModuleInNonModifiedFile = false; - if (ts.contains(file.ambientModuleNames, moduleName)) { - resolvesToAmbientModuleInNonModifiedFile = true; - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); - } - } - else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); - } - if (resolvesToAmbientModuleInNonModifiedFile) { - (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; - } - else { - // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. - (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); - } - } - var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) - : ts.emptyArray; - // Combine results of resolutions and predicted results - if (!result) { - // There were no unresolved/ambient resolutions. - ts.Debug.assert(resolutions.length === moduleNames.length); - return resolutions; - } - var j = 0; - for (var i = 0; i < result.length; i++) { - if (result[i]) { - // `result[i]` is either a `ResolvedModuleFull` or a marker. - // If it is the former, we can leave it as is. - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; - } - } - else { - result[i] = resolutions[j]; - j++; - } - } - ts.Debug.assert(j === resolutions.length); - return result; - // If we change our policy of rechecking failed lookups on each program create, - // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); - if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { - // In the old program, we resolved to an ambient module that was in the same - // place as we expected to find an actual module file. - // We actually need to return 'false' here even though this seems like a 'true' case - // because the normal module resolution algorithm will find this anyway. - return false; - } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } - // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { - return false; - } - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); - } - return true; - } - } - function tryReuseStructureFromOldProgram() { - if (!oldProgram) { - return 0 /* Not */; - } - // check properties that can affect structure of the program or module resolution strategy - // if any of these properties has changed - structure cannot be reused - var oldOptions = oldProgram.getCompilerOptions(); - if (ts.changesAffectModuleResolution(oldOptions, options)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); - // there is an old program, check if we can reuse its structure - var oldRootNames = oldProgram.getRootFileNames(); - if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - // check if program source files has changed in the way that can affect structure of the program - var newSourceFiles = []; - var filePaths = []; - var modifiedSourceFiles = []; - oldProgram.structureIsReused = 2 /* Completely */; - // If the missing file paths are now present, it can change the progam structure, - // and hence cant reuse the structure. - // This is same as how we dont reuse the structure if one of the file from old program is now missing - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { - return oldProgram.structureIsReused = 0 /* Not */; - } - 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_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); - 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); - 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 - // this will affect if default library is injected into the list of files - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - // tripleslash references has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if ((oldSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */) !== (newSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */)) { - // dynamicImport has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // tentatively approve the file - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); - } - else if (hasInvalidatedResolution(oldSourceFile.path)) { - // 'module/types' references could have changed - oldProgram.structureIsReused = 1 /* SafeModules */; - // add file to the modified list so that we will resolve it later - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); - } - // if file has passed all checks it should be safe to reuse it - newSourceFiles.push(newSourceFile); - } - if (oldProgram.structureIsReused !== 2 /* Completely */) { - return oldProgram.structureIsReused; - } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); - // try to verify results of module resolution - for (var _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 = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); - // ensure that module resolution results are still correct - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - oldProgram.structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); - } - else { - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - // ensure that types resolutions are still correct - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - oldProgram.structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); - } - else { - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - } - } - } - if (oldProgram.structureIsReused !== 2 /* Completely */) { - return oldProgram.structureIsReused; - } - if (host.hasChangedAutomaticTypeDirectiveNames) { - return oldProgram.structureIsReused = 1 /* SafeModules */; - } - missingFilePaths = oldProgram.getMissingFilePaths(); - // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); - // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); - } - } - files = newSourceFiles; - fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); - } - resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; - return oldProgram.structureIsReused = 2 /* Completely */; - } - function getEmitHost(writeFileCallback) { - return { - getCanonicalFileName: getCanonicalFileName, - getCommonSourceDirectory: program.getCommonSourceDirectory, - getCompilerOptions: program.getCompilerOptions, - getCurrentDirectory: function () { return currentDirectory; }, - getNewLine: function () { return host.getNewLine(); }, - getSourceFile: program.getSourceFile, - getSourceFileByPath: program.getSourceFileByPath, - getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked, - }; - } - function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); - } - function isSourceFileDefaultLibrary(file) { - if (file.hasNoDefaultLib) { - return true; - } - if (!options.noLib) { - return false; - } - // If '--lib' is not specified, include default library file according to '--target' - // otherwise, using options specified in '--lib' instead of '--target' default library file - var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; - if (!options.lib) { - return equalityComparer(file.fileName, getDefaultLibraryFileName()); - } - else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); - } - } - function getDiagnosticsProducingTypeChecker() { - return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); - } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } - function getTypeChecker() { - return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); - } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); - } - function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); - } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var declarationDiagnostics = []; - if (!emitOnlyDtsFiles) { - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); - } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; - } - } - } - // Create the emit resolver outside of the "emitTime" tracking code below. That way - // any cost associated with it (like type checking) are appropriate associated with - // the type-checking counter. - // - // If the -out option is specified, we should not pass the source file to getEmitResolver. - // This is because in the -out scenario all files need to be emitted, and therefore all - // files need to be type checked. And the way to specify that all files need to be type - // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); - ts.performance.mark("beforeEmit"); - var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - return emitResult; - } - function getSourceFile(fileName) { - return getSourceFileByPath(toPath(fileName)); - } - function getSourceFileByPath(path) { - return filesByName.get(path); - } - function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { - if (sourceFile) { - return getDiagnostics(sourceFile, cancellationToken); - } - return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { - if (cancellationToken) { - cancellationToken.throwIfCancellationRequested(); - } - return getDiagnostics(sourceFile, cancellationToken); - })); - } - function getSyntacticDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); - } - function getSemanticDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); - } - function getDeclarationDiagnostics(sourceFile, cancellationToken) { - var options = program.getCompilerOptions(); - // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) - if (!sourceFile || options.out || options.outFile) { - return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); - } - else { - return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); - } - } - function getSyntacticDiagnosticsForFile(sourceFile) { - // For JavaScript files, we report semantic errors for using TypeScript-only - // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { - if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - } - return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); - } - return sourceFile.parseDiagnostics; - } - function runWithCancellationToken(func) { - try { - return func(); - } - catch (e) { - if (e instanceof ts.OperationCanceledException) { - // We were canceled while performing the operation. Because our type checker - // might be a bad state, we need to throw it away. - // - // Note: we are overly aggressive here. We do not actually *have* to throw away - // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep - // the lifetimes of these two TypeCheckers the same. Also, we generally only - // cancel when the user has made a change anyways. And, in that case, we (the - // program instance) will get thrown away anyways. So trying to keep one of - // these type checkers alive doesn't serve much purpose. - noDiagnosticsTypeChecker = undefined; - diagnosticsProducingTypeChecker = undefined; - } - throw e; - } - } - function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); - } - function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { - return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return ts.emptyArray; - } - var typeChecker = getDiagnosticsProducingTypeChecker(); - ts.Debug.assert(!!sourceFile.bindDiagnostics); - var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); - // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) - var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || - sourceFile.scriptKind === 5 /* External */ || isCheckJs; - var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; - var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; - var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); - var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); - } - return ts.filter(diagnostics, shouldReportDiagnostic); - }); - } - /** - * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines - */ - function shouldReportDiagnostic(diagnostic) { - var file = diagnostic.file, start = diagnostic.start; - if (file) { - var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; - while (line > 0) { - var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); - var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); - if (!result) { - // non-empty line - return true; - } - if (result[3]) { - // @ts-ignore - return false; - } - line--; - } - } - return true; - } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { - return runWithCancellationToken(function () { - var diagnostics = []; - var parent = sourceFile; - walk(sourceFile); - return diagnostics; - function walk(node) { - // Return directly from the case if the given node doesnt want to visit each child - // Otherwise break to visit each child - switch (parent.kind) { - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - if (parent.questionToken === node) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return; - } - // falls through - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 230 /* VariableDeclaration */: - // type annotation - if (parent.type === node) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return; - } - } - switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return; - case 247 /* ExportAssignment */: - if (node.isExportEquals) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 266 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 234 /* InterfaceDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return; - case 237 /* ModuleDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return; - case 235 /* TypeAliasDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return; - case 236 /* EnumDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return; - case 207 /* NonNullExpression */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); - return; - case 206 /* AsExpression */: - diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return; - case 188 /* TypeAssertionExpression */: - ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. - } - var prevParent = parent; - parent = node; - ts.forEachChild(node, walk, walkArray); - parent = prevParent; - } - function walkArray(nodes) { - if (parent.decorators === nodes && !options.experimentalDecorators) { - diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); - } - switch (parent.kind) { - case 233 /* ClassDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - // Check type parameters - if (nodes === parent.typeParameters) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return; - } - // falls through - case 212 /* VariableStatement */: - // Check modifiers - if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 212 /* VariableStatement */); - } - break; - case 151 /* PropertyDeclaration */: - // Check modifiers of property declaration - if (nodes === parent.modifiers) { - for (var _i = 0, _a = nodes; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { - diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - } - } - return; - } - break; - case 148 /* Parameter */: - // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 205 /* ExpressionWithTypeArguments */: - // Check type arguments - if (nodes === parent.typeArguments) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return; - } - break; - } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; - walk(node); - } - } - function checkModifiers(modifiers, isConstValid) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (isConstValid) { - continue; - } - // to report error, - // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: - diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - break; - // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: - } - } - } - function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { - var start = nodes.pos; - return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); - } - // Since these are syntactic diagnostics, parent might not have been set - // this means the sourceFile cannot be infered from the node - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { - return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); - } - }); - } - function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); - } - function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { - return runWithCancellationToken(function () { - var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); - // Don't actually write any files since we're just getting diagnostics. - return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); - }); - } - function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { - var cachedResult = sourceFile - ? cache.perFile && cache.perFile.get(sourceFile.path) - : cache.allDiagnostics; - if (cachedResult) { - return cachedResult; - } - var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; - if (sourceFile) { - if (!cache.perFile) { - cache.perFile = ts.createMap(); - } - cache.perFile.set(sourceFile.path, result); - } - else { - cache.allDiagnostics = result; - } - return result; - } - function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); - } - function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); - } - function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); - } - function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); - } - function fileReferenceIsEqualTo(a, b) { - return a.fileName === b.fileName; - } - function moduleNameIsEqualTo(a, b) { - return a.kind === 9 /* StringLiteral */ - ? b.kind === 9 /* StringLiteral */ && a.text === b.text - : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; - } - function collectExternalModuleReferences(file) { - if (file.imports) { - return; - } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); - var isExternalModuleFile = ts.isExternalModule(file); - // file.imports may not be undefined if there exists dynamic import - var imports; - var moduleAugmentations; - var ambientModules; - // If we are importing helpers, we need to add a synthetic reference to resolve the - // helpers library. - if (options.importHelpers - && (options.isolatedModules || isExternalModuleFile) - && !file.isDeclarationFile) { - // synthesize 'import "tslib"' declaration - var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); - ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); - externalHelpersModuleReference.parent = importDecl; - importDecl.parent = file; - imports = [externalHelpersModuleReference]; - } - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var node = _a[_i]; - collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } - } - file.imports = imports || ts.emptyArray; - file.moduleAugmentations = moduleAugmentations || ts.emptyArray; - file.ambientModuleNames = ambientModules || ts.emptyArray; - return; - function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; - } - if (!moduleNameExpr.text) { - break; - } - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules - // only through top - level external module names. Relative external module names are not permitted. - if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { - (imports || (imports = [])).push(moduleNameExpr); - } - break; - case 237 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; - var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); - // Ambient module declarations can be interpreted as augmentations for some existing external modules. - // This will happen in two cases: - // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope - // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name - // immediately nested in top level ambient module declaration . - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { - (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); - } - else if (!inAmbientModule) { - if (file.isDeclarationFile) { - // for global .d.ts files record name of ambient module - (ambientModules || (ambientModules = [])).push(nameText); - } - // An AmbientExternalModuleDeclaration declares an external module. - // This type of declaration is permitted only in the global module. - // The StringLiteral must specify a top - level external module name. - // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block, if it exists - var body = node.body; - if (body) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); - } - } - } - } - } - } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - (imports || (imports = [])).push(node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { - (imports || (imports = [])).push(node.arguments[0]); - } - else { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); - } - } - } - /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ - function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); - } - function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { - if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); - return undefined; - } - var sourceFile = getSourceFile(fileName); - if (fail) { - if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); - } - } - return sourceFile; - } - else { - var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); - if (sourceFileNoExtension) - return sourceFileNoExtension; - if (fail && options.allowNonTsExtensions) { - fail(ts.Diagnostics.File_0_not_found, fileName); - return undefined; - } - var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); - if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); - return sourceFileWithAddedExtension; - } - } - /** This has side effects through `findSourceFile`. */ - function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined - ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); - }, refFile); - } - function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { - if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); - } - else { - 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, 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 - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); - } - // If the file was previously found via a node_modules search, but is now being processed as a root file, - // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); - if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); - } - // See if we need to reprocess the imports due to prior skipped imports - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { - if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); - } - } - return file_1; - } - // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { - if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); - } - }, shouldCreateNewSourceFile); - if (packageId) { - var packageIdKey = ts.packageIdToString(packageId); - 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); - file.path = path; - if (host.useCaseSensitiveFileNames()) { - var pathLowerCase = path.toLowerCase(); - // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(pathLowerCase); - if (existingFile) { - reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); - } - else { - filesByNameIgnoreCase.set(pathLowerCase, file); - } - } - skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - if (!options.noResolve) { - processReferencedFiles(file, isDefaultLib); - processTypeReferenceDirectives(file); - } - // always process imported modules to record module name resolutions - processImportedModules(file); - if (isDefaultLib) { - files.unshift(file); - } - else { - files.push(file); - } - } - return file; - } - function processReferencedFiles(file, isDefaultLib) { - ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, /*packageId*/ undefined, file, ref.pos, ref.end); - }); - } - function processTypeReferenceDirectives(file) { - // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); - for (var i = 0; i < typeDirectives.length; i++) { - var ref = file.typeReferenceDirectives[i]; - var resolvedTypeReferenceDirective = resolutions[i]; - // store resolved type directive on the file - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); - } - } - function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { - // If we already found this library as a primary reference - nothing to do - var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); - if (previousResolution && previousResolution.primary) { - return; - } - var saveResolution = true; - if (resolvedTypeReferenceDirective) { - if (resolvedTypeReferenceDirective.primary) { - // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); - } - else { - // If we already resolved to this file, it must have been a secondary reference. Check file contents - // for sameness and possibly issue an error - if (previousResolution) { - // Don't bother reading the file again if it's the same file. - if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); - } - } - // don't overwrite previous resolution result - saveResolution = false; - } - else { - // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); - } - } - } - else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); - } - if (saveResolution) { - resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); - } - } - function createDiagnostic(refFile, refPos, refEnd, message) { - var args = []; - for (var _i = 4; _i < arguments.length; _i++) { - args[_i - 4] = arguments[_i]; - } - if (refFile === undefined || refPos === undefined || refEnd === undefined) { - return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); - } - else { - return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); - } - } - function getCanonicalFileName(fileName) { - return host.getCanonicalFileName(fileName); - } - function processImportedModules(file) { - collectExternalModuleReferences(file); - if (file.imports.length || file.moduleAugmentations.length) { - // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. - var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); - ts.Debug.assert(resolutions.length === moduleNames.length); - for (var i = 0; i < moduleNames.length; i++) { - var resolution = resolutions[i]; - ts.setResolvedModule(file, moduleNames[i], resolution); - if (!resolution) { - continue; - } - var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); - var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; - var resolvedFileName = resolution.resolvedFileName; - if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; - } - // add file to program only if: - // - resolution was successful - // - noResolve is falsy - // - module name comes from the list of imports - // - it's not a top level JavaScript module that exceeded the search max - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') - // This may still end up being an untyped module -- the file won't be included but imports will be allowed. - var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve - && i < file.imports.length - && !elideImport - && !(isJsFile && !options.allowJs); - if (elideImport) { - modulesWithElidedImports.set(file.path, true); - } - 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, resolution.packageId); - } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; - } - } - } - else { - // no imports - drop cached module resolutions - file.resolvedModules = undefined; - } - } - function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } - return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); - } - function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { - var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); - allFilesBelongToPath = false; - } - } - } - } - return allFilesBelongToPath; - } - function verifyCompilerOptions() { - if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); - } - if (options.noEmitOnError) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); - } - if (options.out) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); - } - if (options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); - } - } - if (options.inlineSourceMap) { - if (options.sourceMap) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); - } - if (options.mapRoot) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); - } - } - if (options.paths && options.baseUrl === undefined) { - createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); - } - if (options.paths) { - for (var key in options.paths) { - if (!ts.hasProperty(options.paths, key)) { - continue; - } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); - } - if (ts.isArray(options.paths[key])) { - var len = options.paths[key].length; - if (len === 0) { - createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); - } - for (var i = 0; i < len; i++) { - var subst = options.paths[key][i]; - var typeOfSubst = typeof subst; - if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); - } - } - else { - createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); - } - } - } - else { - createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); - } - } - } - if (!options.sourceMap && !options.inlineSourceMap) { - if (options.inlineSources) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); - } - if (options.sourceRoot) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); - } - } - if (options.out && options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); - } - if (options.mapRoot && !options.sourceMap) { - // Error to specify --mapRoot without --sourcemap - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); - } - if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); - } - if (options.out || options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); - } - } - if (options.lib && options.noLib) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); - } - if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); - } - var languageVersion = options.target || 0 /* ES3 */; - var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); - if (options.isolatedModules) { - if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { - createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); - } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); - if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); - } - } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); - } - // Cannot specify module gen that isn't amd or system with --out - if (outFile) { - if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); - } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); - } - } - // 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 || // there is --outDir specified - options.sourceRoot || // there is --sourceRoot specified - options.mapRoot) { // there is --mapRoot specified - // Precalculate and cache the common source directory - var dir = getCommonSourceDirectory(); - // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure - if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); - } - } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); - } - if (options.checkJs && !options.allowJs) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); - } - if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); - } - if (options.noEmit) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); - } - } - if (options.emitDecoratorMetadata && - !options.experimentalDecorators) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); - } - if (options.jsxFactory) { - if (options.reactNamespace) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); - } - if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); - } - } - else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); - } - // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files - if (!options.noEmit && !options.suppressOutputPathCheck) { - var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createMap(); - ts.forEachEmittedFile(emitHost, function (emitFileNames) { - if (!options.emitDeclarationOnly) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); - } - verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); - }); - } - // Verify that all the emit files are unique and don't overwrite input files - function verifyEmitFilePath(emitFileName, emitFilesSeen) { - if (emitFileName) { - var emitFilePath = toPath(emitFileName); - // Report error if the output overwrites input file - if (filesByName.has(emitFilePath)) { - var chain_2; - if (!options.configFilePath) { - // The program is from either an inferred project or an external project - chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); - } - chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); - } - var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; - // Report error if multiple files write into same file - if (emitFilesSeen.has(emitFileKey)) { - // Already seen the same emit file - report error - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); - } - else { - emitFilesSeen.set(emitFileKey, true); - } - } - } - } - function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { - var pathProp = pathsSyntax_1[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer)) { - for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { - var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); - needCompilerDiagnostic = false; - } - } - } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); - } - } - function createDiagnosticForOptionPaths(onKey, key, message, arg0) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { - var pathProp = pathsSyntax_2[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer) && - createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { - needCompilerDiagnostic = false; - } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); - } - } - function getOptionPathsSyntax() { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); - } - return ts.emptyArray; - } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); - } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); - } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); - } - } - function getCompilerOptionsObjectLiteralSyntax() { - if (_compilerOptionsObjectLiteralSyntax === undefined) { - _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isObjectLiteralExpression(prop.initializer)) { - _compilerOptionsObjectLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _compilerOptionsObjectLiteralSyntax; - } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { - var props = ts.getPropertyAssignment(objectLiteral, key1, key2); - for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { - var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); - } - return !!props.length; - } - function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); - programDiagnostics.add(diag); - } - function isEmittedFile(file) { - if (options.noEmit) { - return false; - } - // If this is source file, its not emitted file - var filePath = toPath(file); - if (getSourceFileByPath(filePath)) { - return false; - } - // If options have --outFile or --out just check that - var out = options.outFile || options.out; - if (out) { - return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); - } - // If --outDir, check if file is in that directory - if (options.outDir) { - return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); - } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { - // Otherwise just check if sourceFile with the name exists - var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); - } - return false; - } - function isSameFile(file1, file2) { - return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; - } - } - ts.createProgram = createProgram; - /* @internal */ - /** - * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. - * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. - * This returns a diagnostic even if the module will be an untyped module. - */ - function getResolutionDiagnostic(options, _a) { - var extension = _a.extension; - switch (extension) { - case ".ts" /* Ts */: - case ".d.ts" /* Dts */: - // These are always allowed. - return undefined; - case ".tsx" /* Tsx */: - return needJsx(); - case ".jsx" /* Jsx */: - return needJsx() || needAllowJs(); - case ".js" /* Js */: - return needAllowJs(); - } - function needJsx() { - return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; - } - function needAllowJs() { - return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; - } - } - ts.getResolutionDiagnostic = getResolutionDiagnostic; - function checkAllDefined(names) { - ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); - return names; - } - function getModuleNames(_a) { - var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; - var res = imports.map(function (i) { return i.text; }); - for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { - var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { - res.push(aug.text); - } - } - return res; - } -})(ts || (ts = {})); -/// -/*@internal*/ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -/*@internal*/ -(function (ts) { - var BuilderState; - (function (BuilderState) { - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile, getCanonicalFileName) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed - */ - function canReuseOldState(newReferencedMap, oldState) { - return oldState && !oldState.referencedMap === !newReferencedMap; - } - BuilderState.canReuseOldState = canReuseOldState; - /** - * Creates the state of file references and signature for the new program from oldState if it is safe - */ - function create(newProgram, getCanonicalFileName, oldState) { - var fileInfos = ts.createMap(); - var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; - var hasCalledUpdateShapeSignature = ts.createMap(); - var useOldState = canReuseOldState(referencedMap, oldState); - // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); - if (referencedMap) { - var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); - if (newReferences) { - referencedMap.set(sourceFile.path, newReferences); - } - } - fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); - } - return { - fileInfos: fileInfos, - referencedMap: referencedMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined - }; - } - BuilderState.create = create; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be commited once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are commited only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || ts.createMap(); - var sourceFile = programOfThisState.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { - return [sourceFile]; - } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { - state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.set(path, true); - }); - } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; - /** - * Returns if the shape of the signature has changed since last emit - */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { - ts.Debug.assert(!!sourceFile); - // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { - return false; - } - var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - } - else { - var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = computeHash(emitOutput.outputFiles[0].text); - } - else { - latestSignature = prevSignature; - } - } - cacheToUpdateSignature.set(sourceFile.path, latestSignature); - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Get all the dependencies of the sourceFile - */ - function getAllDependencies(state, programOfThisState, sourceFile) { - var compilerOptions = programOfThisState.getCompilerOptions(); - // With --out or --outFile all outputs go into single file, all files depend on each other - if (compilerOptions.outFile || compilerOptions.out) { - return getAllFileNames(state, programOfThisState); - } - // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { - return getAllFileNames(state, programOfThisState); - } - // Get the references, traversing deep from the referenceMap - var seenMap = ts.createMap(); - var queue = [sourceFile.path]; - while (queue.length) { - var path = queue.pop(); - if (!seenMap.has(path)) { - seenMap.set(path, true); - var references = state.referencedMap.get(path); - if (references) { - var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - queue.push(value); - } - } - } - } - return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { - var file = programOfThisState.getSourceFileByPath(path); - return file ? file.fileName : path; - })); - var _b; - } - BuilderState.getAllDependencies = getAllDependencies; - /** - * Gets the names of all files from the program - */ - function getAllFileNames(state, programOfThisState) { - if (!state.allFileNames) { - var sourceFiles = programOfThisState.getSourceFiles(); - state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); - } - return state.allFileNames; - } - /** - * Gets the files referenced by the the file path - */ - function getReferencedByPaths(state, referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * Gets all files of the program excluding the default library file - */ - function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { - // Use cached result - if (state.allFilesExcludingDefaultLibraryFile) { - return state.allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return state.allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - /** - * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed - */ - function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { - var compilerOptions = programOfThisState.getCompilerOptions(); - // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, - // so returning the file itself is good enough. - if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { - return [sourceFileWithUpdatedShape]; - } - return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); - } - /** - * When program emits modular code, gets the files affected by the sourceFile whose shape has changed - */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { - return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); - } - var compilerOptions = programOfThisState.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFileWithUpdatedShape]; - } - // Now we need to if each file in the referencedBy list has a shape change as well. - // Because if so, its own referencedBy files need to be saved as well to make the - // emitting result consistent with files on disk. - var seenFileNamesMap = ts.createMap(); - // Start with the paths this file was referenced by - seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); - } - } - } - // Return array of values that needs emit - // Return array of values that needs emit - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); -})(ts || (ts = {})); -/// -/*@internal*/ -var ts; -(function (ts) { - function hasSameKeys(map1, map2) { - // Has same size and every key is present in both maps - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); - } - /** - * Create the state so that we can iterate on changedFiles/affected files - */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); - state.program = newProgram; - var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { - state.semanticDiagnosticsPerFile = ts.createMap(); - } - state.changedFilesSet = ts.createMap(); - var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; - if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } - // Copy old state's changed files set - ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); - } - // Update changed files and copy semantic diagnostics if we can - var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; - state.fileInfos.forEach(function (info, sourceFilePath) { - var oldInfo; - var newReferences; - // if not using old state, every file is changed - if (!useOldState || - // File wasnt present in old state - !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || - // versions dont match - oldInfo.version !== info.version || - // Referenced files changed - !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || - // Referenced file was deleted in the new program - newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { - // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated - state.changedFilesSet.set(sourceFilePath, true); - } - else if (canCopySemanticDiagnostics) { - // Unchanged file copy diagnostics - var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); - if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); - } - } - }); - return state; - } - /** - * Verifies that source file is ok to be used in calls that arent handled by next - */ - function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { - ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); - } - /** - * This function returns the next affected file to be processed. - * Note that until doneAffected is called it would keep reporting same result - * This is to allow the callers to be able to actually remove affected file only when the operation is complete - * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained - */ - function getNextAffectedFile(state, cancellationToken, computeHash) { - while (true) { - var affectedFiles = state.affectedFiles; - if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; - var affectedFilesIndex = state.affectedFilesIndex; - while (affectedFilesIndex < affectedFiles.length) { - var affectedFile = affectedFiles[affectedFilesIndex]; - if (!seenAffectedFiles.has(affectedFile.path)) { - // Set the next affected file as seen and remove the cached semantic diagnostics - state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); - return affectedFile; - } - seenAffectedFiles.set(affectedFile.path, true); - affectedFilesIndex++; - } - // Remove the changed file from the change set - state.changedFilesSet.delete(state.currentChangedFilePath); - state.currentChangedFilePath = undefined; - // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - state.affectedFiles = undefined; - } - // Get next changed file - var nextKey = state.changedFilesSet.keys().next(); - if (nextKey.done) { - // Done - return undefined; - } - // With --out or --outFile all outputs go into single file - // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; - } - // Get next batch of affected files - state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); - state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); - state.affectedFilesIndex = 0; - state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); - } - } - /** - * This is called after completing operation on the next affected file. - * The operations here are postponed to ensure that cancellation during the iteration is handled correctly - */ - function doneWithAffectedFile(state, affected) { - if (affected === state.program) { - state.changedFilesSet.clear(); - } - else { - state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; - } - } - /** - * Returns the result with affected file - */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); - return { result: result, affected: affected }; - } - /** - * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it - * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set - */ - function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; - } - // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - var BuilderProgramKind; - (function (BuilderProgramKind) { - BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; - BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; - })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - var host; - var newProgram; - if (ts.isArray(newProgramOrRootNames)) { - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); - host = oldProgramOrHost; - } - else { - newProgram = newProgramOrRootNames; - host = hostOrOptions; - oldProgram = oldProgramOrHost; - } - return { host: host, newProgram: newProgram, oldProgram: oldProgram }; - } - ts.getBuilderCreationParameters = getBuilderCreationParameters; - function createBuilderProgram(kind, _a) { - var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; - // Return same program if underlying program doesnt change - var oldState = oldProgram && oldProgram.getState(); - if (oldState && newProgram === oldState.program) { - newProgram = undefined; - oldState = undefined; - return oldProgram; - } - /** - * Create the canonical file name for identity - */ - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - /** - * Computing hash to for signature verification - */ - var computeHash = host.createHash || ts.identity; - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); - // To ensure that we arent storing any references to old program or new program without state - newProgram = undefined; - oldProgram = undefined; - oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } - }; - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; - } - else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { - result.emitNextAffectedFile = emitNextAffectedFile; - } - else { - ts.notImplemented(); - } - return result; - /** - * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash); - if (!affected) { - // Done - return undefined; - } - return toAffectedFileResult(state, - // When whole program is affected, do emit only once (eg when --out or --outFile is specified) - // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); - } - /** - * Emits the JavaScript and declaration files. - * When targetSource file is specified, emits the files corresponding to that source file, - * otherwise for the whole program. - * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, - * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, - * it will only emit all the affected files instead of whole program - * - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { - assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); - if (!targetSourceFile) { - // Emit and report any errors we ran into. - var sourceMaps = []; - var emitSkipped = void 0; - var diagnostics = void 0; - var emittedFiles = []; - var affectedEmitResult = void 0; - while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { - emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; - diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); - emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); - sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); - } - return { - emitSkipped: emitSkipped, - diagnostics: diagnostics || ts.emptyArray, - emittedFiles: emittedFiles, - sourceMaps: sourceMaps - }; - } - } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - } - /** - * Return the semantic diagnostics for the next affected file or undefined if iteration is complete - * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true - */ - function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { - while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash); - if (!affected) { - // Done - return undefined; - } - else if (affected === state.program) { - // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) - return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); - } - // Get diagnostics for the affected file if its not ignored - if (ignoreSourceFile && ignoreSourceFile(affected)) { - // Get next affected file - doneWithAffectedFile(state, affected); - continue; - } - return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); - } - } - /** - * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program - * The semantic diagnostics are cached and managed here - * Note that it is assumed that when asked about semantic diagnostics through this API, - * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics - * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, - * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics - */ - function getSemanticDiagnostics(sourceFile, cancellationToken) { - assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(!state.semanticDiagnosticsPerFile); - // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - } - if (sourceFile) { - return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); - } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); - } - } - var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - } - ts.createBuilderProgram = createBuilderProgram; -})(ts || (ts = {})); -(function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); - } - ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); - } - ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; - } - ts.createAbstractBuilder = createAbstractBuilder; -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -77520,7 +81170,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -77533,7 +81183,7 @@ var ts; files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } /** @@ -77542,6 +81192,7 @@ var ts; * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -77551,7 +81202,7 @@ var ts; } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -77587,7 +81238,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -77777,7 +81428,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -77790,9 +81441,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -77801,16 +81470,3190 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } ts.closeFileWatcherOf = closeFileWatcherOf; })(ts || (ts = {})); -/// -/// -/// +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = ts.sys.readFile(fileName, options.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (ts.sys.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + ts.sys.createDirectory(directoryPath); + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = ts.sys.createHash(data); // TODO: GH#18217 + var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + ts.sys.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + ts.sys.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options); + var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + return { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, + getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), + setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), + deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + }; + } + ts.createCompilerHost = createCompilerHost; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (program.getCompilerOptions().declaration) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[30;47m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determined if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + // If any of these options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree change + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var modifiedFilePaths; + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + } + else { + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(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(); + var redirectTargetsSet = ts.createMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + // at least one of declarations should come from non-modified source file + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return oldProgram.structureIsReused = 0 /* Not */; + } + } + else { + // A previously-unresolved reference may be resolved now + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var filePaths = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + 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_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + 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); + 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 (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + // try to verify results of module resolution + for (var _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 = getModuleNames(newSourceFile); + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var i = 0; i < newSourceFiles.length; i++) { + filesByName.set(filePaths[i], newSourceFiles[i]); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + resolvedProjectReferences = oldProgram.getProjectReferences(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 235 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 246 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 252 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 271 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 108 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 239 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 240 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 241 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 211 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 210 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 192 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 217 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + } + break; + case 152 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 115 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 149 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 76 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 132 /* ReadonlyKeyword */: + case 124 /* DeclareKeyword */: + case 117 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 115 /* StaticKeyword */: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + } + function getGlobalDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 71 /* Identifier */ + ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 9 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); + } + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file.endOfFileToken); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(node) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + } + } + function collectDynamicImportOrRequireCallsForEachChild(node) { + ts.forEachChild(node, collectDynamicImportOrRequireCalls); + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + 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, ignoreNoDefaultLib, 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 + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + 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); // TODO: GH#18217 + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.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 (redirectedPath) { + filesByName.set(redirectedPath, file); + } + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = []; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; + if (!file.isDeclarationFile) { + fileNames.push(file.fileName); + } + } + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + if (sourceFiles) { + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(host, ref); + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !options.strictNullChecks) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_11 = function (file) { + if (normalizedRootNames.every(function (r) { return r !== file; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file = sourceFiles_4[_i]; + _loop_11(file); + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } + } + // 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 || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + // Out-of-bounds + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; // TODO: GH#18217 This function always returns `false`!` + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); /*@internal*/ var ts; (function (ts) { @@ -77818,8 +84661,10 @@ var ts; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. // The key in the map is source file's path. @@ -77840,7 +84685,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames var typeRootsWatches = ts.createMap(); return { @@ -77851,9 +84696,11 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, @@ -77874,6 +84721,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -77890,6 +84738,14 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { // Any file asked would have invalidated resolution @@ -77898,22 +84754,26 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return collected && collected.has(path); }; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -77945,13 +84805,16 @@ var ts; } var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { @@ -77962,7 +84825,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -77974,7 +84837,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -77988,7 +84851,7 @@ var ts; if (oldResolution === newResolution) { return true; } - if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + if (!oldResolution || !newResolution) { return false; } var oldResult = getResolutionWithResolvedFileName(oldResolution); @@ -78009,14 +84872,39 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { // Folder isnt at expected minimun levels @@ -78025,14 +84913,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, - // When root is "/" do not watch directories like: - // "/", "/user", "/user/username", "/user/username/folderAtRoot" - // When root is "c:/" do not watch directories like: - // "c:/", "c:/folderAtRoot" - dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -78041,7 +84921,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + // Always watch root directory recursively + return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } @@ -78051,42 +84932,56 @@ var ts; dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } - // If the directory is node_modules use it to watch + // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } + var nonRecursive = true; // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; - } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -78098,25 +84993,35 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, nonRecursive); } } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + // This is always recursive + setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 } } - function setDirectoryWatcher(dir, dirPath) { + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var updateResolution = resolutionHost.getCurrentProgram().getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -78157,22 +85062,17 @@ var ts; // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } - function createDirectoryWatcher(directory, dirPath) { + function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } - // If the files are added to project root or node_modules directory, always run through the invalidation process - // Otherwise run through invalidation only if adding to the immediate directory - if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { - if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { - resolutionHost.onInvalidatedResolution(); - } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); } - }, 1 /* Recursive */); + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } function removeResolutionsOfFileFromCache(cache, filePath) { // Deleted file, stop watching failed lookups for all the resolutions in the file @@ -78228,9 +85128,13 @@ var ts; // Resolution is invalidated if the resulting file name is same as the deleted file path function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 }); } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { var isChangedFailedLookupLocation; if (isCreatingWatchedDirectory) { @@ -78280,14 +85184,14 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile @@ -78340,9 +85244,369 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -/// -/// -/// +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + if (preferences === void 0) { preferences = {}; } + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); + if (!files) { + return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); + } + var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + } + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + function discoverProbableSymlinks(files, getCanonicalFileName, host) { + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + var result = ts.createMap(); + if (symlinks) { + var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); + var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); + while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { + resolvedParts.pop(); + originalParts.pop(); + } + result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); + } + } + return result; + } + function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { + var links = discoverProbableSymlinks(files, getCanonicalFileName, host); + var paths = ts.arrayFrom(links.keys()); + var options; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { + var path = paths_2[_i]; + var resolved = links.get(path); + if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + if (!options) + options = []; + options.push(option); + } + } + } + if (options) { + options.push(target); // Since these are speculative, we also include the original resolved name as a possibility + return options; + } + return [target]; + } + /** + * Looks for existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; + }); + }); + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var baseOptions = getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, cwd), getCanonicalFileName, host); + if (symlinks.length === 0) { + return baseOptions; + } + return ts.deduplicate(ts.concatenate(baseOptions, ts.flatMap(symlinks, function (importedFileName) { return getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, cwd), getCanonicalFileName, host); }))); + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { // TODO: GH#18217 + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // 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; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /*@internal*/ var ts; (function (ts) { @@ -78350,7 +85614,7 @@ var ts; getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - } : undefined; + } : undefined; // TODO: GH#18217 /** * Create a function that reports error by writing to the system and handles the formating of the diagnostic */ @@ -78367,18 +85631,38 @@ var ts; return function (diagnostic) { diagnostics[0] = diagnostic; system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); - diagnostics[0] = undefined; + diagnostics[0] = undefined; // TODO: GH#18217 }; } ts.createDiagnosticReporter = createDiagnosticReporter; + /** @internal */ + ts.nonClearingMessageCodes = [ + ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, + ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code + ]; + /** + * @returns Whether the screen was cleared. + */ function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && - diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && !options.extendedDiagnostics && - !options.diagnostics) { + !options.diagnostics && + !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { system.clearScreen(); + return true; } + return false; + } + /** @internal */ + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; } /** * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic @@ -78388,13 +85672,16 @@ var ts; function (diagnostic, newLine, options) { clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); system.write(output); } : function (diagnostic, newLine, options) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); - var output = new Date().toLocaleTimeString() + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); system.write(output); }; } @@ -78402,53 +85689,27 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onConfigFileDiagnostic = reportDiagnostic; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onConfigFileDiagnostic = undefined; - host.onUnRecoverableConfigFileDiagnostic = undefined; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); - var cwd = host.getCurrentDirectory(); - var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); - return configParseResult; - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { // First get and report any syntactic errors. - var diagnostics = program.getSyntacticDiagnostics().slice(); + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { reportSemanticDiagnostics = true; } } @@ -78471,6 +85732,9 @@ var ts; }); } } + if (reportSummary) { + reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -78495,6 +85759,7 @@ var ts; var host = system; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -78515,12 +85780,12 @@ var ts; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, - onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, @@ -78532,7 +85797,17 @@ var ts; return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } function emitFilesAndReportErrorUsingBuilder(builderProgram) { - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + var reportSummary = function (errorCount) { + if (errorCount === 1) { + onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); + } + else { + onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); + } + }; + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); } } /** @@ -78546,10 +85821,9 @@ var ts; * Creates the watch compiler host from system for config file in watch mode */ function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onConfigFileDiagnostic = reportDiagnostic; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -78569,7 +85843,7 @@ var ts; (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -78592,8 +85866,11 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var rootFileNames = host.rootFiles, compilerOptions = host.options; + var configFileSpecs; + var configFileParsingDiagnostics; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -78604,23 +85881,30 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onConfigFileDiagnostic: host.onConfigFileDiagnostic, onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic }; // From tsc we want to get already parsed result and hence check for rootFileNames - if (configFileName && !rootFileNames) { + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); parseConfigFile(); + newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectoryWorker = _b.watchDirectory; + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var newLine = updateNewLine(); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); } var compilerHost = { // Members for CompilerHost @@ -78637,7 +85921,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -78645,8 +85929,8 @@ var ts; // Members for ResolutionCacheHost toPath: toPath, getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: watchDirectory, - watchTypeRootsDirectory: watchDirectory, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, onInvalidatedResolution: scheduleProgramUpdate, onChangedAutomaticTypeDirectiveNames: function () { @@ -78670,7 +85954,6 @@ var ts; (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; - reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); @@ -78695,8 +85978,20 @@ var ts; // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { - return builderProgram; + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + hasChangedConfigFileParsingErrors = false; + } } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { // Compile the program if (watchLogLevel !== ts.WatchLogLevel.None) { writeLog("CreatingProgramWith::"); @@ -78705,10 +86000,11 @@ var ts; } var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -78729,11 +86025,6 @@ var ts; } missingFilePathsRequestedForRelease = undefined; } - if (host.afterProgramCreate) { - host.afterProgramCreate(builderProgram); - } - reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); - return builderProgram; } function updateRootFileNames(files) { ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); @@ -78741,7 +86032,7 @@ var ts; scheduleProgramUpdate(); } function updateNewLine() { - return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); } function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); @@ -78779,7 +86070,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); } } else { @@ -78793,7 +86084,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -78857,7 +86148,7 @@ var ts; } function reportWatchDiagnostic(message) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions); + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); } } // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch @@ -78870,6 +86161,7 @@ var ts; if (timerToUpdateProgram) { host.clearTimeout(timerToUpdateProgram); } + writeLog("Scheduling update"); timerToUpdateProgram = host.setTimeout(updateProgram, 250); } function scheduleProgramReload() { @@ -78891,9 +86183,15 @@ var ts; } } function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { - host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (result.fileNames.length) { + configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); + hasChangedConfigFileParsingErrors = true; + } + else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { + configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; // Update the program @@ -78912,11 +86210,14 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - var configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); - rootFileNames = configParseResult.fileNames; - compilerOptions = configParseResult.options; - configFileSpecs = configParseResult.configFileSpecs; - configFileWildCardDirectories = configParseResult.wildcardDirectories; + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); @@ -78933,11 +86234,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } } - function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(host, directory, cb, flags); - } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -78951,15 +86249,15 @@ var ts; } } function watchConfigFileWildCardDirectories() { - if (configFileWildCardDirectories) { - ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); } else if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); } } function watchWildcardDirectory(directory, flags) { - return watchDirectory(directory, function (fileOrDirectory) { + return watchDirectory(host, directory, function (fileOrDirectory) { ts.Debug.assert(!!configFileName); var fileOrDirectoryPath = toPath(fileOrDirectory); // Since the file existance changed, update the sourceFiles cache @@ -78979,7 +86277,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags); + }, flags, "Wild card directories"); } function ensureDirectoriesExist(directoryPath) { if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { @@ -79005,2042 +86303,1421 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); -/// -/// -/// -/// -/// var ts; (function (ts) { - /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; - /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + /** + * A FileMap maintains a normalized-key to value relationship + */ + function createFileMap() { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + getValueOrUndefined: getValueOrUndefined, + removeKey: removeKey, + getKeys: getKeys, + hasKey: hasKey + }; + function getKeys() { + return Object.keys(lookup); + } + function hasKey(fileName) { + return lookup.has(ts.normalizePath(fileName)); + } + function removeKey(fileName) { + lookup.delete(ts.normalizePath(fileName)); + } + function setValue(fileName, value) { + lookup.set(ts.normalizePath(fileName), value); + } + function getValue(fileName) { + var f = ts.normalizePath(fileName); + if (lookup.has(f)) { + return lookup.get(f); + } + else { + throw new Error("No value corresponding to " + fileName + " exists in this map"); + } + } + function getValueOrUndefined(fileName) { + var f = ts.normalizePath(fileName); + return lookup.get(f); + } + } + function createDependencyMapper() { + var childToParents = createFileMap(); + var parentToChildren = createFileMap(); + var allKeys = createFileMap(); + function addReference(childConfigFileName, parentConfigFileName) { + addEntry(childToParents, childConfigFileName, parentConfigFileName); + addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + } + function getReferencesTo(parentConfigFileName) { + return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + } + function getReferencesOf(childConfigFileName) { + return childToParents.getValueOrUndefined(childConfigFileName) || []; + } + function getKeys() { + return allKeys.getKeys(); + } + function addEntry(mapToAddTo, key, element) { + key = ts.normalizePath(key); + element = ts.normalizePath(element); + var arr = mapToAddTo.getValueOrUndefined(key); + if (arr === undefined) { + mapToAddTo.setValue(key, arr = []); + } + if (arr.indexOf(element) < 0) { + arr.push(element); + } + allKeys.setValue(key, true); + allKeys.setValue(element, true); + } + return { + addReference: addReference, + getReferencesTo: getReferencesTo, + getReferencesOf: getReferencesOf, + getKeys: getKeys + }; + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + function getOutputJavaScriptFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + if (!project.options.outFile) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(project.options.outFile); + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function createConfigFileCache(host) { + var cache = createFileMap(); + var configParseHost = ts.parseConfigHostFromCompilerHost(host); + function parseConfigFile(configFilePath) { + var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); + parsed.options.configFilePath = configFilePath; + cache.setValue(configFilePath, parsed); + return parsed; + } + function removeKey(configFilePath) { + cache.removeKey(configFilePath); + } + return { + parseConfigFile: parseConfigFile, + removeKey: removeKey + }; + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + function createBuildContext(options) { + var invalidatedProjects = createFileMap(); + var queuedProjects = createFileMap(); + var missingRoots = ts.createMap(); + return { + options: options, + projectStatus: createFileMap(), + unchangedOutputs: createFileMap(), + invalidatedProjects: invalidatedProjects, + missingRoots: missingRoots, + queuedProjects: queuedProjects + }; + } + ts.createBuildContext = createBuildContext; + var buildOpts = [ { - name: "help", - shortName: "h", - type: "boolean", - showInSimplifiedHelpView: true, + name: "verbose", + shortName: "v", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Print_this_message, - }, - { - name: "help", - shortName: "?", + description: ts.Diagnostics.Enable_verbose_logging, type: "boolean" }, { - name: "all", - type: "boolean", - showInSimplifiedHelpView: true, + name: "dry", + shortName: "d", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_all_compiler_options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" }, { - name: "version", - shortName: "v", - type: "boolean", - showInSimplifiedHelpView: true, + name: "force", + shortName: "f", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Print_the_compiler_s_version, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" }, { - name: "init", - type: "boolean", - showInSimplifiedHelpView: true, + name: "clean", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, - }, - { - name: "project", - shortName: "p", - type: "string", - isFilePath: true, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - paramType: ts.Diagnostics.FILE_OR_DIRECTORY, - description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, - }, - { - name: "pretty", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" }, { name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, - }, - // Basic - { - name: "target", - shortName: "t", - type: ts.createMapFromTemplate({ - es3: 0 /* ES3 */, - es5: 1 /* ES5 */, - es6: 2 /* ES2015 */, - es2015: 2 /* ES2015 */, - es2016: 3 /* ES2016 */, - es2017: 4 /* ES2017 */, - es2018: 5 /* ES2018 */, - esnext: 6 /* ESNext */, - }), - paramType: ts.Diagnostics.VERSION, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, - }, - { - name: "module", - shortName: "m", - type: ts.createMapFromTemplate({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - esnext: ts.ModuleKind.ESNext - }), - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, - }, - { - name: "lib", - type: "list", - element: { - name: "lib", - type: ts.createMapFromTemplate({ - // JavaScript only - "es5": "lib.es5.d.ts", - "es6": "lib.es2015.d.ts", - "es2015": "lib.es2015.d.ts", - "es7": "lib.es2016.d.ts", - "es2016": "lib.es2016.d.ts", - "es2017": "lib.es2017.d.ts", - "es2018": "lib.es2018.d.ts", - "esnext": "lib.esnext.d.ts", - // Host only - "dom": "lib.dom.d.ts", - "dom.iterable": "lib.dom.iterable.d.ts", - "webworker": "lib.webworker.d.ts", - "scripthost": "lib.scripthost.d.ts", - // ES2015 Or ESNext By-feature options - "es2015.core": "lib.es2015.core.d.ts", - "es2015.collection": "lib.es2015.collection.d.ts", - "es2015.generator": "lib.es2015.generator.d.ts", - "es2015.iterable": "lib.es2015.iterable.d.ts", - "es2015.promise": "lib.es2015.promise.d.ts", - "es2015.proxy": "lib.es2015.proxy.d.ts", - "es2015.reflect": "lib.es2015.reflect.d.ts", - "es2015.symbol": "lib.es2015.symbol.d.ts", - "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", - "es2016.array.include": "lib.es2016.array.include.d.ts", - "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", - "es2017.string": "lib.es2017.string.d.ts", - "es2017.intl": "lib.es2017.intl.d.ts", - "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", - "es2018.promise": "lib.es2018.promise.d.ts", - "es2018.regexp": "lib.es2018.regexp.d.ts", - "esnext.array": "lib.esnext.array.d.ts", - "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", - }), - }, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation - }, - { - name: "allowJs", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Allow_javascript_files_to_be_compiled - }, - { - name: "checkJs", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Report_errors_in_js_files - }, - { - name: "jsx", - type: ts.createMapFromTemplate({ - "preserve": 1 /* Preserve */, - "react-native": 3 /* ReactNative */, - "react": 2 /* React */ - }), - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, - }, - { - name: "declaration", - shortName: "d", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Generates_corresponding_d_ts_file, - }, - { - name: "emitDeclarationOnly", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Only_emit_d_ts_declaration_files, - }, - { - name: "sourceMap", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Generates_corresponding_map_file, - }, - { - name: "outFile", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.FILE, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - }, - { - name: "outDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - }, - { - name: "rootDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, - }, - { - name: "removeComments", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Do_not_emit_comments_to_output, - }, - { - name: "noEmit", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Do_not_emit_outputs, - }, - { - name: "importHelpers", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Import_emit_helpers_from_tslib - }, - { - name: "downlevelIteration", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 - }, - { - name: "isolatedModules", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule - }, - // Strict Type Checks - { - name: "strict", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_all_strict_type_checking_options - }, - { - name: "noImplicitAny", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, - }, - { - name: "strictNullChecks", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_null_checks - }, - { - name: "strictFunctionTypes", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_checking_of_function_types - }, - { - name: "strictPropertyInitialization", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes - }, - { - name: "noImplicitThis", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, - }, - { - name: "alwaysStrict", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file - }, - // Additional Checks - { - name: "noUnusedLocals", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_on_unused_locals, - }, - { - name: "noUnusedParameters", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_on_unused_parameters, - }, - { - name: "noImplicitReturns", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value - }, - { - name: "noFallthroughCasesInSwitch", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement - }, - // Module Resolution - { - name: "moduleResolution", - type: ts.createMapFromTemplate({ - node: ts.ModuleResolutionKind.NodeJs, - classic: ts.ModuleResolutionKind.Classic, - }), - paramType: ts.Diagnostics.STRATEGY, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - }, - { - name: "baseUrl", - type: "string", - isFilePath: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is - name: "paths", - type: "object", - isTSConfigOnly: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is - name: "rootDirs", - type: "list", - isTSConfigOnly: true, - element: { - name: "rootDirs", - type: "string", - isFilePath: true - }, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime - }, - { - name: "typeRoots", - type: "list", - element: { - name: "typeRoots", - type: "string", - isFilePath: true - }, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from - }, - { - name: "types", - type: "list", - element: { - name: "types", - type: "string" - }, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation - }, - { - name: "allowSyntheticDefaultImports", - type: "boolean", - 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: "esModuleInterop", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports - }, - { - 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", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - }, - { - name: "mapRoot", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - }, - { - name: "inlineSourceMap", - type: "boolean", - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file - }, - { - name: "inlineSources", - type: "boolean", - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set - }, - // Experimental - { - name: "experimentalDecorators", - type: "boolean", - category: ts.Diagnostics.Experimental_Options, - description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators - }, - { - name: "emitDecoratorMetadata", - type: "boolean", - category: ts.Diagnostics.Experimental_Options, - description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators - }, - // Advanced - { - name: "jsxFactory", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h - }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, - { - name: "out", - type: "string", - isFilePath: false, - // for correct behaviour, please use outFile - category: ts.Diagnostics.Advanced_Options, - paramType: ts.Diagnostics.FILE, - description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, - }, - { - name: "reactNamespace", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit - }, - { - name: "skipDefaultLibCheck", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files - }, - { - name: "charset", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_character_set_of_the_input_files - }, - { - name: "emitBOM", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files - }, - { - name: "locale", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us - }, - { - name: "newLine", - type: ts.createMapFromTemplate({ - crlf: 0 /* CarriageReturnLineFeed */, - lf: 1 /* LineFeed */ - }), - paramType: ts.Diagnostics.NEWLINE, - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - }, - { - name: "noErrorTruncation", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_truncate_error_messages - }, - { - name: "noLib", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts - }, - { - name: "noResolve", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files - }, - { - name: "stripInternal", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, - }, - { - name: "disableSizeLimit", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects - }, - { - name: "noImplicitUseStrict", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output - }, - { - name: "noEmitHelpers", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output - }, - { - name: "noEmitOnError", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, - }, - { - name: "preserveConstEnums", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code - }, - { - name: "declarationDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY, - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Output_directory_for_generated_declaration_files - }, - { - name: "skipLibCheck", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Skip_type_checking_of_declaration_files, - }, - { - name: "allowUnusedLabels", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_report_errors_on_unused_labels - }, - { - name: "allowUnreachableCode", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code - }, - { - name: "suppressExcessPropertyErrors", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, - }, - { - name: "suppressImplicitAnyIndexErrors", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, - }, - { - name: "forceConsistentCasingInFileNames", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, - { - name: "maxNodeModuleJsDepth", - type: "number", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files - }, - { - name: "noStrictGenericChecks", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, - }, - { - // A list of plugins to load in the language service - name: "plugins", - type: "list", - isTSConfigOnly: true, - element: { - name: "plugin", - type: "object" - }, - description: ts.Diagnostics.List_of_language_service_plugins + type: "boolean" } ]; - /* @internal */ - ts.typeAcquisitionDeclarations = [ - { - /* @deprecated typingOptions.enableAutoDiscovery - * Use typeAcquisition.enable instead. - */ - name: "enableAutoDiscovery", - type: "boolean", - }, - { - name: "enable", - type: "boolean", - }, - { - name: "include", - type: "list", - element: { - name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" + function performBuild(args, compilerHost, buildHost, system) { + var verbose = false; + var dry = false; + var force = false; + var clean = false; + var watch = false; + var projects = []; + for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { + var arg = args_6[_i]; + switch (arg.toLowerCase()) { + case "-v": + case "--verbose": + verbose = true; + continue; + case "-d": + case "--dry": + dry = true; + continue; + case "-f": + case "--force": + force = true; + continue; + case "--clean": + clean = true; + continue; + case "--watch": + case "-w": + watch = true; + continue; + case "--?": + case "-?": + case "--help": + ts.printHelp(buildOpts, "--build "); + return ts.ExitStatus.Success; } + // Not a flag, parse as filename + addProject(arg); } - ]; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - strict: true, - esModuleInterop: true - }; - var optionNameMapCache; - /* @internal */ - function convertEnableAutoDiscoveryToEnable(typeAcquisition) { - // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable - if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - return { - enable: typeAcquisition.enableAutoDiscovery, - include: typeAcquisition.include || [], - exclude: typeAcquisition.exclude || [] - }; + // Nonsensical combinations + if (clean && force) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } - return typeAcquisition; - } - ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; - function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; + if (clean && verbose) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { - optionNameMap.set(option.name.toLowerCase(), option); - if (option.shortName) { - shortOptionNames.set(option.shortName, option.name); - } - }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; - } - /* @internal */ - function createCompilerDiagnosticForInvalidCustomType(opt) { - return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); - } - ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; - function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); - } - /* @internal */ - function parseCustomTypeOption(opt, value, errors) { - return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); - } - ts.parseCustomTypeOption = parseCustomTypeOption; - /* @internal */ - function parseListTypeOption(opt, value, errors) { - if (value === void 0) { value = ""; } - value = trimString(value); - if (ts.startsWith(value, "-")) { + if (clean && watch) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (watch && dry) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + addProject("."); + } + var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); + if (clean) { + return builder.cleanAllProjects(); + } + if (watch) { + builder.buildAllProjects(); + builder.startWatching(); return undefined; } - if (value === "") { - return []; - } - var values = value.split(","); - switch (opt.element.type) { - case "number": - return ts.map(values, parseInt); - case "string": - return ts.map(values, function (v) { return v || ""; }); - default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return builder.buildAllProjects(); + function addProject(projectSpecification) { + var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); + var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); + if (!compilerHost.fileExists(refPath)) { + return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); + } + projects.push(refPath); } } - ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { - var options = {}; - var fileNames = []; - var errors = []; - parseStrings(commandLine); - return { - options: options, - fileNames: fileNames, - errors: errors - }; - function parseStrings(args) { - var i = 0; - while (i < args.length) { - var s = args[i]; - i++; - if (s.charCodeAt(0) === 64 /* at */) { - parseResponseFile(s.slice(1)); - } - else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); - if (opt) { - if (opt.isTSConfigOnly) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); - } - else { - // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); - } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i]); - i++; - break; - case "boolean": - // boolean flag has optional value true, false, others - var optValue = args[i]; - options[opt.name] = optValue !== "false"; - // consume next argument as boolean flag value - if (optValue === "false" || optValue === "true") { - i++; - } - break; - case "string": - options[opt.name] = args[i] || ""; - i++; - break; - case "list": - var result = parseListTypeOption(opt, args[i], errors); - options[opt.name] = result || []; - if (result) { - i++; - } - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - options[opt.name] = parseCustomTypeOption(opt, args[i], errors); - i++; - break; - } - } - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); - } - } - else { - fileNames.push(s); - } - } + ts.performBuild = performBuild; + /** + * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but + * can dynamically add/remove other projects based on changes on the rootNames' references + */ + function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { + if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { + throw new Error("Host must support timestamp APIs"); } - function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var configFileCache = createConfigFileCache(compilerHost); + var context = createBuildContext(defaultOptions); + var existingWatchersForWildcards = ts.createMap(); + var upToDateHost = { + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, + getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, + getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, + setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, + parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + }; + return { + buildAllProjects: buildAllProjects, + getUpToDateStatus: getUpToDateStatus, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProjects: buildInvalidatedProjects, + buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function startWatching() { + if (!system) + throw new Error("System host must be provided if using --watch"); + if (!system.watchFile || !system.watchDirectory || !system.setTimeout) + throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); + var graph = getGlobalDependencyGraph(); + if (!graph.buildQueue) { + // Everything is broken - we don't even know what to watch. Give up. return; } - var args = []; - var pos = 0; - while (true) { - while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) - pos++; - if (pos >= text.length) - break; - var start = pos; - if (text.charCodeAt(start) === 34 /* doubleQuote */) { - pos++; - while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) - pos++; - if (pos < text.length) { - args.push(text.substring(start + 1, pos)); - pos++; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); - } - } - else { - while (text.charCodeAt(pos) > 32 /* space */) - pos++; - args.push(text.substring(start, pos)); - } - } - parseStrings(args); - } - } - ts.parseCommandLine = parseCommandLine; - function getOptionFromName(optionName, allowShort) { - if (allowShort === void 0) { allowShort = false; } - optionName = optionName.toLowerCase(); - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; - // Try to translate short option names to their full equivalents. - if (allowShort) { - var short = shortOptionNames.get(optionName); - if (short !== undefined) { - optionName = short; - } - } - return optionNameMap.get(optionName); - } - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName, readFile) { - var textOrDiagnostic = tryReadFile(fileName, readFile); - return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; - } - ts.readConfigFile = readConfigFile; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileTextToJson(fileName, jsonText) { - var jsonSourceFile = ts.parseJsonText(fileName, jsonText); - return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), - error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined - }; - } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readJsonConfigFile(fileName, readFile) { - var textOrDiagnostic = tryReadFile(fileName, readFile); - return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; - } - ts.readJsonConfigFile = readJsonConfigFile; - function tryReadFile(fileName, readFile) { - var text; - try { - text = readFile(fileName); - } - catch (e) { - return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); - } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; - } - function commandLineOptionsToMap(options) { - return ts.arrayToMap(options, function (option) { return option.name; }); - } - var _tsconfigRootOptions; - function getTsconfigRootOptionsMap() { - if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { - name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { - name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); - } - return _tsconfigRootOptions; - } - /** - * Convert the json syntax tree into the json value - */ - function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - } - ts.convertToObject = convertToObject; - /** - * Convert the json syntax tree into the json value - */ - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; - } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, - /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 268 /* PropertyAssignment */) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); - continue; - } - if (element.questionToken) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - } - if (!isDoubleQuotedString(element.name)) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); - } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); - } - var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined") { - result[keyText] = value; - // Notify key value set, if user asked for it - if (jsonConversionNotifier && - // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || knownOptions === knownRootOptions)) { - var isValidOptionValue = isCompilerOptionsValue(option, value); - if (parentOption) { - if (isValidOptionValue) { - // Notify option set in the parent if its a valid option value - jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); - } - } - else if (knownOptions === knownRootOptions) { - if (isValidOptionValue) { - // Notify about the valid root key value being set - jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); - } - else if (!option) { - // Notify about the unknown root key value being set - jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); - } - } - } - } - } - return result; - } - function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); - } - function convertPropertyValueToJson(valueExpression, option) { - switch (valueExpression.kind) { - case 101 /* TrueKeyword */: - reportInvalidOptionValue(option && option.type !== "boolean"); - return true; - case 86 /* FalseKeyword */: - reportInvalidOptionValue(option && option.type !== "boolean"); - return false; - case 95 /* NullKeyword */: - reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for - return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: - if (!isDoubleQuotedString(valueExpression)) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); - } - reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); - var text = valueExpression.text; - if (option && !ts.isString(option.type)) { - var customOption = option; - // Validate custom option type - if (!customOption.type.has(text.toLowerCase())) { - errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); - } - } - return text; - case 8 /* NumericLiteral */: - reportInvalidOptionValue(option && option.type !== "number"); - return Number(valueExpression.text); - case 196 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { - break; // not valid JSON syntax - } - reportInvalidOptionValue(option && option.type !== "number"); - return -Number(valueExpression.operand.text); - case 182 /* ObjectLiteralExpression */: - reportInvalidOptionValue(option && option.type !== "object"); - var objectLiteralExpression = valueExpression; - // Currently having element option declaration in the tsconfig with type "object" - // determines if it needs onSetValidOptionKeyValueInParent callback or not - // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" - // that satifies it and need it to modify options set in them (for normalizing file paths) - // vs what we set in the json - // If need arises, we can modify this interface and callbacks as needed - if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); - } - else { - return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, - /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); - } - case 181 /* ArrayLiteralExpression */: - reportInvalidOptionValue(option && option.type !== "list"); - return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); - } - // Not in expected format - if (option) { - reportInvalidOptionValue(/*isError*/ true); - } - else { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); - } - return undefined; - function reportInvalidOptionValue(isError) { - if (isError) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); - } - } - } - function isDoubleQuotedString(node) { - return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); - } - } - function getCompilerOptionValueTypeString(option) { - return option.type === "list" ? - "Array" : - ts.isString(option.type) ? option.type : "string"; - } - function isCompilerOptionsValue(option, value) { - if (option) { - if (isNullOrUndefined(value)) - return true; // All options are undefinable/nullable - if (option.type === "list") { - return ts.isArray(value); - } - var expectedType = ts.isString(option.type) ? option.type : "string"; - return typeof value === expectedType; - } - } - /** - * Generate tsconfig configuration when running command line "--init" - * @param options commandlineOptions to be generated into tsconfig.json - * @param fileNames array of filenames to be generated into tsconfig.json - */ - /* @internal */ - function generateTSConfig(options, fileNames, newLine) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var compilerOptionsMap = serializeCompilerOptions(compilerOptions); - return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_6(name); - } - return result; - } - function getDefaultValueForOption(option) { - switch (option.type) { - case "number": - return 1; - case "boolean": - return true; - case "string": - return option.isFilePath ? "./" : ""; - case "list": - return []; - case "object": - return {}; - default: - return option.type.keys().next().value; - } - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - function writeConfigurations() { - // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); - for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { - var option = optionDeclarations_1[_i]; - var category = option.category; - if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); - } - } - // Serialize all options and their descriptions - var marginLength = 0; - var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; - categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); - } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); - for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { - var option = options_1[_i]; - var optionName = void 0; - if (compilerOptionsMap.has(option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); - } - else { - optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; - } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); - marginLength = Math.max(optionName.length, marginLength); - } - }); - // Write the output - var tab = makePadding(2); - var result = []; - result.push("{"); - result.push(tab + "\"compilerOptions\": {"); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); - } - if (fileNames.length) { - result.push(tab + "},"); - result.push(tab + "\"files\": ["); - for (var i = 0; i < fileNames.length; i++) { - result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); - } - result.push(tab + "]"); - } - else { - result.push(tab + "}"); - } - result.push("}"); - return result.join(newLine); - } - } - ts.generateTSConfig = generateTSConfig; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); - } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - /** - * Parse the contents of a config file (tsconfig.json). - * @param jsonNode The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); - } - ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; - /*@internal*/ - function setConfigFileInOptions(options, configFile) { - if (configFile) { - Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); - } - } - ts.setConfigFileInOptions = setConfigFileInOptions; - function isNullOrUndefined(x) { - // tslint:disable-next-line:no-null-keyword - return x === undefined || x === null; - } - function directoryOfCombinedPath(fileName, basePath) { - // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical - // until consistient casing errors are reported - return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); - } - /** - * Parse the contents of a config file from json or json source file (tsconfig.json). - * @param json The contents of the config file to parse - * @param sourceFile sourceFile corresponding to the Json - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - * @param resolutionStack Only present for backwards-compatibility. Should be empty. - */ - function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - if (existingOptions === void 0) { existingOptions = {}; } - if (resolutionStack === void 0) { resolutionStack = []; } - if (extraFileExtensions === void 0) { extraFileExtensions = []; } - ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); - var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); - var raw = parsedConfig.raw; - var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; - setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; - return { - options: options, - fileNames: fileNames, - typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), - raw: raw, - errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave, - configFileSpecs: spec - }; - function getFileNames() { - var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { - if (ts.isArray(raw.files)) { - filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); - } - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); - } - } - var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { - if (ts.isArray(raw.include)) { - includeSpecs = raw.include; - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); - } - } - var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { - if (ts.isArray(raw.exclude)) { - excludeSpecs = raw.exclude; - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); - } - } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; - } - } - if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; - } - var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(getErrorForNoInputFiles(result.spec, configFileName)); - } - return result; - } - function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { - if (!sourceFile) { - errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); - } - } - } - /*@internal*/ - function isErrorNoInputFiles(error) { - return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; - } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ - function getErrorForNoInputFiles(_a, configFileName) { - var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; - return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); - } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; - function isSuccessfulParsedTsconfig(value) { - return !!value.options; - } - /** - * This *just* extracts options/include/exclude/files out of a config file. - * It does *not* resolve the included files. - */ - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { - basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); - return { raw: json || convertToObject(sourceFile, errors) }; - } - var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); - if (ownConfig.extendedConfigPath) { - // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. - resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); - if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { - var baseRaw_1 = extendedConfig.raw; - var raw_1 = ownConfig.raw; - var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; - } - }; - setPropertyInRawIfNotUndefined("include"); - setPropertyInRawIfNotUndefined("exclude"); - setPropertyInRawIfNotUndefined("files"); - if (raw_1.compileOnSave === undefined) { - raw_1.compileOnSave = baseRaw_1.compileOnSave; - } - ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); - // TODO extend type typeAcquisition - } - } - return ownConfig; - } - function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { - if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } - var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - // typingOptions has been deprecated and is only supported for backward compatibility purposes. - // It should be removed in future releases - use typeAcquisition instead. - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); - json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - var extendedConfigPath; - if (json.extends) { - if (!ts.isString(json.extends)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - else { - var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); - } - } - return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; - } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { - var options = getDefaultCompilerOptions(configFileName); - var typeAcquisition, typingOptionstypeAcquisition; - var extendedConfigPath; - var optionsIterator = { - onSetValidOptionKeyValueInParent: function (parentOption, option, value) { - ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); - var currentOption = parentOption === "compilerOptions" ? - options : - parentOption === "typeAcquisition" ? - (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : - (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); - currentOption[option.name] = normalizeOptionValue(option, basePath, value); - }, - onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { - switch (key) { - case "extends": - var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { - return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + var _loop_12 = function (resolved) { + var cfg = configFileCache.parseConfigFile(resolved); + if (cfg) { + // Watch this file + system.watchFile(resolved, function () { + configFileCache.removeKey(resolved); + invalidateProjectAndScheduleBuilds(resolved); + }); + // Update watchers for wildcard directories + if (cfg.configFileSpecs) { + ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { + return system.watchDirectory(dir, function () { + invalidateProjectAndScheduleBuilds(resolved); + }, !!(flags & 1 /* Recursive */)); }); - return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; - } - }, - onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { - if (key === "excludes") { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + // Watch input files + for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { + var input = _a[_i]; + system.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved); + }); + } } + }; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + _loop_12(resolved); } - }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); - if (!typeAcquisition) { - if (typingOptionstypeAcquisition) { - typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? - { - enable: typingOptionstypeAcquisition.enableAutoDiscovery, - include: typingOptionstypeAcquisition.include, - exclude: typingOptionstypeAcquisition.exclude - } : - typingOptionstypeAcquisition; - } - else { - typeAcquisition = getDefaultTypeAcquisition(configFileName); + function invalidateProjectAndScheduleBuilds(resolved) { + invalidateProject(resolved); + system.setTimeout(buildInvalidatedProjects, 100); + system.setTimeout(buildDependentInvalidatedProjects, 3000); } } - return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; - } - function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { - extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + context = createBuildContext(opts); } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + var resolvedNames = resolveProjectNames(configFileNames); + if (resolvedNames === undefined) + return undefined; + return createDependencyGraph(resolvedNames); + } + function getGlobalDependencyGraph() { + return getBuildGraph(rootNames); + } + function getUpToDateStatus(project) { + return ts.getUpToDateStatus(upToDateHost, project); + } + function invalidateProject(configFileName) { + var resolved = resolveProjectName(configFileName); + if (resolved === undefined) { + // If this was a rootName, we need to track it as missing. + // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, + // if they exist + // TODO: do those things + return; + } + configFileCache.removeKey(resolved); + context.invalidatedProjects.setValue(resolved, true); + context.projectStatus.removeKey(resolved); + var graph = getGlobalDependencyGraph(); + if (graph) { + queueBuildForDownstreamReferences(resolved); + } + // Mark all downstream projects of this one needing to be built "later" + function queueBuildForDownstreamReferences(root) { + var deps = graph.dependencyMap.getReferencesTo(root); + for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { + var ref = deps_1[_i]; + // Can skip circular references + if (!context.queuedProjects.hasKey(ref)) { + context.queuedProjects.setValue(ref, true); + queueBuildForDownstreamReferences(ref); + } + } + } + } + function buildInvalidatedProjects() { + buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + } + function buildDependentInvalidatedProjects() { + buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + } + function buildSomeProjects(predicate) { + var resolvedNames = resolveProjectNames(rootNames); + if (resolvedNames === undefined) + return; + var graph = createDependencyGraph(resolvedNames); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + if (!predicate(next)) + continue; + var resolved = resolveProjectName(next); + if (!resolved) + continue; // ?? + var proj = configFileCache.parseConfigFile(resolved); + if (!proj) + continue; // ? + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + continue; + } + buildSingleProject(next); + } + } + function createDependencyGraph(roots) { + var temporaryMarks = {}; + var permanentMarks = {}; + var circularityReportStack = []; + var buildOrder = []; + var graph = createDependencyMapper(); + var hadError = false; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + if (hadError) { return undefined; } - } - return extendedConfigPath; - } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { - var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); - } - if (extendedResult.parseDiagnostics.length) { - errors.push.apply(errors, extendedResult.parseDiagnostics); - return undefined; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { - (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); - } - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } + return { + buildQueue: buildOrder, + dependencyMap: graph }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } - return extendedConfig; - var _a; - } - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { - var errors = []; - var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options: options, errors: errors }; - } - ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { - var errors = []; - var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options: options, errors: errors }; - } - ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } - : {}; - return options; - } - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); - return options; - } - function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = getDefaultTypeAcquisition(configFileName); - var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); - return options; - } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { - if (!jsonOptions) { - return; - } - var optionNameMap = commandLineOptionsToMap(optionDeclarations); - for (var id in jsonOptions) { - var opt = optionNameMap.get(id); - if (opt) { - defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); - } - else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + function visit(projPath, inCircularContext) { + if (inCircularContext === void 0) { inCircularContext = false; } + // Already visited + if (permanentMarks[projPath]) + return; + // Circular + if (temporaryMarks[projPath]) { + if (!inCircularContext) { + hadError = true; + buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + return; + } + } + temporaryMarks[projPath] = true; + circularityReportStack.push(projPath); + var parsed = configFileCache.parseConfigFile(projPath); + if (parsed === undefined) { + hadError = true; + return; + } + if (parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + if (resolvedRefPath === undefined) { + hadError = true; + break; + } + visit(resolvedRefPath, inCircularContext || ref.circular); + graph.addReference(projPath, resolvedRefPath); + } + } + circularityReportStack.pop(); + permanentMarks[projPath] = true; + buildOrder.push(projPath); } } - } - function convertJsonOption(opt, value, basePath, errors) { - if (isCompilerOptionsValue(opt, value)) { - var optType = opt.type; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); + function buildSingleProject(proj) { + if (context.options.dry) { + buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; } - else if (!ts.isString(optType)) { - return convertJsonOptionOfCustomType(opt, value, errors); + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = configFileCache.parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; } - return normalizeNonListOptionValue(opt, basePath, value); - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); - } - } - function normalizeOptionValue(option, basePath, value) { - if (isNullOrUndefined(value)) - return undefined; - if (option.type === "list") { - var listOption_1 = option; - if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { - return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + if (configFile.fileNames.length === 0) { + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; } - return value; - } - else if (!ts.isString(option.type)) { - return option.type.get(ts.isString(value) ? value.toLowerCase() : value); - } - return normalizeNonListOptionValue(option, basePath, value); - } - function normalizeNonListOptionValue(option, basePath, value) { - if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; + var programOptions = { + projectReferences: configFile.projectReferences, + host: compilerHost, + rootNames: configFile.fileNames, + options: configFile.options + }; + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + resultFlags |= BuildResultFlags.SyntaxErrors; + for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { + var diag = syntaxDiagnostics_1[_i]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); + return resultFlags; } - } - return value; - } - function convertJsonOptionOfCustomType(opt, value, errors) { - if (isNullOrUndefined(value)) - return undefined; - var key = value.toLowerCase(); - var val = opt.type.get(key); - if (val !== undefined) { - return val; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - function convertJsonOptionOfListType(option, values, basePath, errors) { - return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); - } - function trimString(s) { - return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); - } - /** - * Tests for a path that ends in a recursive directory wildcard. - * Matches **, \**, **\, and \**\, but not a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\* # matches the recursive directory wildcard "**". - * \/?$ # matches an optional trailing directory separator at the end of the string. - */ - var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path where .. appears after a recursive directory wildcard. - * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \.\. # matches a parent directory path component ".." - * ($|\/) # matches either the end of the string or a directory separator. - */ - var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; - /** - * Tests for a path containing a wildcard character in a directory component of the path. - * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * \/ # matches a directory separator. - * [^/]*? # matches any number of characters excluding directory separators (non-greedy). - * [*?] # matches either a wildcard character (* or ?) - * [^/]* # matches any number of characters excluding directory separators (greedy). - * \/ # matches a directory separator. - */ - var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; - /** - * Matches the portion of a wildcard path that does not contain wildcards. - * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * ^ # matches the beginning of the string - * [^*?]* # matches any number of non-wildcard characters - * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by - * # a path component that contains at least one wildcard character (* or ?). - */ - var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - /** - * Expands an array of file specifications. - * - * @param filesSpecs The literal file names to include. - * @param includeSpecs The wildcard file specifications to include. - * @param excludeSpecs The wildcard file specifications to exclude. - * @param basePath The base path for any relative file specifications. - * @param options Compiler options. - * @param host The host used to resolve files and directories. - * @param errors An array for diagnostic reporting. - */ - function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { - basePath = ts.normalizePath(basePath); - var validatedIncludeSpecs, validatedExcludeSpecs; - // The exclude spec list is converted into a regular expression, which allows us to quickly - // test whether a file or directory should be excluded before recursively traversing the - // file system. - if (includeSpecs) { - validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); - } - if (excludeSpecs) { - validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); - } - // Wildcard directories (provided as part of a wildcard path) are stored in a - // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), - // or a recursive directory. This information is used by filesystem watchers to monitor for - // new entries in these paths. - var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; - return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); - } - /** - * Gets the file names from the provided config file specs that contain, files, include, exclude and - * other properties needed to resolve the file names - * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details - * @param basePath The base path for any relative file specifications. - * @param options Compiler options. - * @param host The host used to resolve files and directories. - * @param extraFileExtensions optionaly file extra file extension information from host - */ - /* @internal */ - function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { - if (extraFileExtensions === void 0) { extraFileExtensions = []; } - basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; - // Literal file names (provided via the "files" array in tsconfig.json) are stored in a - // file map with a possibly case insensitive key. We use this map later when when including - // wildcard paths. - var literalFileMap = ts.createMap(); - // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a - // file map with a possibly case insensitive key. We use this map to store paths matched - // via wildcard, and to handle extension priority. - var wildcardFileMap = ts.createMap(); - var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; - // Rather than requery this for each file and filespec, we query the supported extensions - // once and store it on the expansion context. - var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - // Literal files are always included verbatim. An "include" or "exclude" specification cannot - // remove a literal file. - if (filesSpecs) { - for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { - var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + // Don't emit .d.ts if there are decl file errors + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + var declDiagnostics = program.getDeclarationDiagnostics(); + if (declDiagnostics.length) { + resultFlags |= BuildResultFlags.DeclarationEmitErrors; + for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { + var diag = declDiagnostics_1[_a]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); + return resultFlags; + } } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + resultFlags |= BuildResultFlags.TypeErrors; + for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { + var diag = semanticDiagnostics_1[_b]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); + return resultFlags; + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { + if (compilerHost.readFile(fileName) === content) { + // Check for unchanged .d.ts files + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + } + else { + anyDtsChanged = true; + } + } + compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + context.unchangedOutputs.setValue(fileName, priorChangeTime); + } + }); + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + context.projectStatus.setValue(proj, status); + return resultFlags; } - if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; - // If we have already included a literal or wildcard path with a - // higher priority extension, we should skip this file. - // - // This handles cases where we may encounter both .ts and - // .d.ts (or .js if "allowJs" is enabled) in the same - // directory when they are compilation outputs. - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + function updateOutputTimestamps(proj) { + if (context.options.dry) { + return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { + var file = outputs_1[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + } + compilerHost.setModifiedTime(file, now); + } + context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean(configFileNames) { + var resolvedNames = resolveProjectNames(configFileNames); + if (resolvedNames === undefined) + return undefined; + // Get the same graph for cleaning we'd use for building + var graph = createDependencyGraph(resolvedNames); + if (graph === undefined) + return undefined; + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = configFileCache.parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here continue; } - // We may have included a wildcard path with a lower priority - // extension due to the user-defined order of entries in the - // "include" array. If there is a lower priority extension in the - // same directory, we should remove it. - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); - if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { + var output = outputs_2[_b]; + if (compilerHost.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function getAllProjectsInScope() { + var resolvedNames = resolveProjectNames(rootNames); + if (resolvedNames === undefined) + return undefined; + var graph = createDependencyGraph(resolvedNames); + if (graph === undefined) + return undefined; + return graph.buildQueue; + } + function cleanAllProjects() { + var resolvedNames = getAllProjectsInScope(); + if (resolvedNames === undefined) { + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + var filesToDelete = getFilesToClean(resolvedNames); + if (filesToDelete === undefined) { + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (context.options.dry) { + buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + // Do this check later to allow --clean --dry to function even if the host can't delete files + if (!compilerHost.deleteFile) { + throw new Error("Host does not support deleting files"); + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + compilerHost.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); + if (compilerHost.fileExists(fullPath)) { + return fullPath; + } + var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); + if (compilerHost.fileExists(fullPathWithTsconfig)) { + return fullPathWithTsconfig; + } + buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); + return undefined; + } + function resolveProjectNames(configFileNames) { + var resolvedNames = []; + for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { + var name = configFileNames_1[_i]; + var resolved = resolveProjectName(name); + if (resolved === undefined) { + return undefined; + } + resolvedNames.push(resolved); + } + return resolvedNames; + } + function buildAllProjects() { + var graph = getGlobalDependencyGraph(); + if (graph === undefined) + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + var queue = graph.buildQueue; + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { + var next = queue_1[_i]; + var proj = configFileCache.parseConfigFile(next); + if (proj === undefined) { + anyFailed = true; + break; + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (!context.options.verbose) + return; + var names = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var name = _a[_i]; + names.push(name); + } + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + function relName(path) { + return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); + } + function reportVerbose(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + buildHost.verbose.apply(buildHost, [message].concat(args)); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!context.options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + /** + * Gets the UpToDateStatus for a project + */ + function getUpToDateStatus(host, project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(host, project); + if (host.setLastStatus) { + host.setLastStatus(project.options.configFilePath, actual); + } + return actual; + } + ts.getUpToDateStatus = getUpToDateStatus; + function getUpToDateStatusWorker(host, project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); } } } - var literalFiles = ts.arrayFrom(literalFileMap.values()); - var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences && host.parseConfigFile) { + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(host, ref); + var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date return { - fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories, - spec: spec + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName }; } - ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; - function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - return specs.filter(function (spec) { - var diag = specToDiagnostic(spec, allowTrailingRecursion); - if (diag !== undefined) { - errors.push(createDiagnostic(diag, spec)); + function getAllProjectOutputs(project) { + if (project.options.outFile) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); } - return diag === undefined; - }); - function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); } - } - 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 (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. - */ - function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { - // We watch a directory recursively if it contains a wildcard anywhere in a directory segment - // of the pattern: - // - // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively - // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added - // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler - // - // We watch a directory without recursion if it contains a wildcard in the file segment of - // the pattern: - // - // /a/b/* - Watch /a/b directly to catch any new file - // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z - var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); - var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; - if (include !== undefined) { - var recursiveKeys = []; - for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(spec)) { - continue; - } - var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); - if (match) { - var key = match.key, flags = match.flags; - var existingFlags = wildcardDirectories[key]; - if (existingFlags === undefined || existingFlags < flags) { - wildcardDirectories[key] = flags; - if (flags === 1 /* Recursive */) { - recursiveKeys.push(key); - } - } - } - } - // Remove any subpaths under an existing recursively watched directory. - for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } - } - } - } - } - return wildcardDirectories; - } - function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { - var match = wildcardDirectoryPattern.exec(spec); - if (match) { - return { - key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), - flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ - }; - } - if (ts.isImplicitGlob(spec)) { - return { key: spec, flags: 1 /* Recursive */ }; - } - return undefined; - } - /** - * Determines whether a literal or wildcard file has already been included that has a higher - * extension priority. - * - * @param file The path to the file. - * @param extensionPriority The priority of the extension. - * @param context The expansion context. - */ - function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { - var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); - for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { - var higherPriorityExtension = extensions[i]; - var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { - return true; - } - } - return false; - } - /** - * Removes files included via wildcard expansion with a lower extension priority that have - * already been included. - * - * @param file The path to the file. - * @param extensionPriority The priority of the extension. - * @param context The expansion context. - */ - function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { - var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); - for (var i = nextExtensionPriority; i < extensions.length; i++) { - var lowerPriorityExtension = extensions[i]; - var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); - wildcardFiles.delete(lowerPriorityPath); - } - } - /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. - * Also converts enum values back to strings. - */ - /* @internal */ - function convertCompilerOptionsForTelemetry(opts) { - var out = {}; - for (var key in opts) { - if (opts.hasOwnProperty(key)) { - var type = getOptionFromName(key); - if (type !== undefined) { // Ignore unknown options - out[key] = getOptionValueWithEmptyStrings(opts[key], type); - } - } - } - return out; - } - ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; - function getOptionValueWithEmptyStrings(value, option) { - switch (option.type) { - case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". - return ""; - case "string": // Could be any arbitrary string -- use empty string instead. - return ""; - case "number": // Allow numbers, but be sure to check it's actually a number. - return typeof value === "number" ? value : ""; - case "boolean": - return typeof value === "boolean" ? value : ""; - case "list": - var elementType_1 = option.element; - return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + break; default: - return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { - if (optionEnumValue === value) { - return optionStringValue; - } - }); + ts.assertTypeIsNever(status); } } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + /*@internal*/ + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + /* @internal */ + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return !availableVersion.greaterThan(cachedTyping.version); + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + /* @internal */ + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + /* @internal */ + JsTyping.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 + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function stringToInt(str) { + var n = parseInt(str, 10); + if (isNaN(n)) { + throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); + } + return n; + } + var isPrereleaseRegex = /^(.*)-next.\d+/; + var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; + var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; + var Semver = /** @class */ (function () { + function Semver(major, minor, patch, + /** + * If true, this is `major.minor.0-next.patch`. + * If false, this is `major.minor.patch`. + */ + isPrerelease) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.isPrerelease = isPrerelease; + } + Semver.parse = function (semver) { + var isPrerelease = isPrereleaseRegex.test(semver); + var result = Semver.tryParse(semver, isPrerelease); + if (!result) { + throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); + } + return result; + }; + Semver.fromRaw = function (_a) { + var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; + return new Semver(major, minor, patch, isPrerelease); + }; + // This must parse the output of `versionString`. + Semver.tryParse = function (semver, isPrerelease) { + // Per the semver spec : + // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." + var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; + var match = rgx.exec(semver); + return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; + }; + Object.defineProperty(Semver.prototype, "versionString", { + get: function () { + return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; + }, + enumerable: true, + configurable: true + }); + Semver.prototype.equals = function (sem) { + return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; + }; + Semver.prototype.greaterThan = function (sem) { + return this.major > sem.major || this.major === sem.major + && (this.minor > sem.minor || this.minor === sem.minor + && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease + && this.patch > sem.patch)); + }; + return Semver; + }()); + ts.Semver = Semver; })(ts || (ts = {})); var ts; (function (ts) { @@ -81070,6 +87747,8 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -81114,6 +87793,17 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -81209,6 +87899,8 @@ var ts; * */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -81291,36 +87983,36 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 148 /* Parameter */: - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 267 /* CatchClause */: - case 260 /* JsxAttribute */: + case 149 /* Parameter */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 272 /* CatchClause */: + case 265 /* JsxAttribute */: return 1 /* Value */; - case 147 /* TypeParameter */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 165 /* TypeLiteral */: + case 148 /* TypeParameter */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 166 /* TypeLiteral */: return 2 /* Type */; - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 271 /* EnumMember */: - case 233 /* ClassDeclaration */: + case 276 /* EnumMember */: + case 238 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -81330,26 +88022,26 @@ var ts; else { return 4 /* Namespace */; } - case 236 /* EnumDeclaration */: - case 245 /* NamedImports */: - case 246 /* ImportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - case 242 /* ImportDeclaration */: - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 241 /* EnumDeclaration */: + case 250 /* NamedImports */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 272 /* SourceFile */: + case 277 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 247 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -81368,6 +88060,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -81377,11 +88073,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 145 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 241 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 145 /* QualifiedName */) { + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -81393,27 +88089,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 145 /* QualifiedName */) { - while (root.parent && root.parent.kind === 145 /* QualifiedName */) { + if (root.parent.kind === 146 /* QualifiedName */) { + while (root.parent && root.parent.kind === 146 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 161 /* TypeReference */ && !isLastClause; + return root.parent.kind === 162 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 183 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 183 /* PropertyAccessExpression */) { + if (root.parent.kind === 187 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 205 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 266 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 233 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 234 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -81424,28 +88120,30 @@ var ts; switch (node.kind) { case 99 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 173 /* ThisType */: + case 176 /* ThisType */: return true; } switch (node.parent.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return true; - case 205 /* ExpressionWithTypeArguments */: + case 181 /* ImportType */: + return !node.parent.isTypeOf; + case 209 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 185 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 189 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 186 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 190 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -81453,7 +88151,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 226 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -81474,15 +88172,15 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 237 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -81492,22 +88190,24 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 268 /* PropertyAssignment */: - case 271 /* EnumMember */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 237 /* ModuleDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 273 /* PropertyAssignment */: + case 276 /* EnumMember */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 242 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return true; - case 177 /* LiteralType */: - return node.parent.parent.kind === 175 /* IndexedAccessType */; + case 180 /* LiteralType */: + return node.parent.parent.kind === 178 /* IndexedAccessType */; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -81517,7 +88217,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 291 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -81529,17 +88229,17 @@ var ts; return undefined; } switch (node.kind) { - case 272 /* SourceFile */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: + case 277 /* SourceFile */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return node; } } @@ -81547,48 +88247,48 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return "class" /* classElement */; - case 234 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 235 /* TypeAliasDeclaration */: return "type" /* typeElement */; - case 236 /* EnumDeclaration */: return "enum" /* enumElement */; - case 230 /* VariableDeclaration */: - return getKindOfVariableDeclaration(node); - case 180 /* BindingElement */: - return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - return "function" /* functionElement */; - case 155 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 156 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return "method" /* memberFunctionElement */; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return "property" /* memberVariableElement */; - case 159 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 158 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 157 /* CallSignature */: return "call" /* callSignatureElement */; - case 154 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 147 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 271 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 148 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 241 /* ImportEqualsDeclaration */: - case 246 /* ImportSpecifier */: - case 243 /* ImportClause */: - case 250 /* ExportSpecifier */: - case 244 /* NamespaceImport */: - return "alias" /* alias */; - case 291 /* JSDocTypedefTag */: + case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 240 /* TypeAliasDeclaration */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 198 /* BinaryExpression */: + case 241 /* EnumDeclaration */: return "enum" /* enumElement */; + case 235 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 184 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + return "function" /* functionElement */; + case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 158 /* CallSignature */: return "call" /* callSignatureElement */; + case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: + case 249 /* NamespaceImport */: + return "alias" /* alias */; + case 202 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -81612,11 +88312,13 @@ var ts; return "" /* unknown */; } } + case 71 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; } function getKindOfVariableDeclaration(v) { - return ts.isConst(v) + return ts.isVarConst(v) ? "const" /* constElement */ : ts.isLet(v) ? "let" /* letElement */ @@ -81631,7 +88333,7 @@ var ts; return true; case 71 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 148 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; default: return false; } @@ -81649,6 +88351,18 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsRangeExclusive(r1, r2) { + return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end); + } + ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; + function rangeContainsPositionExclusive(r, pos) { + return r.pos < pos && pos < r.end; + } + ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -81661,6 +88375,10 @@ var ts; return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); } ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { var start = Math.max(start1, start2); var end = Math.min(end1, end2); @@ -81676,46 +88394,46 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 182 /* ObjectLiteralExpression */: - case 178 /* ObjectBindingPattern */: - case 165 /* TypeLiteral */: - case 211 /* Block */: - case 238 /* ModuleBlock */: - case 239 /* CaseBlock */: - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 166 /* TypeLiteral */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 244 /* CaseBlock */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 186 /* NewExpression */: + case 190 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 185 /* CallExpression */: - case 189 /* ParenthesizedExpression */: - case 172 /* ParenthesizedType */: + case 189 /* CallExpression */: + case 193 /* ParenthesizedExpression */: + case 175 /* ParenthesizedType */: return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 191 /* ArrowFunction */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 159 /* ConstructSignature */: + case 158 /* CallSignature */: + case 195 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -81725,65 +88443,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 237 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); - case 215 /* IfStatement */: + case 242 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 220 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 181 /* ArrayLiteralExpression */: - case 179 /* ArrayBindingPattern */: - case 184 /* ElementAccessExpression */: - case 146 /* ComputedPropertyName */: - case 167 /* TupleType */: + case 185 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 188 /* ElementAccessExpression */: + case 147 /* ComputedPropertyName */: + case 168 /* TupleType */: return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 216 /* DoStatement */: + case 221 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 193 /* TypeOfExpression */: - case 192 /* DeleteExpression */: - case 194 /* VoidExpression */: - case 201 /* YieldExpression */: - case 202 /* SpreadElement */: + case 197 /* TypeOfExpression */: + case 196 /* DeleteExpression */: + case 198 /* VoidExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 248 /* ExportDeclaration */: - case 242 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -81796,11 +88514,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -81842,48 +88560,35 @@ var ts; return syntaxList; } ts.findContainingList = findContainingList; - /* Gets the token whose text has range [start, end) and - * position >= start and (position < end or (position === end && token is keyword or identifier)) + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) */ - function getTouchingWord(sourceFile, position, includeJsDocComment) { - return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); - } - ts.getTouchingWord = getTouchingWord; - /* Gets the token whose text has range [start, end) and position >= start - * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) - */ - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; /** * Returns the token if position is in [start, end). * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true */ - function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; outer: while (true) { - if (ts.isToken(current)) { - // exit early - return current; - } // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; - if (!includeJsDocComment && ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { // If this child begins after position, then all subsequent children will as well. break; @@ -81914,33 +88619,28 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); + var tokenAtPosition = getTokenAtPosition(file, position); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { // this is token that starts at the end of previous token - return it return n; } - var children = n.getChildren(); - for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { - var child = children_3[_i]; + return ts.firstDefined(n.getChildren(), function (child) { var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); - } - } - return undefined; + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); } } ts.findNextToken = findNextToken; @@ -81948,7 +88648,7 @@ var ts; * Finds the rightmost token satisfying `token.end <= position`, * excluding `JsxText` tokens containing only whitespace. */ - function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { var result = find(startNode || sourceFile); ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; @@ -81965,13 +88665,13 @@ var ts; // 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 start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || 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); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -81980,13 +88680,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 272 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -82000,19 +88700,19 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } /** * 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) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; 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])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -82020,7 +88720,7 @@ var ts; function isInString(sourceFile, position, previousToken) { if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { - var start = previousToken.getStart(); + var start = previousToken.getStart(sourceFile); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. @@ -82040,7 +88740,7 @@ var ts; * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); if (!token) { return false; } @@ -82052,17 +88752,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 263 /* JsxExpression */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 263 /* JsxExpression */) { + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 256 /* JsxClosingElement */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { return true; } return false; @@ -82072,7 +88772,7 @@ var ts; return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; } function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; @@ -82080,10 +88780,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -82096,21 +88797,38 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, // the tree could be of any shape depending on the tokens parsed before current node, // scanning of the previous identifier followed by "<" before current node would give us better result // Note that we also balance out the already provided type arguments, arrays, object literals while doing so var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -82124,28 +88842,30 @@ var ts; remainingLessThanTokens++; break; case 18 /* CloseBraceToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) - return false; + return undefined; break; case 20 /* CloseParenToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) - return false; + return undefined; break; case 22 /* CloseBracketToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) - return false; + return undefined; break; // Valid tokens in a type name. Skip. case 26 /* CommaToken */: + nTypeArguments++; + break; case 36 /* EqualsGreaterThanToken */: case 71 /* Identifier */: case 9 /* StringLiteral */: @@ -82165,41 +88885,35 @@ var ts; break; } // Invalid token in type - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) * @param predicate Additional predicate to test on the comment range. */ - function isInComment(sourceFile, position, tokenAtPosition, predicate) { - return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); } ts.isInComment = isInComment; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - // First, we have to see if this position actually landed in a comment. - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { + function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth() !== 0; + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { - var flags = ts.getCombinedModifierFlags(node); + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; var result = []; if (flags & 8 /* Private */) result.push("private" /* privateMemberModifier */); @@ -82213,28 +88927,21 @@ var ts; result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) result.push("export" /* exportedModifier */); - if (node.flags & 2097152 /* Ambient */) + if (node.flags & 4194304 /* Ambient */) result.push("declare" /* ambientModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 161 /* TypeReference */ || node.kind === 185 /* CallExpression */) { + if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 233 /* ClassDeclaration */ || node.kind === 234 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isWord(kind) { - return kind === 71 /* Identifier */ || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); - } function isComment(kind) { return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; } @@ -82252,9 +88959,9 @@ var ts; return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { + function isInsideTemplateLiteral(node, position, sourceFile) { return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); } ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { @@ -82274,18 +88981,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 181 /* ArrayLiteralExpression */ || - node.kind === 182 /* ObjectLiteralExpression */) { + if (node.kind === 185 /* ArrayLiteralExpression */ || + node.kind === 186 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 198 /* BinaryExpression */ && + if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 220 /* ForOfStatement */ && + if (node.parent.kind === 225 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -82293,40 +89000,41 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 268 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); } ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -82348,6 +89056,7 @@ var ts; 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, + 142 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -82355,11 +89064,9 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -82368,16 +89075,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -82390,23 +89087,241 @@ var ts; return result; } ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 147 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + 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; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + /* @internal */ + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 148 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -82435,23 +89350,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -82459,6 +89386,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -82568,18 +89496,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); @@ -82587,8 +89518,8 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 246 /* ImportSpecifier */ || location.parent.kind === 250 /* ExportSpecifier */) && + return !!location.parent && + (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -82615,7 +89546,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -82641,10 +89572,15 @@ var ts; * WARNING: This is an expensive operation and is only intended to be used in refactorings * and code fixes (because those are triggered by explicit user actions). */ - function getSynthesizedDeepClone(node) { - if (node === undefined) { - return undefined; - } + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWorker(node) { var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. @@ -82655,9 +89591,7 @@ var ts; else if (ts.isNumericLiteral(clone_7)) { clone_7.numericLiteralFlags = node.numericLiteralFlags; } - clone_7.pos = node.pos; - clone_7.end = node.end; - return clone_7; + return ts.setTextRange(clone_7, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -82665,9 +89599,9 @@ var ts; visited.parent = undefined; return visited; } - ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepClones(nodes) { - return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); } ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** @@ -82675,29 +89609,102 @@ var ts; */ /* @internal */ function suppressLeadingAndTrailingTrivia(node) { - ts.Debug.assertDefined(node); - suppress(node, 512 /* NoLeadingComments */, getFirstChild); - suppress(node, 1024 /* NoTrailingComments */, getLastChild); - function suppress(node, flag, getChild) { - ts.addEmitFlags(node, flag); - var child = getChild(node); - if (child) - suppress(child, flag, getChild); - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + /* @internal */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + /* @internal */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - function getLastChild(node) { - var lastChild; - node.forEachChild(function (child) { lastChild = child; }, function (children) { - // As an optimization, jump straight to the end of the list. - if (children.length) { - lastChild = ts.last(children); + /* @internal */ + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + /* @internal */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + 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, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); }); - return lastChild; + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; } })(ts || (ts = {})); var ts; @@ -82941,7 +89948,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -82950,8 +89957,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -82978,6 +89985,8 @@ var ts; case 9 /* text */: case 17 /* parameterName */: return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); } } /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ @@ -83128,10 +90137,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -83225,6 +90234,7 @@ var ts; case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; case 23 /* jsxText */: return "jsx text" /* jsxText */; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); } } function convertClassificationsToSpans(classifications) { @@ -83342,20 +90352,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 287 /* JSDocParameterTag */: + case 296 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: processElement(tag.typeExpression); + pos = tag.end; break; - case 288 /* JSDocReturnTag */: + case 297 /* JSDocReturnTag */: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -83438,22 +90450,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 255 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -83479,19 +90491,20 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 230 /* VariableDeclaration */ || - token.parent.kind === 151 /* PropertyDeclaration */ || - token.parent.kind === 148 /* Parameter */ || - token.parent.kind === 260 /* JsxAttribute */) { + if (parent.kind === 235 /* VariableDeclaration */ || + parent.kind === 152 /* PropertyDeclaration */ || + parent.kind === 149 /* Parameter */ || + parent.kind === 265 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 198 /* BinaryExpression */ || - token.parent.kind === 196 /* PrefixUnaryExpression */ || - token.parent.kind === 197 /* PostfixUnaryExpression */ || - token.parent.kind === 199 /* ConditionalExpression */) { + if (parent.kind === 202 /* BinaryExpression */ || + parent.kind === 200 /* PrefixUnaryExpression */ || + parent.kind === 201 /* PostfixUnaryExpression */ || + parent.kind === 203 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -83501,7 +90514,8 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 260 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + // TODO: GH#18217 + return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -83517,32 +90531,32 @@ var ts; else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 148 /* Parameter */: + case 149 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -83578,29 +90592,43 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); - var scriptPath = node.getSourceFile().path; + var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { - // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option @@ -83611,25 +90639,25 @@ var ts; // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; - }); + }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } return result; } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -83639,13 +90667,16 @@ var ts; * Remove the basename from the path. Note that we don't use the basename to filter completions; * the client is responsible for refining completions. */ - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { // Enumerate the available files if possible @@ -83658,19 +90689,19 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script" /* scriptElement */, span)); + result.push(nameAndKind(foundFile, "script" /* scriptElement */)); }); } // If possible, get folder completion as well @@ -83679,7 +90710,9 @@ var ts; for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createPathCompletion(directoryName, "directory" /* directory */, span)); + if (directoryName !== "@types") { + result.push(nameAndKind(directoryName, "directory" /* directory */)); + } } } } @@ -83692,56 +90725,76 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_13 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_13(name, kind); } } } } - if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { - ts.forEachAncestorDirectory(scriptPath, function (ancestor) { - var nodeModules = ts.combinePaths(ancestor, "node_modules"); - if (host.directoryExists(nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - } - }); + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { + var ambientName = _d[_c]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { - var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_14 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + } + }; + for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { + var moduleName = _f[_e]; + _loop_14(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + } + }); + } } return result; } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); - if (!ts.startsWith(fragment, pathPrefix)) { - return [{ name: pathPrefix, kind: "directory" /* directory */ }]; + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; } - var remainingFragment = fragment.slice(pathPrefix.length); - return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { if (!host.readDirectory) { @@ -83753,12 +90806,13 @@ var ts; } // The prefix has two effective parts: the directory path and the base component after the filepath that is not a // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); @@ -83783,45 +90837,21 @@ var ts; function removeLeadingDirectorySeparator(path) { return path[0] === ts.directorySeparator ? path.slice(1) : path; } - function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { - // Check If this is a nested module - var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); - var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { // Get modules that the type checker picked up - var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); // Nested modules of the form "module-name/sub" need to be adjusted to only return the string // after the last '/' that appears in the fragment because that's where the replacement span // starts - if (isNestedModule) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { - return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); - }); + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } - if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { - for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { - var visibleModule = _a[_i]; - if (!isNestedModule) { - nonRelativeModuleNames.push(visibleModule.moduleName); - } - else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { - var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (nestedFiles) { - for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { - var f = nestedFiles_1[_b]; - f = ts.normalizePath(f); - var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModuleNames.push(nestedModule); - } - } - } - } - } - return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return nonRelativeModuleNames; } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { @@ -83834,23 +90864,13 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - switch (kind) { - case "path": { - // Give completions for a relative path - var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); - } - case "types": { - // Give completions based on the typings available - var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); - return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); - } - default: - return undefined; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); @@ -83898,7 +90918,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); seen.set(moduleName, true); } } @@ -83915,43 +90935,18 @@ var ts; return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var contents = tryReadingPackageJson(packageJson); - if (!contents) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - // Provide completions for all non @types dependencies - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(contents[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; for (var dep in dependencies) { if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { result.push(dep); @@ -83959,12 +90954,15 @@ var ts; } } } + return result; } - // Replace everything after the last directory seperator that appears + // Replace everything after the last directory separator that appears function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -83975,15 +90973,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. - // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment @@ -84004,9 +90993,6 @@ var ts; function tryReadDirectory(host, path, extensions, exclude, include) { return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray; } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } function tryFileExists(host, path) { return tryIOAndConsumeErrors(host, host.fileExists, path); } @@ -84015,7 +91001,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -84028,45 +91014,71 @@ var ts; catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } + function containsSlash(fragment) { + return ts.stringContains(fragment, ts.directorySeparator); + } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) + return undefined; // TODO: GH#18217 if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } switch (completionData.kind) { case 0 /* Data */: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1 /* JsDocTagName */: // If the current position is a jsDoc tag name, only tag names should be provided for completion return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); @@ -84080,7 +91092,7 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -84089,12 +91101,12 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "var" /* variableElement */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -84112,33 +91124,35 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -84148,8 +91162,15 @@ var ts; if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } + for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { + var literal = literals_1[_i]; + entries.push(createCompletionEntryForLiteral(literal)); + } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -84177,7 +91198,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var completionNameForLiteral = JSON.stringify; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -84185,27 +91210,27 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { - if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; - } - else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); - // If the text after the '.' starts with this name, write over it. Else, add new text. - var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; - replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); - } - if (isJsxInitializer) { - if (insertText === undefined) - insertText = name; - insertText = "{" + insertText + "}"; - if (typeof isJsxInitializer !== "boolean") { - replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); - } + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -84221,15 +91246,23 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, }; } - function quote(text) { - // TODO: GH#20619 Use configured quote style - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -84239,19 +91272,19 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -84260,7 +91293,7 @@ var ts; continue; } // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 uniques.set(name, true); } entries.push(entry); @@ -84306,22 +91339,24 @@ var ts; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { switch (node.parent.kind) { - case 177 /* LiteralType */: + case 180 /* LiteralType */: switch (node.parent.parent.kind) { - case 161 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent), typeChecker) }; - case 175 /* IndexedAccessType */: + case 162 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + case 181 /* ImportType */: + return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; default: return undefined; } - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -84335,11 +91370,10 @@ var ts; // foo({ // '/*completion position*/' // }); - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1 /* Properties */, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); - case 184 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression @@ -84348,29 +91382,23 @@ var ts; // } // let a: A; // a['/*completion position*/'] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } - case 185 /* CallExpression */: - case 186 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo_1 = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + case 189 /* CallExpression */: + case 190 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - if (argumentInfo_1) { - var candidates = []; - typeChecker.getResolvedSignature(argumentInfo_1.invocation, candidates, argumentInfo_1.argumentCount); - var uniques_1 = ts.createMap(); - return { kind: 2 /* Types */, types: ts.flatMap(candidates, function (candidate) { return getStringLiteralTypes(typeChecker.getParameterType(candidate, argumentInfo_1.argumentIndex), typeChecker, uniques_1); }) }; - } - return fromContextualType(); + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - case 252 /* ExternalModuleReference */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 257 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); @@ -84384,30 +91412,50 @@ var ts; function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } - function getStringLiteralTypes(type, typeChecker, uniques) { + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 32768 /* TypeParameter */) { - type = type.getConstraint(); - } - return type && type.flags & 131072 /* Union */ - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, typeChecker, uniques); }) - : type && type.flags & 32 /* StringLiteral */ && !(type.flags & 256 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) ? [type] : ts.emptyArray; } - function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { - var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new @@ -84415,21 +91463,31 @@ var ts; return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); - return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + } // Compute all the completion symbols again. - var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); switch (symbolCompletion.type) { case "request": { var request = symbolCompletion.request; @@ -84446,44 +91504,61 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); - var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; - return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } - case "none": { + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { - return { - name: name, - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined, - codeActions: undefined, - source: undefined, - }; - } - return undefined; - } + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { - var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; @@ -84503,26 +91578,28 @@ var ts; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); - function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - // Don't include make a recommended completion for an abstract class - return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); } - function getContextualType(currentToken, position, sourceFile, checker) { - var parent = currentToken.parent; - switch (currentToken.kind) { + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { case 71 /* Identifier */: - return getContextualTypeFromParent(currentToken, checker); + return getContextualTypeFromParent(previousToken, checker); case 58 /* EqualsToken */: switch (parent.kind) { - case 230 /* VariableDeclaration */: - return checker.getContextualType(parent.initializer); - case 198 /* BinaryExpression */: + case 235 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 202 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -84532,30 +91609,30 @@ var ts; case 73 /* CaseKeyword */: return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 253 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) + : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) - : checker.getContextualType(currentToken); + : checker.getContextualType(previousToken); } } function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 186 /* NewExpression */: + case 190 /* NewExpression */: return checker.getContextualType(parent); - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 264 /* CaseClause */: + case 269 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -84571,15 +91648,15 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 272 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; @@ -84622,11 +91699,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 274 /* JSDocTypeExpression */) { - currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 292 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -84644,16 +91721,16 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. @@ -84665,7 +91742,7 @@ var ts; var isRightOfOpenTag = false; var isStartingCloseTag = false; var isJsxInitializer = false; - var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 + var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -84676,13 +91753,17 @@ var ts; if (contextToken.kind === 23 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: node = parent.left; break; + case 181 /* ImportType */: + case 212 /* MetaProperty */: + node = parent; + break; default: // There is nothing that precedes the dot, so this likely just a stray character // or leading into a '...' token. Just bail out instead. @@ -84693,7 +91774,7 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 183 /* PropertyAccessExpression */) { + if (parent && parent.kind === 187 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -84701,45 +91782,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 253 /* JsxElement */ || currentToken.parent.kind === 255 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { location = currentToken; } break; case 41 /* SlashToken */: - if (currentToken.parent.kind === 254 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 198 /* BinaryExpression */: - if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { - // It has a left-hand side, so we're not in an opening JSX tag. + case 202 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 254 /* JsxSelfClosingElement */: - case 253 /* JsxElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: + case 260 /* JsxOpeningElement */: if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: switch (previousToken.kind) { case 58 /* EqualsToken */: isJsxInitializer = true; break; case 71 /* Identifier */: - if (previousToken !== parent.name) { + // For `
= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23 /* DotToken */: - return containingNodeKind === 179 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: - return containingNodeKind === 180 /* BindingElement */; // var {x :html| + return containingNodeKind === 184 /* BindingElement */; // var {x :html| case 21 /* OpenBracketToken */: - return containingNodeKind === 179 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: - return containingNodeKind === 267 /* CatchClause */ || + return containingNodeKind === 272 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 236 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 165 /* TypeLiteral */; // const x : { | - case 25 /* SemicolonToken */: - return containingNodeKind === 150 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 165 /* TypeLiteral */); // const x : { a; | + return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: - return containingNodeKind === 233 /* ClassDeclaration */ || // class A< | - containingNodeKind === 203 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 235 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | + containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: - return containingNodeKind === 148 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 179 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 149 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: - return containingNodeKind === 246 /* ImportSpecifier */ || - containingNodeKind === 250 /* ExportSpecifier */ || - containingNodeKind === 244 /* NamespaceImport */; + return containingNodeKind === 251 /* ImportSpecifier */ || + containingNodeKind === 255 /* ExportSpecifier */ || + containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } // falls through @@ -85576,8 +92616,7 @@ var ts; } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here - if (isClassMemberCompletionKeywordText(contextToken.getText()) && - isFromClassElementDeclaration(contextToken)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { @@ -85586,28 +92625,28 @@ var ts; // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 75 /* ClassKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 83 /* EnumKeyword */: + case 89 /* FunctionKeyword */: + case 109 /* InterfaceKeyword */: + case 110 /* LetKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 115 /* StaticKeyword */: + case 104 /* VarKeyword */: + case 116 /* YieldKeyword */: return true; } return ts.isDeclarationName(contextToken) @@ -85617,7 +92656,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 154 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -85626,28 +92665,6 @@ var ts; } return false; } - /** - * Filters out completion suggestions for named imports or exports. - * - * @param exportsOfModule The list of symbols which a module exposes. - * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. - * - * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports - * do not occur at the current position and have not otherwise been typed. - */ - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createUnderscoreEscapedMap(); - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (isCurrentlyEditingNode(element)) { - continue; - } - var name = element.propertyName || element.name; - existingImportsOrExports.set(name.escapedText, true); - } - return exportsOfModule.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existingImportsOrExports.get(e.escapedName); }); - } /** * Filters out completion suggestions for named imports or exports. * @@ -85662,12 +92679,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 268 /* PropertyAssignment */ && - m.kind !== 269 /* ShorthandPropertyAssignment */ && - m.kind !== 180 /* BindingElement */ && - m.kind !== 153 /* MethodDeclaration */ && - m.kind !== 155 /* GetAccessor */ && - m.kind !== 156 /* SetAccessor */) { + if (m.kind !== 273 /* PropertyAssignment */ && + m.kind !== 274 /* ShorthandPropertyAssignment */ && + m.kind !== 184 /* BindingElement */ && + m.kind !== 154 /* MethodDeclaration */ && + m.kind !== 156 /* GetAccessor */ && + m.kind !== 157 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -85675,7 +92692,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 180 /* BindingElement */ && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -85686,9 +92703,9 @@ var ts; // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. var name = ts.getNameOfDeclaration(m); - existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } - existingMemberNames.set(existingName, true); + existingMemberNames.set(existingName, true); // TODO: GH#18217 } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } @@ -85697,15 +92714,15 @@ var ts; * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 151 /* PropertyDeclaration */ && - m.kind !== 153 /* MethodDeclaration */ && - m.kind !== 155 /* GetAccessor */ && - m.kind !== 156 /* SetAccessor */) { + if (m.kind !== 152 /* PropertyDeclaration */ && + m.kind !== 154 /* MethodDeclaration */ && + m.kind !== 156 /* GetAccessor */ && + m.kind !== 157 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -85717,10 +92734,7 @@ var ts; continue; } // do not filter it out if the static presence doesnt match - var mIsStatic = ts.hasModifier(m, 32 /* Static */); - var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); - if ((mIsStatic && !currentElementIsStatic) || - (!mIsStatic && currentElementIsStatic)) { + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -85728,23 +92742,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - addPropertySymbols(baseSymbols, 8 /* Private */); - addPropertySymbols(implementingTypeSymbols, 24 /* NonPublicAccessibilityModifier */); - return result; - function addPropertySymbols(properties, inValidModifierFlags) { - for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -85760,14 +92762,14 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 260 /* JsxAttribute */) { + if (attr.kind === 265 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -85790,7 +92792,7 @@ var ts; // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: - case 1 /* Global */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; case 5 /* None */: @@ -85804,7 +92806,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 144 /* LastKeyword */; i++) { + for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -85823,62 +92825,36 @@ var ts; return kind !== 140 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* ConstructorParameterKeywords */: - return isConstructorParameterCompletionKeyword(kind); - case 3 /* FunctionLikeBodyKeywords */: - return isFunctionLikeBodyCompletionKeyword(kind); - case 4 /* TypeKeywords */: + case 2 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 3 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 4 /* FunctionLikeBodyKeywords */: + return !isClassMemberCompletionKeyword(kind); + case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132 /* ReadonlyKeyword */; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: case 123 /* ConstructorKeyword */: - case 132 /* ReadonlyKeyword */: case 125 /* GetKeyword */: case 136 /* SetKeyword */: case 120 /* AsyncKeyword */: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: - case 117 /* AbstractKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 140 /* UndefinedKeyword */: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -85893,48 +92869,106 @@ var ts; } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { - var jsDoc = getJsDocHavingNode(node).jsDoc; - if (!jsDoc) - return undefined; - for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { - var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; - if (!tags || position < pos || position > end) - continue; - for (var i = tags.length - 1; i >= 0; i--) { - var tag = tags[i]; - if (position >= tag.pos) { - return tag; - } - } - } + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); } - function getJsDocHavingNode(node) { - if (!ts.isToken(node)) - return node; - switch (node.kind) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - return node.parent.parent; - default: - return node.parent; - } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 32764 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); } /** * Gets all properties on a type, but if that type is a union of several types, * excludes array-like types or callable/constructable types. */ - function getPropertiesForCompletion(type, checker, isForAccess) { - if (!(type.flags & 131072 /* Union */)) { - return ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 303 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25 /* SemicolonToken */: // class c {getValue(): number; | } + case 18 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17 /* OpenBraceToken */: // class c { | + case 26 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + return true; + default: + return false; } - var types = type.types; - // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - var filteredTypes = isForAccess ? types : types.filter(function (memberType) { - return !(memberType.flags & 16382 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); - }); - return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -85944,7 +92978,7 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; @@ -85965,13 +92999,21 @@ var ts; }; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; - return ({ fileName: fileName, highlightSpans: highlightSpans }); + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; }); } function getSyntacticDocumentHighlights(node, sourceFile) { @@ -86009,6 +93051,12 @@ var ts; case 125 /* GetKeyword */: case 136 /* SetKeyword */: return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); + case 121 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 120 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 116 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) @@ -86036,7 +93084,7 @@ var ts; } else if (ts.isTryStatement(node)) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } // Do not cross function boundaries. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -86050,7 +93098,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 272 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -86077,48 +93125,41 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 225 /* SwitchStatement */: - if (statement.kind === 221 /* ContinueStatement */) { + case 230 /* SwitchStatement */: + if (statement.kind === 226 /* ContinueStatement */) { return false; } // falls through - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. // TODO: GH#20090 - return (ts.isFunctionLike(node) && "quit"); + return ts.isFunctionLike(node) && "quit"; } }); } function getModifierOccurrences(modifier, declaration) { - var modifierFlag = ts.modifierToFlag(modifier); - return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); - ts.Debug.assert(!!mod); - return mod; - } - }); + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); } function getNodesToSearchForModifier(declaration, modifierFlag) { // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 238 /* ModuleBlock */: - case 272 /* SourceFile */: - case 211 /* Block */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: + case 216 /* Block */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -86126,13 +93167,12 @@ var ts; else { return container.statements; } - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 232 /* FunctionDeclaration */: { + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -86165,7 +93205,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 216 /* DoStatement */) { + if (loopNode.kind === 221 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { @@ -86185,13 +93225,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -86256,6 +93296,48 @@ var ts; }); return keywords; } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } function getIfElseOccurrences(ifStatement, sourceFile) { var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; @@ -86323,6 +93405,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -86336,7 +93423,7 @@ var ts; if (!bucket && createIfMissing) { buckets.set(key, bucket = ts.createMap()); } - return bucket; + return bucket; // TODO: GH#18217 } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { @@ -86345,8 +93432,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -86376,13 +93462,27 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -86391,7 +93491,10 @@ var ts; // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -86402,6 +93505,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -86419,6 +93523,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -86426,11 +93537,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -86439,10 +93551,10 @@ var ts; var FindAllReferences; (function (FindAllReferences) { /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ - function createImportTracker(sourceFiles, checker, cancellationToken) { + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); return function (exportSymbol, exportInfo, isForRename) { - var _a = getImportersForExport(sourceFiles, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); }; } @@ -86459,7 +93571,7 @@ var ts; ImportExport[ImportExport["Export"] = 1] = "Export"; })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ - function getImportersForExport(sourceFiles, allDirectImports, _a, checker, cancellationToken) { + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; var markSeenDirectImport = ts.nodeSeenTracker(); var markSeenIndirectUser = ts.nodeSeenTracker(); @@ -86476,7 +93588,7 @@ var ts; // Module augmentations may use this module's exports without importing it. for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl)) { + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { addIndirectUser(decl); } } @@ -86491,12 +93603,13 @@ var ts; if (!markSeenDirectImport(direct)) { continue; } - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 230 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 71 /* Identifier */) { directImports.push(name); @@ -86507,26 +93620,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 241 /* ImportEqualsDeclaration */: - handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); + case 71 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 246 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: + directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 244 /* NamespaceImport */) { - handleNamespaceImport(direct, namedBindings.name); + if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } - else if (ts.isDefaultImport(direct)) { - var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - if (!isAvailableThroughGlobal) { - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports - } - directImports.push(direct); - } - else { - directImports.push(direct); + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -86536,18 +93645,24 @@ var ts; directImports.push(direct); } break; + case 181 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); } } } } - function handleNamespaceImport(importDeclaration, name, isReExport) { + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { if (exportKind === 2 /* ExportEquals */) { // This is a direct import, not import-as-namespace. - directImports.push(importDeclaration); + if (!alreadyAddedDirect) + directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 272 /* SourceFile */ || sourceFileLike.kind === 237 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -86560,7 +93675,7 @@ var ts; ts.Debug.assert(!isAvailableThroughGlobal); var isNew = markSeenIndirectUser(sourceFileLike); if (isNew) { - indirectUserDeclarations.push(sourceFileLike); + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 } return isNew; } @@ -86602,7 +93717,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 241 /* ImportEqualsDeclaration */) { + if (decl.kind === 246 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -86612,40 +93727,48 @@ var ts; handleNamespaceImportLike(decl); return; } + if (decl.kind === 181 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } // Ignore if there's a grammar error if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 248 /* ExportDeclaration */) { + if (decl.kind === 253 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } - var importClause = decl.importClause; - if (!importClause) { - return; - } - var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 244 /* NamespaceImport */) { - handleNamespaceImportLike(namedBindings.name); - return; - } - if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); - } - else { - // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals - var name = importClause.name; - // If a default import has the same name as the default export, allow to rename it. - // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name); - addSearch(name, defaultImportAlias); - } - // 'default' might be accessed as a named import `{ default as foo }`. - if (!isForRename && exportKind === 1 /* Default */) { - searchForNamedImport(namedBindings); + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 249 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 250 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); } } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } } /** * `import x = require("./x") or `import * as x from "./x"`. @@ -86671,13 +93794,15 @@ var ts; if (propertyName) { // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. singleReferences.push(propertyName); - if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`. + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { // Search locally for `bar`. addSearch(name, checker.getSymbolAtLocation(name)); } } else { - var localSymbol = element.kind === 250 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -86692,27 +93817,21 @@ var ts; /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 248 /* ExportDeclaration */) + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) return; - var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; - if (moduleSpecifier || !exportClause) - return; - for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) { - var element = _b[_i]; - if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) { - return true; - } - } + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var referencingFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 272 /* SourceFile */) { + if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -86740,9 +93859,10 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - cancellationToken.throwIfCancellationRequested(); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol) { @@ -86759,7 +93879,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 272 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -86767,27 +93887,25 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 248 /* ExportDeclaration */: - case 242 /* ImportDeclaration */: { + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: { var decl = statement; - if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) { + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 241 /* ImportEqualsDeclaration */: { + case 246 /* ImportEqualsDeclaration */: { var decl = statement; - var moduleReference = decl.moduleReference; - if (moduleReference.kind === 252 /* ExternalModuleReference */ && - moduleReference.expression.kind === 9 /* StringLiteral */) { - action(decl, moduleReference.expression); + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); } break; } @@ -86795,19 +93913,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185 /* CallExpression */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return decl; - case 252 /* ExternalModuleReference */: - return decl.parent; - default: - ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); - } - } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. * If at an import, look locally for the symbol it imports. @@ -86819,12 +93924,13 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 183 /* PropertyAccessExpression */) { + if (parent.kind === 187 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) : undefined; } else { @@ -86851,15 +93957,18 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); } } function getExportAssignmentExport(ex) { @@ -86905,7 +94014,7 @@ var ts; // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) - var importedName = symbolName(importedSymbol); + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } @@ -86931,15 +94040,18 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 230 /* VariableDeclaration */) { + if (parent.kind === 235 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 267 /* CatchClause */ ? undefined : p.parent.parent.kind === 212 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -86948,15 +94060,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -86972,15 +94084,6 @@ var ts; return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; - function symbolName(symbol) { - if (symbol.escapedName !== "default" /* Default */) { - return symbol.escapedName; - } - return ts.forEach(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.escapedText; - }); - } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. @@ -86998,65 +94101,65 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 185 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 272 /* SourceFile */) { + if (parent.kind === 277 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 238 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } - function isExternalModuleImportEquals(_a) { - var moduleReference = _a.moduleReference; - return moduleReference.kind === 252 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { function nodeEntry(node, isInString) { - return { type: "node", node: node, isInString: isInString }; + return { type: "node", node: node.name || node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {}); + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - // A node in a JSDoc comment can't have an implementation anyway. - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); + var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + var result_6 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); + return result_6; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -87069,14 +94172,14 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function flattenEntries(referenceSymbols) { @@ -87088,8 +94191,8 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -87097,13 +94200,13 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { @@ -87116,15 +94219,7 @@ var ts; })(); var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "" /* unknown */, - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); @@ -87137,20 +94232,22 @@ var ts; return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; } var node = entry.node, isInString = entry.isInString; + var sourceFile = node.getSourceFile(); return { - fileName: node.getSourceFile().fileName, - textSpan: getTextSpan(node), + fileName: sourceFile.fileName, + textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString + isInString: isInString, }; } function toImplementationLocation(entry, checker) { if (entry.type === "node") { var node = entry.node; - return __assign({ textSpan: getTextSpan(node), fileName: node.getSourceFile().fileName }, implementationKindDisplayParts(node, checker)); + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); } else { var textSpan = entry.textSpan, fileName = entry.fileName; @@ -87162,13 +94259,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 182 /* ObjectLiteralExpression */) { + else if (node.kind === 186 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 203 /* ClassExpression */) { + else if (node.kind === 207 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] @@ -87180,22 +94277,22 @@ var ts; } function toHighlightSpan(entry) { if (entry.type === "span") { - var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } var node = entry.node, isInString = entry.isInString; - var fileName = entry.node.getSourceFile().fileName; + var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { - textSpan: getTextSpan(node), + textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: isInString }; - return { fileName: fileName, span: span }; + return { fileName: sourceFile.fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9 /* StringLiteral */) { start += 1; @@ -87217,11 +94314,13 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -87236,32 +94335,37 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 237 /* ModuleDeclaration */: - case 252 /* ExternalModuleReference */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return true; - case 185 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } - function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -87275,17 +94379,20 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 237 /* ModuleDeclaration */: - references.push({ type: "node", node: decl.name }); + case 242 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push({ type: "node", node: decl.name }); + } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -87312,23 +94419,23 @@ var ts; return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { // Global search @@ -87369,7 +94476,6 @@ var ts; return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.assert(decl.kind === 272 /* SourceFile */); ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) @@ -87388,10 +94494,11 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, + function State(sourceFiles, sourceFilesSet, /** True if we're searching for constructor references. */ specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; @@ -87423,31 +94530,27 @@ var ts; this.symbolIdToReferences = []; // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; - this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } State.prototype.includesSourceFile = function (sourceFile) { - return this.includedSourceFiles.has(sourceFile.fileName); + return this.sourceFilesSet.has(sourceFile.fileName); }; /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) - this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; - /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form // here appears to be intentional). - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); - return { - symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, - includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, - }; + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** * Callback to add references for a particular searched symbol. @@ -87470,11 +94573,15 @@ var ts; }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ - State.prototype.markSearchedSymbol = function (sourceFile, symbol) { + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { var sourceId = ts.getNodeId(sourceFile); - var symbolId = ts.getSymbolId(symbol); - var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); - return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; }; return State; }()); @@ -87486,7 +94593,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - addRef(singleRef); + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); } } // For each import, find all references to that import in its source file. @@ -87515,14 +94623,42 @@ var ts; } } } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var exportingFile = declaration.getSourceFile(); - if (state.includesSourceFile(exportingFile)) { - getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state); - } + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); } } /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ @@ -87532,29 +94668,22 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 180 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 178 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && + ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (!bindingElement) - return undefined; - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); } /** * Determines the smallest scope in which a symbol may have named references. @@ -87568,7 +94697,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 190 /* FunctionExpression */ || valueDeclaration.kind === 203 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -87578,7 +94707,7 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 233 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -87596,18 +94725,18 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 272 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -87620,19 +94749,58 @@ var ts; // declare module "a" { export type T = number; } // declare module "b" { import { T } from "a"; export const x: T; } // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) - return exposedByParent ? scope.getSourceFile() : scope; + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; // Be lenient with invalid code. - return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { - var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier); - return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -87665,10 +94833,9 @@ var ts; function getLabelReferencesInNode(container, targetLabel) { var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { // Only pick labels that are either the target label, or have a target that is the target label - return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } @@ -87677,9 +94844,11 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79 /* DefaultKeyword */: @@ -87691,33 +94860,36 @@ var ts; function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** * Search within node "container" for references for a search value, where the search value is defined as a * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). * searchLocation: a node where the search value */ - function getReferencesInContainer(container, sourceFile, search, state) { - if (!state.markSearchedSymbol(sourceFile, search.symbol)) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking @@ -87731,9 +94903,8 @@ var ts; } return; } - if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) { + if (!hasMatchingMeaning(referenceLocation, state)) return; - } var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -87745,7 +94916,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -87755,7 +94926,8 @@ var ts; } switch (state.specialSearchKind) { case 0 /* None */: - addReference(referenceLocation, relatedSymbol, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -87768,7 +94940,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -87776,7 +94948,10 @@ var ts; return; } if (!propertyName) { - addRef(); + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + addRef(); + } } else if (referenceLocation === propertyName) { // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. @@ -87784,7 +94959,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, state); } } @@ -87797,7 +94972,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. @@ -87807,7 +94983,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -87844,6 +95021,7 @@ var ts; function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); /* * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment * has two meanings: property name and property value. Therefore when we do findAllReference at the position where @@ -87851,8 +95029,8 @@ var ts; * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the * position of property accessing, the referenceEntry of such position will be handled in the first case. */ - if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); } } function addReference(referenceLocation, relatedSymbol, state) { @@ -87885,31 +95063,28 @@ var ts; } function addClassStaticThisReferences(referenceLocation, search, state) { addReference(referenceLocation, search.symbol, state); - if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.parent.name === referenceLocation); - // This is the class declaration. - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); - } - } - function addStaticThisReferences(classLike, pusher) { + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { var member = _a[_i]; if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { continue; } - member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { - pusher(node); - } - else if (!ts.isFunctionLike(node)) { - node.forEachChild(cb); - } - }); + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 99 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } } } - function getPropertyAccessExpressionFromRightHandSide(node) { - return ts.isRightSideOfPropertyAccess(node) && node.parent; - } /** * `classSymbol` is the class where the constructor was defined. * Reference the constructor and all calls to `new this()`. @@ -87918,12 +95093,12 @@ var ts; for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 154 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 153 /* MethodDeclaration */) { + if (decl && decl.kind === 154 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { @@ -87937,14 +95112,13 @@ var ts; } /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor" /* Constructor */); + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 154 /* Constructor */); + ts.Debug.assert(decl.kind === 155 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { @@ -87958,13 +95132,13 @@ var ts; function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { - addReference(refNode.parent); + addReference(refNode); return; } if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 269 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -87975,78 +95149,50 @@ var ts; return; } // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface - var containingTypeReference = getContainingTypeReference(refNode); - if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { - var parent = containingTypeReference.parent; - if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { - addReference(parent.initializer); + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); } - else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - var body = parent.body; - if (body.kind === 211 /* Block */) { + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 216 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { - if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { - addReference(returnStatement.expression); - } + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); }); } - else if (isImplementationExpression(body)) { - addReference(body); + else { + addIfImplementation(body); } } - else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { - addReference(parent.expression); + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); } } - } - function getSymbolsForClassAndInterfaceComponents(type, result) { - if (result === void 0) { result = []; } - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var componentType = _a[_i]; - if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { - result.push(componentType.symbol); - } - if (componentType.getFlags() & 393216 /* UnionOrIntersection */) { - getSymbolsForClassAndInterfaceComponents(componentType, result); - } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); } - return result; - } - function getContainingTypeReference(node) { - var topLevelTypeReference; - while (node) { - if (ts.isTypeNode(node)) { - topLevelTypeReference = node; - } - node = node.parent; - } - return topLevelTypeReference; } function getContainingClassIfInHeritageClause(node) { - if (node && node.parent) { - if (node.kind === 205 /* ExpressionWithTypeArguments */ - && node.parent.kind === 266 /* HeritageClause */ - && ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } - else if (node.kind === 71 /* Identifier */ || node.kind === 183 /* PropertyAccessExpression */) { - return getContainingClassIfInHeritageClause(node.parent); - } - } - return undefined; + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; } /** * Returns true if this is an expression that can be considered an implementation */ function isImplementationExpression(node) { switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 191 /* ArrowFunction */: - case 190 /* FunctionExpression */: - case 182 /* ObjectLiteralExpression */: - case 203 /* ClassExpression */: - case 181 /* ArrayLiteralExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 185 /* ArrayLiteralExpression */: return true; default: return false; @@ -88067,58 +95213,29 @@ var ts; * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol A class or interface Symbol * @param parent Another class or interface Symbol * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results */ - function explicitlyInheritsFrom(child, parent, cachedResults, checker) { - var parentIsInterface = parent.getFlags() & 64 /* Interface */; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - if (cached !== undefined) { - return cached; - } - // Set the key so that we don't infinitely recurse - cachedResults.set(key, false); - var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); @@ -88128,13 +95245,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -88142,9 +95259,8 @@ var ts; return undefined; } var sourceFile = searchSpaceNode.getSourceFile(); - var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (!node || node.kind !== 97 /* SuperKeyword */) { + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 97 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -88160,87 +95276,67 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = []; - for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references); - } + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 277 /* SourceFile */: + return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); return [{ definition: { type: "this", node: thisOrSuperKeyword }, references: references }]; } - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, result) { - ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (!node || !ts.isThis(node)) { - return; - } - var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); - switch (searchSpaceNode.kind) { - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - if (searchSpaceNode.symbol === container.symbol) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - // Make sure the container belongs to the same class - // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 272 /* SourceFile */: - if (container.kind === 272 /* SourceFile */ && !ts.isExternalModule(container)) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - } - }); - } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { - var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral); - return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; }); }); return [{ @@ -88251,26 +95347,27 @@ var ts; // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { - // The search set contains at least the current symbol var result = []; + forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - if (containingObjectLiteralElement.kind !== 269 /* ShorthandPropertyAssignment */) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - if (propertySymbol) { - result.push(propertySymbol); - } - } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { - var contextualSymbol = _a[_i]; - addRootSymbols(contextualSymbol); - } + var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol); + if (res1) + return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -88283,177 +95380,60 @@ var ts; * will be included correctly. */ var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If the symbol.valueDeclaration is a property parameter declaration, - // we should include both parameter declaration symbol and property declaration symbol - // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. - // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - ts.addRange(result, getParameterPropertySymbols(symbol, checker)); // If this is symbol of binding element without propertyName declaration in Object binding pattern // Include the property in the search var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - addRootSymbols(bindingElementPropertySymbol); - } - addRootSymbols(symbol); - return result; - function addRootSymbols(sym) { - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - result.push(rootSymbol); - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - } - } - } - } - function getParameterPropertySymbols(symbol, checker) { - return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) - ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) - : undefined; - } - /** - * Find symbol of the given property-name and add the symbol to the given result array - * @param symbol a symbol to start searching for the given propertyName - * @param propertyName a name of property to search for - * @param result an array of symbol of found property symbols - * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. - * The value of previousIterationSymbol is undefined when the function is first called. - */ - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { - if (!symbol) { - return; - } - // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited - // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. - // For example: - // interface C extends C { - // /*findRef*/propName: string; - // } - // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, - // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, - // the function will add any found symbol of the property-name, then its sub-routine will call - // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already - // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (previousIterationSymbolsCache.has(symbol.escapedName)) { - return; - } - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); + function fromRoot(sym) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + : undefined); }); } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = checker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, checker.getRootSymbols(propertySymbol)); - } - // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache.set(symbol.escapedName, symbol); - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); - } - } - } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - if (search.includes(referenceSymbol)) { - return referenceSymbol; - } - if (referenceSymbol.flags & 1 /* FunctionScopedVariable */) { - ts.Debug.assert(!(referenceSymbol.flags & 4 /* Property */)); - var paramProps = getParameterPropertySymbols(referenceSymbol, checker); - if (paramProps) { - return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4 /* Property */); }), referenceLocation, state); - } - } - // If the reference location 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 symbol to - // compare to our searchSymbol - var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); - if (contextualSymbol) { - return contextualSymbol; - } - // If the reference location is the name of property from object literal destructuring pattern - // Get the property symbol from the object literal's type and look if thats the search symbol - // In below eg. get 'property' from type of elems iterating type - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); - if (propertySymbol && search.includes(propertySymbol)) { - return propertySymbol; - } - } - // If the reference location is the binding element and doesn't have property name - // then include the binding element in the related symbols - // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); - if (bindingElementPropertySymbol) { - var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); - if (fromBindingElement) - return fromBindingElement; - } - return findRootSymbol(referenceSymbol); - function findRootSymbol(sym) { - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - // if it is in the list, then we are done - if (search.includes(rootSymbol)) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the - // parent symbol - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { - return undefined; - } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - return ts.find(result, search.includes); - } - return undefined; - }); - } - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 146 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { - return nameExpression.text; - } - return undefined; - } - return ts.getTextOfIdentifierOrLiteral(node.name); + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { var contextualType = checker.getContextualType(node.parent); - var name = getNameFromObjectLiteralElement(node); - var symbol = contextualType && name && contextualType.getProperty(name); + if (!contextualType) + return ts.emptyArray; + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + var symbol = contextualType.getProperty(name); return symbol ? [symbol] : - contextualType && contextualType.flags & 131072 /* Union */ ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; + contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -88475,8 +95455,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -88488,35 +95468,10 @@ var ts; } Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2 /* Ambient */); - } - else { - switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 231 /* VariableDeclarationList */); - return node.parent.parent; - } + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -88543,12 +95498,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9 /* StringLiteral */) { - return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); - } - return false; - } /** * If we are just looking for implementations and this is a property access expression, we need to get the * symbol of the local type of the symbol the property is being accessed on. This is because our search @@ -88556,26 +95505,218 @@ var ts; * being accessed (i.e. it is declared in some parent class or interface) */ function getParentSymbolsOfPropertyAccess(location, symbol, checker) { - var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(location); - if (!propertyAccessExpression) { - return undefined; - } - var localParentType = checker.getTypeAtLocation(propertyAccessExpression.expression); - if (!localParentType) { - return undefined; - } - if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) { - return [localParentType.symbol]; - } - else if (localParentType.flags & 393216 /* UnionOrIntersection */) { - return getSymbolsForClassAndInterfaceComponents(localParentType); - } + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var allFiles = program.getSourceFiles(); + var _loop_15 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_15(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { + var newLocation = oldToNew(oldLocation); + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 + ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -88584,34 +95725,38 @@ var ts; if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; } + var parent = node.parent; // Labels if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } var typeChecker = program.getTypeChecker(); - var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); - if (calledDeclaration) { - return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; - } - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbol(node, typeChecker); // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return undefined; + return getDefinitionInfoForIndexSignatures(node, typeChecker); } - // If this is an alias, and the request came at the declaration location - // get the aliased symbol instead. This allows for goto def on an import e.g. - // import {A, B} from "mod"; - // to jump to the implementation directly. - if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { - var aliased = typeChecker.getAliasedSymbol(symbol); - if (aliased.declarations) { - symbol = aliased; + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -88619,16 +95764,9 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -88641,9 +95779,9 @@ var ts; // 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 (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -88669,6 +95807,14 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { @@ -88678,15 +95824,20 @@ var ts; var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file = reference && program.getSourceFile(reference.resolvedFileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 return file && { fileName: typeReferenceDirective.fileName, file: file }; } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } return undefined; } GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; } @@ -88695,7 +95846,7 @@ var ts; if (!type) { return undefined; } - if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { + if (type.isUnion() && !(type.flags & 32 /* Enum */)) { return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); @@ -88707,15 +95858,41 @@ var ts; return undefined; } // Check if position is on triple slash reference. - var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (comment) { return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; } - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); return { definitions: definitions, textSpan: textSpan }; } GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } // Go to the original declaration for cases: // // (1) when the aliased symbol was declared in the location(parent). @@ -88729,18 +95906,17 @@ var ts; return true; } switch (declaration.kind) { - case 243 /* ImportClause */: - case 241 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 246 /* ImportEqualsDeclaration */: return true; - case 246 /* ImportSpecifier */: - return declaration.parent.kind === 245 /* NamedImports */; + case 251 /* ImportSpecifier */: + return declaration.parent.kind === 250 /* NamedImports */; default: return false; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class @@ -88758,30 +95934,22 @@ var ts; if (!signatureDeclarations) { return undefined; } - var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); return declarations.length - ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] : undefined; } } - function isSignatureDeclaration(node) { - switch (node.kind) { - case 154 /* Constructor */: - case 158 /* ConstructSignature */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return true; - default: - return false; - } - } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ - function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; var sourceFile = name.getSourceFile(); return { fileName: sourceFile.fileName, @@ -88792,25 +95960,11 @@ var ts; containerName: containerName }; } - function getSymbolInfo(typeChecker, symbol, node) { - return { - symbolName: typeChecker.symbolToString(symbol), - symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), - containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" - }; - } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { - var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos <= ref.end) { - return ref; - } - } - return undefined; + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { @@ -88820,14 +95974,14 @@ var ts; kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -88835,14 +95989,8 @@ var ts; function tryGetSignatureDeclaration(typeChecker, node) { var callLike = getAncestorCallLikeExpression(node); var signature = callLike && typeChecker.getResolvedSignature(callLike); - if (signature) { - var decl = signature.declaration; - if (decl && isSignatureDeclaration(decl)) { - return decl; - } - } // Don't go to a function type, go to the value having that type. - return undefined; + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); @@ -88852,47 +96000,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", + "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -88920,10 +96104,12 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 292 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: + case 302 /* JSDocPropertyTag */: return [declaration]; - case 291 /* JSDocTypedefTag */: - return [declaration.parent]; + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } @@ -88943,15 +96129,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 285 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 291 /* JSDocTypedefTag */: - case 292 /* JSDocPropertyTag */: - case 287 /* JSDocParameterTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -89033,7 +96220,7 @@ var ts; if (!ts.isIdentifier(param.name)) return undefined; var name = param.name.text; - if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } @@ -89081,8 +96268,8 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - var tokenStart = tokenAtPos.getStart(); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(sourceFile); if (!tokenAtPos || tokenStart < position) { return undefined; } @@ -89091,7 +96278,7 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.getStart(sourceFile) < position) { return undefined; } if (!parameters || parameters.length === 0) { @@ -89099,22 +96286,7 @@ var ts; var singleLineResult = "/** */"; return { newText: singleLineResult, caretOffset: 3 }; } - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - // replace non-whitespace characters in prefix with spaces. - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); - var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? currentName.escapedText : "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -89122,32 +96294,48 @@ var ts; // * TODO: other tags. // * the closing comment line // * if the caret was directly in front of the object, then we add an extra line and indentation. - var preamble = "/**" + newLine + - indentationStr + " * "; + var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - docParams + + parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } function getCommentOwnerInfo(tokenAtPos) { for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 150 /* PropertySignature */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 235 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 212 /* VariableStatement */: { + case 217 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -89155,14 +96343,14 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 272 /* SourceFile */: + case 277 /* SourceFile */: return undefined; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 237 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 198 /* BinaryExpression */: { + return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { return undefined; @@ -89182,21 +96370,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 189 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return rightHandSide.parameters; - case 203 /* ClassExpression */: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 154 /* Constructor */) { - return member.parameters; - } - } - break; + case 207 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } } return ts.emptyArray; } @@ -89204,425 +96388,74 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// -/// -/// -/// -/* @internal */ -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - /* @internal */ - function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); - } - JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ - JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" - ]; - 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 - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions - * @param typeAcquisition is used to customize the typing acquisition process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { - if (!typeAcquisition || !typeAcquisition.enable) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); - // Only infer typings for .js and .jsx files - fileNames = ts.mapDefined(fileNames, function (fileName) { - var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { - return path; - } - }); - var filesToWatch = []; - if (typeAcquisition.include) - addInferredTypings(typeAcquisition.include, "Explicitly included types"); - var exclude = typeAcquisition.exclude || []; - // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); - possibleSearchDirs.set(projectRootPath, true); - possibleSearchDirs.forEach(function (_true, searchDir) { - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); - }); - getTypingNamesFromSourceFileNames(fileNames); - // add typings for unresolved imports - if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module, "Inferred typings from unresolved imports"); - } - // Add the cached typing locations for inferred typings that are already installed - packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { - inferredTypings.set(name, typing.typingLocation); - } - }); - // Remove typings that the user has added to the exclude list - for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { - var excludeTypingName = exclude_1[_i]; - var didDelete = inferredTypings.delete(excludeTypingName); - if (didDelete && log) - log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); - } - var newTypingNames = []; - var cachedTypingPaths = []; - inferredTypings.forEach(function (inferred, typing) { - if (inferred !== undefined) { - cachedTypingPaths.push(inferred); - } - else { - newTypingNames.push(typing); - } - }); - var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - if (log) - log("Result: " + JSON.stringify(result)); - return result; - function addInferredTyping(typingName) { - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } - function addInferredTypings(typingNames, message) { - if (log) - log(message + ": " + JSON.stringify(typingNames)); - ts.forEach(typingNames, addInferredTyping); - } - /** - * Get the typing info from common package manager json files like package.json or bower.json - */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (!host.fileExists(jsonPath)) { - return; - } - filesToWatch.push(jsonPath); - var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; - var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); - addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); - } - /** - * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" - * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred - * to the 'angular-route' typing name. - * @param fileNames are the names for source files in the project - */ - function getTypingNamesFromSourceFileNames(fileNames) { - var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) - return undefined; - var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - return safeList.get(cleanedTypingName); - }); - if (fromFileNames.length) { - addInferredTypings(fromFileNames, "Inferred typings from file names"); - } - var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); - if (hasJsxFile) { - if (log) - log("Inferred 'react' typings due to presence of '.jsx' extension"); - addInferredTyping("react"); - } - } - /** - * Infer typing names from packages folder (ex: node_module, bower_components) - * @param packagesFolderPath is the path to the packages folder - */ - function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { - filesToWatch.push(packagesFolderPath); - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(packagesFolderPath)) { - return; - } - // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - if (log) - log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); - var packageNames = []; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; - var normalizedFileName = ts.normalizePath(fileName); - var baseFileName = ts.getBaseFileName(normalizedFileName); - if (baseFileName !== "package.json" && baseFileName !== "bower.json") { - continue; - } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (baseFileName === "package.json" && packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - var ownTypes = packageJson.types || packageJson.typings; - if (ownTypes) { - var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); - if (log) - log(" Package '" + packageJson.name + "' provides its own types."); - inferredTypings.set(packageJson.name, absolutePath); - } - else { - packageNames.push(packageJson.name); - } - } - addInferredTypings(packageNames, " Found package names"); - } - } - JsTyping.discoverTypings = discoverTypings; - var PackageNameValidationResult; - (function (PackageNameValidationResult) { - PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; - PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; - PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; - PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; - PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; - })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); - var maxPackageNameLength = 214; - /** - * Validates package name using rules defined at https://docs.npmjs.com/files/package.json - */ - function validatePackageName(packageName) { - if (!packageName) { - return 2 /* EmptyName */; - } - if (packageName.length > maxPackageNameLength) { - return 3 /* NameTooLong */; - } - if (packageName.charCodeAt(0) === 46 /* dot */) { - return 4 /* NameStartsWithDot */; - } - if (packageName.charCodeAt(0) === 95 /* _ */) { - return 5 /* NameStartsWithUnderscore */; - } - // check if name is scope package like: starts with @ and has one '/' in the middle - // scoped packages are not currently supported - // TODO: when support will be added we'll need to split and check both scope and package name - if (/^@[^/]+\/[^/]+$/.test(packageName)) { - return 1 /* ScopedPackagesNotSupported */; - } - if (encodeURIComponent(packageName) !== packageName) { - return 6 /* NameContainsNonURISafeCharacters */; - } - return 0 /* Ok */; - } - JsTyping.validatePackageName = validatePackageName; - function renderPackageNameValidationFailure(result, typing) { - switch (result) { - case 2 /* EmptyName */: - return "Package name '" + typing + "' cannot be empty"; - case 3 /* NameTooLong */: - return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; - case 4 /* NameStartsWithDot */: - return "Package name '" + typing + "' cannot start with '.'"; - case 5 /* NameStartsWithUnderscore */: - return "Package name '" + typing + "' cannot start with '_'"; - case 1 /* ScopedPackagesNotSupported */: - return "Package '" + typing + "' is scoped and currently is not supported"; - case 6 /* NameContainsNonURISafeCharacters */: - return "Package name '" + typing + "' contains non URI safe characters"; - case 0 /* Ok */: - return ts.Debug.fail(); // Shouldn't have called this. - default: - ts.Debug.assertNever(result); - } - } - JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_16 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_8(sourceFile); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + _loop_16(sourceFile); } rawItems.sort(compareNavigateToItems); - if (maxResultCount !== undefined) { - rawItems = rawItems.slice(0, maxResultCount); - } - return rawItems.map(createNavigateToItem); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); } NavigateTo.getNavigateToItems = getNavigateToItems; function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - if (!shouldKeepItem(declaration, checker)) { + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; + if (!shouldKeepItem(declaration, checker)) continue; - } - // It was a match! If the pattern has dots in it, then also see if the - // declaration container matches as well. - var containerMatches = matches; if (patternMatcher.patternContainsDots) { - containerMatches = patternMatcher.getMatches(getContainers(declaration), name); - if (!containerMatches) { - continue; + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } } - var matchKind = bestMatchKind(containerMatches); - var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } } } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 243 /* ImportClause */: - case 246 /* ImportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - var importer = checker.getSymbolAtLocation(declaration.name); + case 248 /* ImportClause */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; default: return true; } } - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - if (!match.isCaseSensitive) { - return false; - } - } - return true; - } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); if (name && ts.isPropertyNameLiteral(name)) { containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); return true; } - else if (name && name.kind === 146 /* ComputedPropertyName */) { + else if (name && name.kind === 147 /* ComputedPropertyName */) { return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { @@ -89654,33 +96487,19 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 146 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { - return undefined; - } + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + return ts.emptyArray; } // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } - } - return bestMatchKind; - } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. return ts.compareValues(i1.matchKind, i2.matchKind) @@ -89700,12 +96519,11 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -89782,7 +96600,7 @@ var ts; } function rootNavigationBarNode(sourceFile) { ts.Debug.assert(!parentsStack.length); - var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; parent = root; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -89798,6 +96616,7 @@ var ts; function emptyNavigationBarNode(node) { return { node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, additionalNodes: undefined, parent: parent, children: undefined, @@ -89818,7 +96637,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -89835,7 +96654,7 @@ var ts; return; } switch (node.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -89847,33 +96666,33 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 153 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 243 /* ImportClause */: + case 248 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addLeafNode(importClause); + addLeafNode(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { + if (namedBindings.kind === 249 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -89884,8 +96703,8 @@ var ts; } } break; - case 180 /* BindingElement */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -89906,12 +96725,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -89921,9 +96740,9 @@ var ts; } endNode(); break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -89931,18 +96750,18 @@ var ts; } endNode(); break; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 250 /* ExportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - case 159 /* IndexSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 235 /* TypeAliasDeclaration */: + case 255 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 160 /* IndexSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 240 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var special = ts.getSpecialPropertyAssignmentKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -89950,7 +96769,7 @@ var ts; case 3 /* PrototypeProperty */: case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); - break; + return; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: @@ -89964,7 +96783,7 @@ var ts; if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 291 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(tag)) { addLeafNode(tag); } }); @@ -89974,7 +96793,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -89991,7 +96810,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -90000,7 +96819,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -90008,37 +96827,45 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - return a.body.kind === b.body.kind && (a.body.kind !== 237 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { + var _a; target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { @@ -90046,17 +96873,16 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } - var _a; } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { children.sort(compareChildren); } function compareChildren(child1, child2) { - return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** @@ -90065,29 +96891,26 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 237 /* ModuleDeclaration */) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 203 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: return getFunctionOrClassName(node); - case 291 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return undefined; } } - function getItemName(node) { - if (node.kind === 237 /* ModuleDeclaration */) { + function getItemName(node, name) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } - var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -90095,16 +96918,16 @@ var ts; } } switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -90112,37 +96935,18 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return "constructor"; - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: return "new()"; - case 157 /* CallSignature */: + case 158 /* CallSignature */: return "()"; - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: return "[]"; - case 291 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return ""; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 212 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - return nameIdentifier.text; - } - } - } - return ""; - } - } /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; @@ -90161,24 +96965,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 272 /* SourceFile */: - case 235 /* TypeAliasDeclaration */: - case 291 /* JSDocTypedefTag */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 277 /* SourceFile */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return true; - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 230 /* VariableDeclaration */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 235 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -90188,35 +96993,36 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 238 /* ModuleBlock */: - case 272 /* SourceFile */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: return true; default: return hasSomeImportantChild(item); } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 230 /* VariableDeclaration */ && childKind !== 180 /* BindingElement */; + return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; }); } } } function convertToTree(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: getModifiers(n.node), spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), childItems: ts.map(n.children, convertToTree) }; } function convertToTopLevelItem(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: getModifiers(n.node), spans: getSpans(n), @@ -90227,7 +97033,7 @@ var ts; }; function convertToChildItem(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), @@ -90256,7 +97062,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 237 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -90267,16 +97073,16 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 237 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 } function isComputedProperty(member) { - return !member.name || member.name.kind === 146 /* ComputedPropertyName */; + return !member.name || member.name.kind === 147 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 272 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 230 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -90286,16 +97092,16 @@ var ts; return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 230 /* VariableDeclaration */) { + else if (node.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 198 /* BinaryExpression */ && + else if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } // Default exports are named "default" @@ -90308,9 +97114,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 191 /* ArrowFunction */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: return true; default: return false; @@ -90329,56 +97135,68 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program) { + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); // Delete or replace the first import. if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); + changeTracker.delete(sourceFile, oldImportDecls[0]); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, + useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), }); } // Delete any subsequent imports. for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + changeTracker.delete(sourceFile, oldImportDecls[i]); } } } OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -90402,7 +97220,7 @@ var ts; } else { // List of named imports - var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); }); + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); if (newElements.length < namedBindings.elements.length) { namedBindings = newElements.length ? ts.updateNamedImports(namedBindings, newElements) @@ -90416,12 +97234,12 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { - return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) + return specifier !== undefined && ts.isStringLiteralLike(specifier) ? specifier.text : undefined; } @@ -90443,16 +97261,16 @@ var ts; if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. var defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 return coalescedImports; } var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); - }); + }); // TODO: GH#18217 for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; // Drop the name, if any - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -90465,22 +97283,21 @@ var ts; else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; /* @@ -90523,13 +97340,65 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + /* @internal */ // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { @@ -90537,9 +97406,12 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -90556,7 +97428,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -90567,9 +97459,19 @@ var ts; if (span) out.push(span); depthRemaining--; - n.forEachChild(walk); + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -90578,13 +97480,13 @@ var ts; var currentLineStart = lineStarts[i]; var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; var lineText = sourceFile.text.substring(currentLineStart, lineEnd); - var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + var result = isRegionDelimiter(lineText); if (!result || ts.isInComment(sourceFile, currentLineStart)) { continue; } if (!result[1]) { - var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span_12, span_12, /*autoCollapse*/ false, result[2] || "#region")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -90596,6 +97498,10 @@ var ts; } } } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); if (!comments) @@ -90603,11 +97509,19 @@ var ts; var firstSingleLineCommentStart = -1; var lastSingleLineCommentEnd = -1; var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); switch (kind) { case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (singleLineCommentCount === 0) { @@ -90618,7 +97532,7 @@ var ts; break; case 3 /* MultiLineCommentTrivia */: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); singleLineCommentCount = 0; break; default: @@ -90629,33 +97543,33 @@ var ts; function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 191 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); } // 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. switch (n.parent.kind) { - case 216 /* DoStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 215 /* IfStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 267 /* CatchClause */: + case 221 /* DoStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 272 /* CatchClause */: return spanForNode(n.parent); - case 228 /* TryStatement */: + case 233 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -90668,19 +97582,36 @@ var ts; default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanForNode(n.parent); - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 239 /* CaseBlock */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 244 /* CaseBlock */: return spanForNode(n); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -90700,14 +97631,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -90722,12 +97653,10 @@ var ts; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); - function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { + function createPatternMatch(kind, isCaseSensitive) { return { kind: kind, - punctuationStripped: punctuationStripped, - isCaseSensitive: isCaseSensitive, - camelCaseWeight: camelCaseWeight + isCaseSensitive: isCaseSensitive }; } function createPatternMatcher(pattern) { @@ -90736,318 +97665,232 @@ var ts; // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. var stringToWordSpans = ts.createMap(); - pattern = pattern.trim(); - var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); - var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; return { - getMatches: getMatches, - getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern, + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, patternContainsDots: dotSeparatedSegments.length > 1 }; - // Quick checks so we can bail out when asked to match a candidate. - function skipMatch(candidate) { - return invalidPattern || !candidate; - } - function getMatchesForLastSegmentOfPattern(candidate) { - if (skipMatch(candidate)) { - return undefined; - } - return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); - } - function getMatches(candidateContainers, candidate) { - if (skipMatch(candidate)) { - return undefined; - } - // First, check that the last part of the dot separated pattern matches the name of the - // candidate. If not, then there's no point in proceeding and doing the more - // expensive work. - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); - if (!candidateMatch) { - return undefined; - } - candidateContainers = candidateContainers || []; - // -1 because the last part was checked against the name, and only the rest - // of the parts are checked against the container. - if (dotSeparatedSegments.length - 1 > candidateContainers.length) { - // There weren't enough container parts to match against the pattern parts. - // So this definitely doesn't match. - return undefined; - } - // So far so good. Now break up the container for the candidate and check if all - // the dotted parts match up correctly. - var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { - var segment = dotSeparatedSegments[i]; - var containerName = candidateContainers[j]; - var containerMatch = matchSegment(containerName, segment); - if (!containerMatch) { - // This container didn't match the pattern piece. So there's no match at all. - return undefined; - } - ts.addRange(totalMatch, containerMatch); - } - // Success, this symbol's full name matched against the dotted name the user was asking - // about. - return totalMatch; - } - function getWordSpans(word) { - var spans = stringToWordSpans.get(word); - if (!spans) { - stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); - } - return spans; - } - function matchTextChunk(candidate, chunk, punctuationStripped) { - var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); - if (index === 0) { - if (chunk.text.length === candidate.length) { - // a) Check if the part matches the candidate entirely, in an case insensitive or - // sensitive manner. If it does, return that there was an exact match. - return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.text); - } - else { - // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive - // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); - } - } - var isLowercase = chunk.isLowerCase; - if (isLowercase) { - if (index > 0) { - // c) If the part is entirely lowercase, then check if it is contained anywhere in the - // candidate in a case insensitive manner. If so, return that there was a substring - // match. - // - // Note: We only have a substring match if the lowercase part is prefix match of some - // word part. That way we don't match something like 'Class' when the user types 'a'. - // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). - var wordSpans = getWordSpans(candidate); - for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_13 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ false)); - } - } - } - } - else { - // d) If the part was not entirely lowercase, then check if it is contained in the - // candidate in a case *sensitive* manner. If so, return that there was a substring - // match. - if (candidate.indexOf(chunk.text) > 0) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ true); - } - } - if (!isLowercase) { - // e) If the part was not entirely lowercase, then attempt a camel cased match as well. - if (chunk.characterSpans.length > 0) { - var candidateParts = getWordSpans(candidate); - var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); - if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight); - } - camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true); - if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ false, /*camelCaseWeight:*/ camelCaseWeight); - } - } - } - if (isLowercase) { - // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? - // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to - // filter the list based on a substring that starts on a capital letter and also with a lowercase one. - // (Pattern: fogbar, Candidate: quuxfogbarFogBar). - if (chunk.text.length < candidate.length) { - if (index > 0 && isUpperCaseLetter(candidate.charCodeAt(index))) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ false); - } - } - } + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { return undefined; } - function containsSpaceOrAsterisk(text) { - for (var i = 0; i < text.length; i++) { - var ch = text.charCodeAt(i); - if (ch === 32 /* space */ || ch === 42 /* asterisk */) { - return true; - } - } - return false; + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; } - function matchSegment(candidate, segment) { - // First check if the segment matches as is. This is also useful if the segment contains - // characters we would normally strip when splitting into parts that we also may want to - // match in the candidate. For example if the segment is "@int" and the candidate is - // "@int", then that will show up as an exact match here. - // - // Note: if the segment contains a space or an asterisk then we must assume that it's a - // multi-word segment. - if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) { - var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); - if (match) { - return [match]; - } - } - // The logic for pattern matching is now as follows: - // - // 1) Break the segment passed in into words. Breaking is rather simple and a - // good way to think about it that if gives you all the individual alphanumeric words - // of the pattern. - // - // 2) For each word try to match the word against the candidate value. - // - // 3) Matching is as follows: - // - // a) Check if the word matches the candidate entirely, in an case insensitive or - // sensitive manner. If it does, return that there was an exact match. - // - // b) Check if the word is a prefix of the candidate, in a case insensitive or - // sensitive manner. If it does, return that there was a prefix match. - // - // c) If the word is entirely lowercase, then check if it is contained anywhere in the - // candidate in a case insensitive manner. If so, return that there was a substring - // match. - // - // Note: We only have a substring match if the lowercase part is prefix match of - // some word part. That way we don't match something like 'Class' when the user - // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with - // 'a'). - // - // d) If the word was not entirely lowercase, then check if it is contained in the - // candidate in a case *sensitive* manner. If so, return that there was a substring - // match. - // - // e) If the word was not entirely lowercase, then attempt a camel cased match as - // well. - // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting - // on a part boundary of the candidate? - // - // Only if all words have some sort of match is the pattern considered matched. - var subWordTextChunks = segment.subWordTextChunks; - var matches; - for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { - var subWordTextChunk = subWordTextChunks_1[_i]; - // Try to match the candidate with this word - var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); - if (!result) { - return undefined; - } - matches = matches || []; - matches.push(result); - } - return matches; + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); } - function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { - var patternPartStart = patternSpan ? patternSpan.start : 0; - var patternPartLength = patternSpan ? patternSpan.length : pattern.length; - if (patternPartLength > candidateSpan.length) { - // Pattern part is longer than the candidate part. There can never be a match. - return false; - } - if (ignoreCase) { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); - if (toLowerCase(ch1) !== toLowerCase(ch2)) { - return false; - } - } - } - else { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); - if (ch1 !== ch2) { - return false; - } - } - } - return true; + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); } - function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { - var chunkCharacterSpans = chunk.characterSpans; - // Note: we may have more pattern parts than candidate parts. This is because multiple - // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". - // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. - var currentCandidate = 0; - var currentChunkSpan = 0; - var firstMatch; - var contiguous; - while (true) { - // Let's consider our termination cases - if (currentChunkSpan === chunkCharacterSpans.length) { - // We did match! We shall assign a weight to this - var weight = 0; - // Was this contiguous? - if (contiguous) { - weight += 1; - } - // Did we start at the beginning of the candidate? - if (firstMatch === 0) { - weight += 2; - } - return weight; + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); } - else if (currentCandidate === candidateParts.length) { - // No match, since we still have more of the pattern to hit - return undefined; + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); } - var candidatePart = candidateParts[currentCandidate]; - var gotOneMatchThisCandidate = false; - // Consider the case of matching SiUI against SimpleUIElement. The candidate parts - // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' - // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. - for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { - var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; - if (gotOneMatchThisCandidate) { - // We've already gotten one pattern part match in this candidate. We will - // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. - if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || - !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { - break; - } - } - if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { - break; - } - gotOneMatchThisCandidate = true; - firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; - // If we were contiguous, then keep that value. If we weren't, then keep that - // value. If we don't know, then set the value to 'true' as an initial match is - // obviously contiguous. - contiguous = contiguous === undefined ? true : contiguous; - candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); - } - // Check if we matched anything at all. If we didn't, then we need to unset the - // contiguous bit if we currently had it set. - // If we haven't set the bit yet, then that means we haven't matched anything so - // far, and we don't want to change that. - if (!gotOneMatchThisCandidate && contiguous !== undefined) { - contiguous = false; - } - // Move onto the next candidate. - currentCandidate++; } } } - ts.createPatternMatcher = createPatternMatcher; + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } function createSegment(text) { return { totalTextChunk: createTextChunk(text), subWordTextChunks: breakPatternIntoTextChunks(text) }; } - // A segment is considered invalid if we couldn't find any words in it. - function segmentIsInvalid(segment) { - return segment.subWordTextChunks.length === 0; - } function isUpperCaseLetter(ch) { // Fast check for the ascii range. if (ch >= 65 /* A */ && ch <= 90 /* Z */) { @@ -91077,24 +97920,18 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(str, value, i)) { - return i; + var _loop_17 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; } + }; + for (var start = 0; start <= n; start++) { + var state_4 = _loop_17(start); + if (typeof state_4 === "object") + return state_4.value; } return -1; } - // Assumes 'value' is already lowercase. - function startsWithIgnoringCase(str, value, start) { - for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(str.charCodeAt(i + start)); - var ch2 = value.charCodeAt(i); - if (ch1 !== ch2) { - return false; - } - } - return true; - } function toLowerCase(ch) { // Fast convert for the ascii range. if (ch >= 65 /* A */ && ch <= 90 /* Z */) { @@ -91162,7 +97999,7 @@ var ts; var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); var currentIsDigit = isDigit(identifier.charCodeAt(i)); var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); - var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || lastIsDigit !== currentIsDigit || @@ -91209,46 +98046,28 @@ var ts; return false; } function isAllPunctuation(identifier, start, end) { - for (var i = start; i < end; i++) { - var ch = identifier.charCodeAt(i); - // We don't consider _ or $ as punctuation as there may be things with that name. - if (!charIsPunctuation(ch) || ch === 95 /* _ */ || ch === 36 /* $ */) { - return false; - } - } - return true; + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); } - function transitionFromUpperToLower(identifier, word, index, wordStart) { - if (word) { - // Cases this supports: - // 1) IDisposable -> I, Disposable - // 2) UIElement -> UI, Element - // 3) HTMLDocument -> HTML, Document - // - // etc. - if (index !== wordStart && - index + 1 < identifier.length) { - var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); - var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); - if (currentIsUpper && nextIsLower) { - // We have a transition from an upper to a lower letter here. But we only - // want to break if all the letters that preceded are uppercase. i.e. if we - // have "Foo" we don't want to break that into "F, oo". But if we have - // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, - // Foo". i.e. the last uppercase letter belongs to the lowercase letters - // that follows. Note: this will make the following not split properly: - // "HELLOthere". However, these sorts of names do not show up in .Net - // programs. - for (var i = wordStart; i < index; i++) { - if (!isUpperCaseLetter(identifier.charCodeAt(i))) { - return false; - } - } - return true; - } - } - } - return false; + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); } function transitionFromLowerToUpper(identifier, word, index) { var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); @@ -91266,10 +98085,20 @@ var ts; // on characters would be: A M // // We break the search string on characters. But we break the symbol name on words. - var transition = word - ? (currentIsUpper && !lastIsUpper) - : currentIsUpper; - return transition; + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); } })(ts || (ts = {})); var ts; @@ -91283,25 +98112,29 @@ var ts; checkJsDirective: undefined, referencedFiles: [], typeReferenceDirectives: [], + libReferenceDirectives: [], amdDependencies: [], hasNoDefaultLib: undefined, moduleName: undefined }; var importedFiles = []; var ambientExternalModules; + var lastToken; + var currentToken; var braceNesting = 0; // assume that text represent an external module if it contains at least one top level import/export // ambient modules that are found inside external modules are interpreted as module augmentations var externalModule = false; function nextToken() { - var token = ts.scanner.scan(); - if (token === 17 /* OpenBraceToken */) { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 17 /* OpenBraceToken */) { braceNesting++; } - else if (token === 18 /* CloseBraceToken */) { + else if (currentToken === 18 /* CloseBraceToken */) { braceNesting--; } - return token; + return currentToken; } function getFileReference() { var fileName = ts.scanner.getTokenValue(); @@ -91345,6 +98178,9 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { + if (lastToken === 23 /* DotToken */) { + return false; + } var token = ts.scanner.getToken(); if (token === 91 /* ImportKeyword */) { token = nextToken(); @@ -91364,7 +98200,7 @@ var ts; else { if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -91395,7 +98231,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -91411,7 +98247,7 @@ var ts; token = nextToken(); if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -91441,7 +98277,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -91453,7 +98289,7 @@ var ts; } else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -91543,6 +98379,9 @@ var ts; // export {a as b} from "mod" // export import i = require("mod") // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") while (true) { if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { break; @@ -91574,7 +98413,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 @@ -91593,7 +98432,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -91603,52 +98442,40 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { - var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); }); - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); - function isDefinedInLibraryFile(declaration) { - if (!defaultLibFileName) { - return false; - } - var sourceFile = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName)); - return canonicalName === getCanonicalDefaultLibName(); - } } Rename.getRenameInfo = getRenameInfo; function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; // Only allow a symbol to be renamed if it actually has at least one declaration. - if (symbol) { - var declarations = symbol.declarations; - if (declarations && declarations.length > 0) { - // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { - return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); - } - // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { - return undefined; - } - var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) - ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) - : undefined; - var displayName = specifierName || typeChecker.symbolToString(symbol); - var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); - return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); - } + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } - else if (ts.isStringLiteral(node)) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); - } - return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile); + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { @@ -91662,6 +98489,7 @@ var ts; }; } function getRenameInfoError(diagnostic) { + // TODO: GH#18217 return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), @@ -91696,7 +98524,6 @@ var ts; } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -91708,8 +98535,13 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); - function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); @@ -91717,66 +98549,135 @@ var ts; // We are at the beginning of the file return undefined; } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var shouldCarefullyCheckContext = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (shouldCarefullyCheckContext) { + if (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position)) { + return undefined; + } + } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, shouldCarefullyCheckContext); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program); + return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); } return undefined; } - return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 185 /* CallExpression */) { - return undefined; + function getCandidateInfo(argumentInfo, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0 /* Call */) { + if (onlyUseSyntacticOwners) { + if (ts.isCallOrNewExpression(invocation.node)) { + var invocationChildren = invocation.node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + if (!ts.contains(invocationChildren, startingToken)) { + return undefined; + } + break; + case 26 /* CommaToken */: + var containingList = ts.findContainingList(startingToken); + if (!containingList || !ts.contains(invocationChildren, ts.findContainingList(startingToken))) { + return undefined; + } + break; + case 27 /* LessThanToken */: + if (!lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.node.expression)) { + return undefined; + } + break; + default: + return undefined; + } + } + else { + return undefined; + } + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } + else if (invocation.kind === 1 /* TypeArgs */) { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentInfo.argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + else { + ts.Debug.assertNever(invocation); + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { // See if we can find some symbol with the call expression name that has call signatures. - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_18 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; + var _loop_19 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { - var callSignatures = type.getCallSignatures(); - if (callSignatures && callSignatures.length) { - return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, typeChecker); + var callSignatures_1 = type.getCallSignatures(); + if (callSignatures_1 && callSignatures_1.length) { + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } + }; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_19(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_18(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; // There are 3 cases to handle: @@ -91796,7 +98697,7 @@ var ts; if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -91812,60 +98713,66 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 187 /* TaggedTemplateExpression */) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. - if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 187 /* TaggedTemplateExpression */) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 200 /* TemplateExpression */); - var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; + ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 209 /* TemplateSpan */ && node.parent.parent.parent.kind === 187 /* TaggedTemplateExpression */) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 200 /* TemplateExpression */); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; // If we're just after a template tail, don't show signature help. - if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); - var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + else if (ts.isJsxOpeningLikeElement(parent)) { // Provide a signature help for JSX opening element or JSX self-closing element. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") // i.e // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } // 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; } // spanIndex is either the index for a given template span. // This does not give appropriate results for a NoSubstitutionTemplateLiteral - function getArgumentIndexForTemplatePiece(spanIndex, node, position) { + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. // There are three cases we can encounter: // 1. We are precisely in the template literal (argIndex = 0). @@ -91926,8 +98833,8 @@ var ts; // Case: 1 1 3 2 1 3 2 2 1 // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); - if (ts.isTemplateLiteralKind(node.kind)) { - if (ts.isInsideTemplateLiteral(node, position)) { + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return 0; } return spanIndex + 2; @@ -91942,7 +98849,7 @@ var ts; } return { kind: 2 /* TaggedTemplateArguments */, - invocation: tagExpression, + invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -91973,8 +98880,8 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 200 /* TemplateExpression */) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + if (template.kind === 204 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -91982,39 +98889,40 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 272 /* SourceFile */; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } + var _loop_20 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } - // TODO: Handle generic call with incomplete syntax + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_20(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -92029,9 +98937,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -92039,8 +98947,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -92053,10 +98961,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -92078,8 +98986,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: parameter.name, @@ -92090,8 +98998,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -92106,59 +99014,225 @@ var ts; /* @internal */ var ts; (function (ts) { - function computeSuggestionDiagnostics(sourceFile, program) { - program.getSemanticDiagnostics(sourceFile); - var checker = program.getDiagnosticsProducingTypeChecker(); + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - if (sourceFile.commonJsModuleIndicator) { - diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); - function check(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); - } - } - break; - } - if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { - diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); - } - node.forEachChild(check); - } check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importNode = _a[_i]; - var name = importNameForConvertToDefaultImport(importNode.parent); + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, importNode.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 194 /* FunctionExpression */: + var decl = ts.getDeclarationOfJSInitializer(node); + if (decl) { + var symbol_3 = decl.symbol; + if (symbol_3 && (symbol_3.exports && symbol_3.exports.size || symbol_3.members && symbol_3.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 237 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + node.forEachChild(check); + } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 217 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); // TODO: GH#18217 + case 219 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { - if (ts.isExternalModuleReference(node)) { - return node.parent.name; - } - if (ts.isImportDeclaration(node)) { - var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) - ? importClause.namedBindings.name - : undefined; + switch (node.kind) { + case 247 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 246 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; } } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -92173,7 +99247,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -92196,6 +99270,14 @@ var ts; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } if (typeChecker.isUndefinedSymbol(symbol)) { return "var" /* variableElement */; } @@ -92210,7 +99292,7 @@ var ts; if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { return "parameter" /* parameterElement */; } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { @@ -92253,11 +99335,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 255 /* JsxOpeningElement */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -92283,11 +99365,12 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; var printer; var documentationFromAlias; + var tagsFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -92296,7 +99379,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 183 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 187 /* 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)) { @@ -92316,8 +99399,8 @@ var ts; } if (callExpressionLike) { var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - var useConstructSignatures = callExpressionLike.kind === 186 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 190 /* 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 @@ -92332,7 +99415,7 @@ var ts; } else if (symbolFlags & 2097152 /* Alias */) { symbolKind = "alias" /* alias */; - pushTypePart(symbolKind); + pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); @@ -92354,7 +99437,7 @@ var ts; // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); - if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } @@ -92372,7 +99455,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration // 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 @@ -92380,21 +99463,21 @@ var ts; return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 154 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 154 /* Constructor */) { + if (functionDeclaration_1.kind === 155 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 157 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -92404,11 +99487,11 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class - pushTypePart("local class" /* localClassElement */); + pushSymbolKind("local class" /* localClassElement */); } else { // Class declaration has name which is not local. @@ -92438,7 +99521,7 @@ var ts; } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } @@ -92448,7 +99531,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 237 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -92469,23 +99552,24 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 147 /* TypeParameter */); - ts.Debug.assert(decl !== undefined); + var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 158 /* ConstructSignature */) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 159 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 157 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 235 /* TypeAliasDeclaration */) { + else if (declaration.kind === 240 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -92502,7 +99586,7 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 271 /* EnumMember */) { + if (declaration.kind === 276 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -92527,27 +99611,31 @@ var ts; displayParts.push.apply(displayParts, resolvedInfo.displayParts); displayParts.push(ts.lineBreakPart()); documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; } } } switch (symbol.declarations[0].kind) { - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); break; + case 255 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + break; default: displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 241 /* ImportEqualsDeclaration */) { + if (declaration.kind === 246 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -92625,10 +99713,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 272 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 198 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -92647,6 +99735,9 @@ var ts; if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function getPrinter() { if (!printer) { @@ -92662,7 +99753,7 @@ var ts; } function addAliasPrefixIfNecessary() { if (alias) { - pushTypePart("alias" /* alias */); + pushSymbolKind("alias" /* alias */); displayParts.push(ts.spacePart()); } } @@ -92677,18 +99768,21 @@ var ts; } var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { prefixNextMeaning(); if (symbolKind) { - pushTypePart(symbolKind); + pushSymbolKind(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } } } - function pushTypePart(symbolKind) { + function pushSymbolKind(symbolKind) { switch (symbolKind) { case "var" /* variableElement */: case "function" /* functionElement */: @@ -92705,6 +99799,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -92733,16 +99828,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 190 /* FunctionExpression */) { + if (declaration.kind === 194 /* FunctionExpression */) { return true; } - if (declaration.kind !== 230 /* VariableDeclaration */ && declaration.kind !== 232 /* FunctionDeclaration */) { + if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 272 /* SourceFile */ || parent.kind === 238 /* ModuleBlock */) { + if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { return false; } } @@ -92790,7 +99885,7 @@ var ts; options.noResolve = true; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -92831,7 +99926,8 @@ var ts; } // Emit program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -92854,7 +99950,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_21 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -92873,7 +99969,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_21(opt); } return options; } @@ -92969,8 +100065,6 @@ var ts; formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// /* @internal */ var ts; (function (ts) { @@ -93012,7 +100106,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { scanner.scan(); @@ -93052,10 +100146,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 260 /* JsxAttribute */: - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 265 /* JsxAttribute */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } @@ -93232,7 +100326,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 144 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -93244,9 +100338,9 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 144 /* LastKeyword */); + var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 144 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; + var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, @@ -93279,6 +100373,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. @@ -93333,8 +100428,8 @@ var ts; // Async-await rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - // template string - rule("NoSpaceBetweenTagAndTemplateString", 71 /* Identifier */, [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), @@ -93366,11 +100461,11 @@ var ts; 136 /* SetKeyword */, 115 /* StaticKeyword */, 139 /* TypeKeyword */, - 142 /* FromKeyword */, + 143 /* FromKeyword */, 128 /* KeyOfKeyword */, 126 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 142 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions @@ -93386,7 +100481,7 @@ var ts; rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), @@ -93535,45 +100630,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 218 /* ForStatement */; + return context.contextNode.kind === 223 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 198 /* BinaryExpression */: - case 199 /* ConditionalExpression */: - case 170 /* ConditionalType */: - case 206 /* AsExpression */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 160 /* TypePredicate */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 173 /* ConditionalType */: + case 210 /* AsExpression */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 161 /* TypePredicate */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 180 /* BindingElement */: + case 184 /* BindingElement */: // equals in type X = ... - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: // equal in p = 0; - case 148 /* Parameter */: - case 271 /* EnumMember */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 149 /* Parameter */: + case 276 /* EnumMember */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 220 /* ForOfStatement */: - return context.currentTokenSpan.kind === 144 /* OfKeyword */ || context.nextTokenSpan.kind === 144 /* OfKeyword */; + case 225 /* ForOfStatement */: + return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; } return false; } @@ -93585,22 +100680,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 151 /* PropertyDeclaration */ || - contextKind === 150 /* PropertySignature */ || - contextKind === 148 /* Parameter */ || - contextKind === 230 /* VariableDeclaration */ || + return contextKind === 152 /* PropertyDeclaration */ || + contextKind === 151 /* PropertySignature */ || + contextKind === 149 /* Parameter */ || + contextKind === 235 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 199 /* ConditionalExpression */ || - context.contextNode.kind === 170 /* ConditionalType */; + return context.contextNode.kind === 203 /* ConditionalExpression */ || + context.contextNode.kind === 173 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 178 /* ObjectBindingPattern */ || - context.contextNode.kind === 176 /* MappedType */ || + return context.contextNode.kind === 182 /* ObjectBindingPattern */ || + context.contextNode.kind === 179 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -93626,70 +100721,73 @@ var ts; return true; } switch (node.kind) { - case 211 /* Block */: - case 239 /* CaseBlock */: - case 182 /* ObjectLiteralExpression */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 186 /* ObjectLiteralExpression */: + case 243 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 157 /* CallSignature */: - case 190 /* FunctionExpression */: - case 154 /* Constructor */: - case 191 /* ArrowFunction */: + case 158 /* CallSignature */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 195 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 232 /* FunctionDeclaration */ || context.contextNode.kind === 190 /* FunctionExpression */; + return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 165 /* TypeLiteral */: - case 237 /* ModuleDeclaration */: - case 248 /* ExportDeclaration */: - case 249 /* NamedExports */: - case 242 /* ImportDeclaration */: - case 245 /* NamedImports */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 166 /* TypeLiteral */: + case 242 /* ModuleDeclaration */: + case 253 /* ExportDeclaration */: + case 254 /* NamedExports */: + case 247 /* ImportDeclaration */: + case 250 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 233 /* ClassDeclaration */: - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: - case 267 /* CatchClause */: - case 238 /* ModuleBlock */: - case 225 /* SwitchStatement */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 272 /* CatchClause */: + case 243 /* ModuleBlock */: + case 230 /* SwitchStatement */: return true; - case 211 /* Block */: { + case 216 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 191 /* ArrowFunction */ && blockParent.kind !== 190 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { return true; } } @@ -93698,31 +100796,31 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 215 /* IfStatement */: - case 225 /* SwitchStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: - case 228 /* TryStatement */: - case 216 /* DoStatement */: - case 224 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 229 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 267 /* CatchClause */: + case 272 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 182 /* ObjectLiteralExpression */; + return context.contextNode.kind === 186 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 185 /* CallExpression */; + return context.contextNode.kind === 189 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 186 /* NewExpression */; + return context.contextNode.kind === 190 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -93734,32 +100832,35 @@ var ts; return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 191 /* ArrowFunction */; + return context.contextNode.kind === 195 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 181 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 253 /* JsxElement */ && context.contextNode.kind !== 257 /* JsxFragment */; + return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 263 /* JsxExpression */ || context.contextNode.kind === 262 /* JsxSpreadAttribute */; + return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 260 /* JsxAttribute */; + return context.nextTokenParent.kind === 265 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 260 /* JsxAttribute */; + return context.contextNode.kind === 265 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 254 /* JsxSelfClosingElement */; + return context.contextNode.kind === 259 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -93767,45 +100868,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 149 /* Decorator */; + return node.kind === 150 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 231 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 237 /* ModuleDeclaration */; + return context.contextNode.kind === 242 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 165 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 158 /* ConstructSignature */; + return context.contextNode.kind === 159 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 161 /* TypeReference */: - case 188 /* TypeAssertionExpression */: - case 235 /* TypeAliasDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 205 /* ExpressionWithTypeArguments */: + case 162 /* TypeReference */: + case 192 /* TypeAssertionExpression */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -93816,20 +100917,19 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 188 /* TypeAssertionExpression */; + return context.contextNode.kind === 192 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 194 /* VoidExpression */; + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 201 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 207 /* NonNullExpression */; + return context.contextNode.kind === 211 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -93877,12 +100977,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 144 /* LastKeyword */ && column <= 144 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 144 /* LastToken */ + 1; + var mapRowLength = 145 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -93932,10 +101032,6 @@ var ts; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// -/// -/// /* @internal */ var ts; (function (ts) { @@ -94064,17 +101160,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 238 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 272 /* SourceFile */: - case 211 /* Block */: - case 238 /* ModuleBlock */: + return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 277 /* SourceFile */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -94103,7 +101199,7 @@ var ts; } // pick only errors that fall in range var sorted = errors - .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; @@ -94178,7 +101274,7 @@ var ts; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { return options.indentSize; } previousLine = line; @@ -94231,7 +101327,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 trimTrailingWhitespacesForRemainingRange(); } } @@ -94265,7 +101361,7 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -94297,20 +101393,23 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 233 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 234 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 232 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 236 /* EnumDeclaration */: return 236 /* EnumDeclaration */; - case 155 /* GetAccessor */: return 125 /* GetKeyword */; - case 156 /* SetAccessor */: return 136 /* SetKeyword */; - case 153 /* MethodDeclaration */: + case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; + case 156 /* GetAccessor */: return 125 /* GetKeyword */; + case 157 /* SetAccessor */: return 136 /* SetKeyword */; + case 154 /* MethodDeclaration */: if (node.asteriskToken) { return 39 /* AsteriskToken */; } // falls through - case 151 /* PropertyDeclaration */: - case 148 /* Parameter */: - return ts.getNameOfDeclaration(node).kind; + case 152 /* PropertyDeclaration */: + case 149 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -94334,9 +101433,9 @@ var ts; getIndentation: function () { return indentation; }, getDelta: getDelta, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { indentation += lineAdded ? options.indentSize : -options.indentSize; - delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; } } }; @@ -94354,15 +101453,15 @@ var ts; case 41 /* SlashToken */: case 29 /* GreaterThanToken */: switch (container.kind) { - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: return false; } break; case 21 /* OpenBracketToken */: case 22 /* CloseBracketToken */: - if (container.kind !== 176 /* MappedType */) { + if (container.kind !== 179 /* MappedType */) { return false; } break; @@ -94374,7 +101473,7 @@ var ts; } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node - return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { @@ -94454,7 +101553,7 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 149 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); if (child.kind === 10 /* JsxText */) { @@ -94462,7 +101561,7 @@ var ts; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 181 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -94470,7 +101569,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -94484,8 +101582,8 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -94499,17 +101597,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -94592,6 +101693,7 @@ var ts; } } } + // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -94684,7 +101786,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -94692,18 +101793,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -94829,56 +101930,47 @@ 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); } + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { return undefined; } - if (precedingToken === undefined) { - precedingToken = ts.findPrecedingToken(position, sourceFile); - } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; // 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; + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // 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. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); } formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 191 /* ArrowFunction */: + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 195 /* ArrowFunction */: if (node.typeParameters === list) { return 27 /* LessThanToken */; } @@ -94886,8 +101978,8 @@ var ts; return 19 /* OpenParenToken */; } break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -94895,7 +101987,7 @@ var ts; return 19 /* OpenParenToken */; } break; - case 161 /* TypeReference */: + case 162 /* TypeReference */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -94992,9 +102084,9 @@ var ts; if (options.indentStyle === ts.IndentStyle.None) { 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 precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { @@ -95012,7 +102104,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 198 /* BinaryExpression */) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -95057,14 +102149,14 @@ var ts; var previous; var current = precedingToken; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, /*isNextChild*/ true)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); var indentationDelta = nextTokenKind !== 0 /* Unknown */ // handle cases when codefix is about to be inserted before the close brace ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -95073,7 +102165,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.indentSize; // TODO: GH#18217 } previous = current; current = current.parent; @@ -95123,7 +102215,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } // In our AST, a call argument's `parent` is the call-expression, not the argument list. @@ -95168,7 +102260,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 272 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -95181,7 +102273,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0 /* Unknown */; } @@ -95216,7 +102308,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 215 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -95230,39 +102322,46 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { - case 161 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 182 /* ObjectLiteralExpression */: + case 162 /* TypeReference */: + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); + case 186 /* ObjectLiteralExpression */: return node.parent.properties; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return node.parent.elements; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 154 /* Constructor */: - case 163 /* ConstructorType */: - case 158 /* ConstructSignature */: { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } - case 233 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 186 /* NewExpression */: - case 185 /* CallExpression */: { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); + case 190 /* NewExpression */: + case 189 /* CallExpression */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } - case 231 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 245 /* NamedImports */: - case 249 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + case 236 /* VariableDeclarationList */: + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); + case 250 /* NamedImports */: + case 254 /* NamedExports */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -95301,10 +102400,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: node = node.expression; break; default: @@ -95366,84 +102465,89 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { - case 214 /* ExpressionStatement */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 181 /* ArrayLiteralExpression */: - case 211 /* Block */: - case 238 /* ModuleBlock */: - case 182 /* ObjectLiteralExpression */: - case 165 /* TypeLiteral */: - case 176 /* MappedType */: - case 167 /* TupleType */: - case 239 /* CaseBlock */: - case 265 /* DefaultClause */: - case 264 /* CaseClause */: - case 189 /* ParenthesizedExpression */: - case 183 /* PropertyAccessExpression */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 212 /* VariableStatement */: - case 230 /* VariableDeclaration */: - case 247 /* ExportAssignment */: - case 223 /* ReturnStatement */: - case 199 /* ConditionalExpression */: - case 179 /* ArrayBindingPattern */: - case 178 /* ObjectBindingPattern */: - case 255 /* JsxOpeningElement */: - case 258 /* JsxOpeningFragment */: - case 254 /* JsxSelfClosingElement */: - case 263 /* JsxExpression */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 148 /* Parameter */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 172 /* ParenthesizedType */: - case 187 /* TaggedTemplateExpression */: - case 195 /* AwaitExpression */: - case 249 /* NamedExports */: - case 245 /* NamedImports */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - return true; - } - return false; - } - function nodeWillIndentChild(parent, child, indentByDefault) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 215 /* IfStatement */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 191 /* ArrowFunction */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return childKind !== 211 /* Block */; - case 248 /* ExportDeclaration */: - return childKind !== 249 /* NamedExports */; - case 242 /* ImportDeclaration */: - return childKind !== 243 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 245 /* NamedImports */); - case 253 /* JsxElement */: - return childKind !== 256 /* JsxClosingElement */; - case 257 /* JsxFragment */: - return childKind !== 259 /* JsxClosingFragment */; + case 219 /* ExpressionStatement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 185 /* ArrayLiteralExpression */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 186 /* ObjectLiteralExpression */: + case 166 /* TypeLiteral */: + case 179 /* MappedType */: + case 168 /* TupleType */: + case 244 /* CaseBlock */: + case 270 /* DefaultClause */: + case 269 /* CaseClause */: + case 193 /* ParenthesizedExpression */: + case 187 /* PropertyAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 217 /* VariableStatement */: + case 252 /* ExportAssignment */: + case 228 /* ReturnStatement */: + case 203 /* ConditionalExpression */: + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: + case 259 /* JsxSelfClosingElement */: + case 268 /* JsxExpression */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 149 /* Parameter */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 175 /* ParenthesizedType */: + case 191 /* TaggedTemplateExpression */: + case 199 /* AwaitExpression */: + case 254 /* NamedExports */: + case 250 /* NamedImports */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 152 /* PropertyDeclaration */: + return true; + case 235 /* VariableDeclaration */: + case 273 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 195 /* ArrowFunction */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return childKind !== 216 /* Block */; + case 253 /* ExportDeclaration */: + return childKind !== 254 /* NamedExports */; + case 247 /* ImportDeclaration */: + return childKind !== 248 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); + case 258 /* JsxElement */: + return childKind !== 261 /* JsxClosingElement */; + case 262 /* JsxFragment */: + return childKind !== 264 /* JsxClosingFragment */; + case 172 /* IntersectionType */: + case 171 /* UnionType */: + if (childKind === 166 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -95451,18 +102555,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: { - if (parent.kind !== 211 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */); - } - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: - return true; + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: + return parent.kind !== 216 /* Block */; default: return false; } @@ -95471,12 +102568,18 @@ var ts; * True when the parent node should indent the given child by an explicit rule. * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. */ - function shouldIndentChildNode(parent, child, isNextChild) { + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -95484,7 +102587,7 @@ var ts; var ts; (function (ts) { var textChanges; - (function (textChanges_1) { + (function (textChanges_3) { /** * Currently for simplicity we store recovered positions on the node itself. * It can be changed to side-table later if we decide that current design is too invasive. @@ -95511,7 +102614,7 @@ var ts; (function (Position) { Position[Position["FullStart"] = 0] = "FullStart"; Position[Position["Start"] = 1] = "Start"; - })(Position = textChanges_1.Position || (textChanges_1.Position = {})); + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); function skipWhitespacesAndLineBreaks(text, start) { return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } @@ -95527,7 +102630,7 @@ var ts; } return false; } - textChanges_1.useNonAdjustedPositions = { + textChanges_3.useNonAdjustedPositions = { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true, }; @@ -95536,11 +102639,11 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { return node.getStart(sourceFile); @@ -95570,23 +102673,21 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; /** * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 182 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -95601,9 +102702,9 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - // Map from class id to nodes to insert at the start - this.nodesInsertedAtClassStarts = ts.createMap(); + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; } ChangeTracker.fromContext = function (context) { return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); @@ -95617,13 +102718,11 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; - /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ - 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.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node, }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } @@ -95632,92 +102731,49 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; - ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { - var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); - if (!containingList) { - ts.Debug.fail("node is not a list element"); - return this; - } - var index = ts.indexOfNode(containingList, node); - if (index < 0) { - return this; - } - if (containingList.length === 1) { - this.deleteNode(sourceFile, node); - return this; - } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); - if (nextToken && isSeparator(node, nextToken)) { - // find first non-whitespace position in the leading trivia of the node - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var nextElement = containingList[index + 1]; - /// find first non-whitespace position in the leading trivia of the next node - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } - return this; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -95732,20 +102788,47 @@ var ts; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { if (blankLineBetween === void 0) { blankLineBetween = false; } - var pos = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); - return this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ - ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { - var end = (ts.isFunctionLike(node) - // If no `)`, is an arrow function `x => x`, so use the end of the first parameter - ? ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile) || ts.first(node.parameters) - : node.kind !== 230 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name).end; - this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter @@ -95762,6 +102845,9 @@ var ts; else if (ts.isParameter(before)) { return {}; } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { @@ -95783,7 +102869,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -95793,64 +102879,113 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { - var firstMember = ts.firstOrUndefined(cls.members); - if (!firstMember) { - var id = ts.getNodeId(cls).toString(); - var newMembers = this.nodesInsertedAtClassStarts.get(id); - if (newMembers) { - ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); - newMembers.members.push(newElement); + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; } else { - this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + return { prefix: "", suffix: this.newLineCharacter }; } } else { - this.insertNodeBefore(sourceFile, firstMember, newElement); + return { prefix: this.newLineCharacter, suffix: "" }; } }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { - if (ts.isStatementButNotDeclaration(after) || - after.kind === 151 /* PropertyDeclaration */ || - after.kind === 150 /* PropertySignature */ || - after.kind === 152 /* MethodSignature */) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - options: {}, - range: { pos: after.end, end: after.end }, - node: ts.createToken(25 /* SemicolonToken */) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { - if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { - return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 235 /* VariableDeclaration */: + case 9 /* StringLiteral */: + case 71 /* Identifier */: + return { prefix: ", " }; + case 273 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 84 /* ExportKeyword */: + return { prefix: " " }; + case 149 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; } - else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { - return { suffix: this.newLineCharacter }; + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 195 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + } + if (node.body.kind !== 216 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + } } - else if (ts.isVariableDeclaration(node)) { - return { prefix: ", " }; + else { + var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } - else if (ts.isParameter(node)) { - return {}; - } - return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -95863,7 +102998,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -95907,17 +103042,9 @@ var ts; // let insert position be the beginning of the line that contains next element 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, - options: { - prefix: prefix, - // write separator and leading trivia of the next element as suffix - suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) - } - }); + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -95949,13 +103076,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), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -95963,34 +103084,47 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; - ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.nodesInsertedAtClassStarts.forEach(function (_a) { - var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; - var newCls = cls.kind === 233 /* ClassDeclaration */ - ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) - : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + this.classesWithNodesInsertedAtStart.forEach(function (cls) { + var sourceFile = cls.getSourceFile(); + var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_22 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_22(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } }); }; /** @@ -96000,27 +103134,44 @@ var ts; * so we can only call this once and can't get the non-formatted text separately. */ ChangeTracker.prototype.getChanges = function (validate) { - this.finishInsertNodeAtClassStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); - textChanges_1.ChangeTracker = ChangeTracker; + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + } var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_10 = function (i) { + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_23 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. - for (var i = 0; i < normalized.length - 2; i++) { - _loop_10(i); + for (var i = 0; i < normalized.length - 1; i++) { + _loop_23(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -96029,35 +103180,44 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; } + if (change.kind === ChangeKind.Text) { + return change.text; + } var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; var text = change.kind === ChangeKind.ReplaceWithMultipleNodes - ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (options.suffix || ""); } /** Note: this may mutate `nodeIn`. */ - function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) { - var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text; + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; if (validate) validate(node, text); var formatOptions = formatContext.options; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) - ? (formatOptions.indentSize || 0) - : 0; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(text, changes); @@ -96072,17 +103232,17 @@ var ts; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { - var change = changes[i]; - text = "" + text.substring(0, change.span.start) + change.newText + text.substring(ts.textSpanEnd(change.span)); + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); } return text; } - textChanges_1.applyChanges = applyChanges; + textChanges_3.applyChanges = applyChanges; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); @@ -96239,7 +103399,7 @@ var ts; if (!ranges) return position; // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -96267,6 +103427,201 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 149 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceNode(sourceFile, oldFunction, newFunction); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 247 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 184 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 235 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 148 /* TypeParameter */: { + var typeParam = node; + switch (typeParam.parent.kind) { + case 300 /* JSDocTemplateTag */: + changes.deleteRange(sourceFile, getRangeToDeleteJsDocTag(typeParam.parent, sourceFile)); + break; + case 174 /* InferType */: + // TODO: GH#25594 + break; + default: { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(typeParam.parent); + if (typeParameters.length === 1) { + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1); + var nextToken = ts.getTokenAtPosition(sourceFile, end); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + } + } + break; + } + case 251 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 249 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 272 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 223 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 217 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + function getRangeToDeleteJsDocTag(node, sourceFile) { + var parent = node.parent; + var toDelete = parent.kind === 289 /* JSDocComment */ && parent.comment === undefined && parent.tags.length === 1 ? parent : node; + return ts.createTextRangeFromNode(toDelete, sourceFile); + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -96274,17 +103629,28 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixRegistrations = []; + var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; - var registrations = codeFixRegistrations[error]; - if (!registrations) { - registrations = []; - codeFixRegistrations[error] = registrations; - } - registrations.push(reg); + errorCodeToFixes.add(String(error), reg); } if (reg.fixIds) { for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { @@ -96296,27 +103662,11 @@ var ts; } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixRegistrations); + return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixRegistrations[context.errorCode]; - var allActions = []; - ts.forEach(fixes, function (f) { - var actions = f.getCodeActions(context); - if (actions && actions.length > 0) { - for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { - var action = actions_1[_i]; - if (action === undefined) { - context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); - } - else { - allActions.push(action); - } - } - } - }); - return allActions; + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -96327,27 +103677,27 @@ var ts; function createCombinedCodeActions(changes, commands) { return { changes: changes, commands: commands }; } + codefix.createCombinedCodeActions = createCombinedCodeActions; function createFileTextChanges(fileName, textChanges) { return { fileName: fileName, textChanges: textChanges }; } codefix.createFileTextChanges = createFileTextChanges; function codeFixAll(context, errorCodes, use) { var commands = []; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } + codefix.eachDiagnostic = eachDiagnostic; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -96375,10 +103725,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); /* @internal */ var ts; @@ -96391,13 +103742,13 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); function makeChange(changeTracker, sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var decorator = ts.findAncestor(token, ts.isDecorator); ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); @@ -96418,9 +103769,8 @@ var ts; var decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96430,7 +103780,7 @@ var ts; }); }, }); function getDeclaration(file, pos) { - var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(file, pos); // For an arrow function with no name, 'name' lands on the first parameter. return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); } @@ -96447,7 +103797,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); @@ -96458,7 +103808,7 @@ var ts; if (!param.type) { var paramType = ts.getJSDocType(param); if (paramType) - changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); } } if (needParens) @@ -96466,40 +103816,40 @@ var ts; if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) - changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); } } else { var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. - changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); } } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 /* VariableDeclaration */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 151 /* PropertyDeclaration */; + node.kind === 235 /* VariableDeclaration */ || + node.kind === 151 /* PropertySignature */ || + node.kind === 152 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 278 /* JSDocNonNullableType */: + case 285 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 277 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return transformJSDocTypeReference(node); default: - var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 ts.setEmitFlags(visited, 1 /* SingleLine */); return visited; } @@ -96518,7 +103868,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -96578,15 +103928,13 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, }); function doChange(changes, sourceFile, position, checker) { - var deletedNodes = []; - var deletes = []; - var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; @@ -96595,46 +103943,29 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); + changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); } else { - deleteNode(ctorDeclaration, /*inList*/ true); + changes.delete(sourceFile, ctorDeclaration); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); break; } if (!newClassDeclaration) { return undefined; } - copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - 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 changes.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changes.deleteNode(sourceFile, node); }); - } - } function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol @@ -96662,8 +103993,8 @@ var ts; return ts.isFunctionLike(source); } function createClassElement(symbol, modifiers) { - // both properties and methods are bound as property symbols - if (!(symbol.flags & 4 /* Property */)) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { return; } var memberDeclaration = symbol.valueDeclaration; @@ -96672,28 +104003,28 @@ var ts; 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 === 214 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); + changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 190 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 191 /* ArrowFunction */: { + case 195 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 211 /* Block */) { + if (arrowFunctionBody.kind === 216 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -96703,7 +104034,7 @@ var ts; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } default: { @@ -96713,7 +104044,7 @@ var ts; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); return prop; } } @@ -96721,13 +104052,13 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { return undefined; } if (node.name.kind !== 71 /* Identifier */) { return undefined; } - var memberElements = createClassElementsFromSymbol(initializer.symbol); + var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } @@ -96749,21 +104080,6 @@ var ts; return cls; } } - function copyComments(sourceNode, targetNode, sourceFile) { - 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 getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } @@ -96777,54 +104093,49 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); // No support for fix-all since this applies to the whole file at once anyway. - return [{ description: description, changes: changes, fixId: undefined }]; + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); if (!imported || imported.resolvedFileName !== exportingFile.fileName) { continue; } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252 /* ExternalModuleReference */: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 246 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - } - case 185 /* CallExpression */: { - var call = parent; - if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + case 189 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } break; - } } } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -96859,24 +104170,24 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 212 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + case 217 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 214 /* ExpressionStatement */: { + case 219 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 185 /* CallExpression */: { - if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + case 189 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 198 /* BinaryExpression */: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + case 202 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -96885,28 +104196,28 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - // `const alias = module.exports;` can be removed. - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - // Move it out to its own variable statement. - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); }); if (foundImport) { // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. @@ -96914,74 +104225,79 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: { + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; if (!ts.isPropertyAccessExpression(left)) { return false; } if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, statement); + changes.delete(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } /** * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 269 /* ShorthandPropertyAssignment */: - case 270 /* SpreadAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 275 /* SpreadAssignment */: return undefined; - case 268 /* PropertyAssignment */: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153 /* MethodDeclaration */: + case 273 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 154 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + function convertNamedExport(sourceFile, assignment, changes, exports) { // If "originalKeywordKind" was set, this is e.g. `exports. - var text = propertyName.text; + var text = assignment.left.name.text; var rename = exports.get(text); if (rename !== undefined) { /* @@ -96989,37 +104305,13 @@ var ts; export { _class as class }; */ var newNodes = [ - makeConst(/*modifiers*/ undefined, rename, right), + makeConst(/*modifiers*/ undefined, rename, assignment.right), makeExportDeclaration([ts.createExportSpecifier(rename, text)]), ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); } else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + convertExportsPropertyAssignment(assignment, sourceFile, changes); } } function convertReExportAll(reExported, checker) { @@ -97040,10 +104332,28 @@ var ts; function reExportDefault(moduleSpecifier) { return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); } - function convertExportsDotXEquals(name, exported) { + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { var modifiers = [ts.createToken(84 /* ExportKeyword */)]; switch (exported.kind) { - case 190 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -97051,10 +104361,10 @@ var ts; } } // falls through - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -97062,7 +104372,7 @@ var ts; } function exportConst() { // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 } } /** @@ -97070,41 +104380,41 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: { + case 182 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 179 /* ArrayBindingPattern */: { + case 183 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; */ - var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } /** * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -97139,7 +104449,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -97151,20 +104461,26 @@ var ts; } function collectFreeIdentifiers(file) { var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); return map; } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return parent.name !== node; - case 180 /* BindingElement */: + case 184 /* BindingElement */: + return parent.propertyName !== node; + case 251 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -97179,19 +104495,11 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier)); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -97219,8 +104527,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97231,7 +104539,7 @@ var ts; }); }, }); function getQualifiedName(sourceFile, pos) { - var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; } @@ -97257,11 +104565,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -97272,29 +104577,33 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var implementedType = checker.getTypeAtLocation(implementedTypeNode); var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -97302,6 +104611,14 @@ var ts; } } } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -97309,6 +104626,594 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 2 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { + var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + } + } + }); + return result; + } + function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 247 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 247 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, _b) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; + var imports = _b.imports; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + }); + // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together + return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 247 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : getFixesInfoForNonUMDImport(context, symbolToken); + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }]; + var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) + return undefined; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) { + var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); + if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultExport, 1 /* Default */); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + var checker = program.getTypeChecker(); + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getAliasedSymbol(defaultExport); + return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + } + else { + var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target); + return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; + } + case 2 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken; + changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67901928 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67216319 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, @@ -97320,94 +105225,131 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + if (info.kind === InfoKind.enum) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenNames = ts.createMap(); - return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; - var info = getInfo(diag.file, diag.start, program.getTypeChecker()); - if (!info) - return; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - if (!ts.addToSeen(seenNames, token.text)) { - return; - } - // Always prefer to add a method declaration if possible. - if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); - } - else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var classToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === InfoKind.enum) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { - var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); } - } - }); + }); + classToMembers.forEach(function (infos, classDeclaration) { + var superClasses = getAllSuperClasses(classDeclaration, checker); + var _loop_24 = function (info) { + // If some superclass added this property, don't add it again. + if (superClasses.some(function (superClass) { + var superInfos = classToMembers.get(superClass); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_24(info); + } + }); + })); }, }); + function getAllSuperClasses(cls, checker) { + var res = []; + while (cls) { + var superElement = ts.getClassExtendsHeritageElement(cls); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + cls = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["enum"] = 0] = "enum"; + InfoKind[InfoKind["class"] = 1] = "class"; + })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); if (!ts.isIdentifier(token)) { return undefined; } - var classAndMakeStatic = getClassAndMakeStatic(token, checker); - if (!classAndMakeStatic) { - return undefined; - } - var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); - var call = ts.tryCast(token.parent.parent, ts.isCallExpression); - return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; - } - function getClassAndMakeStatic(token, checker) { var parent = token.parent; - if (!ts.isPropertyAccessExpression(parent)) { + if (!ts.isPropertyAccessExpression(parent)) return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); + if (classDeclaration) { + var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; } - if (parent.expression.kind === 99 /* ThisKeyword */) { - var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); - if (!ts.isClassElement(containingClassMemberDeclaration)) { - return undefined; - } - var classDeclaration = containingClassMemberDeclaration.parent; - // Property accesses on `this` in a static method are accesses of a static member. - return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */) } : undefined; - } - else { - var leftExpressionType = checker.getTypeAtLocation(parent.expression); - var symbol = leftExpressionType.symbol; - if (!(symbol && leftExpressionType.flags & 65536 /* Object */ && symbol.flags & 32 /* Class */)) { - return undefined; - } - var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); - // The expression is a class symbol but the type is not the instance-side. - return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration }; } + return undefined; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 203 /* ClassExpression */) { + if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -97433,7 +105375,7 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 198 /* BinaryExpression */) { + if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); @@ -97442,9 +105384,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( @@ -97452,7 +105393,24 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. @@ -97468,82 +105426,34 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); - } - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "fixSpelling"; - var errorCodes = [ - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); - if (!info) - return undefined; - var node = info.node, suggestion = info.suggestion; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); - if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion); - }); }, - }); - function getInfo(sourceFile, pos, checker) { - // This is the identifier of the misspelled word. eg: - // this.speling = 1; - // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 - var suggestion; - if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); - var containingType = checker.getTypeAtLocation(node.parent.expression); - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences); + var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); } else { - var meaning = ts.getMeaningFromLocation(node); - var name = ts.getTextOfNode(node); - ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; } - function doChange(changes, sourceFile, node, suggestion) { - changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); - } - function convertSemanticMeaningToSymbolFlags(meaning) { - var flags = 0; - if (meaning & 4 /* Namespace */) { - flags |= 1920 /* Namespace */; - } - if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; - } - if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; - } - return flags; + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 68 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97553,39 +105463,36 @@ var ts; var codefix; (function (codefix) { var fixId = "fixCannotFindModule"; - var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); + return packageName === undefined ? [] + : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; - // If !registry, registry not available yet, can't do anything. - return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; - } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97604,9 +105511,9 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -97614,7 +105521,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes); + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); } }); }, @@ -97622,16 +105529,16 @@ var ts; function getClass(sourceFile, pos) { // Token is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -97657,7 +105564,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -97676,10 +105583,10 @@ var ts; }); function doChange(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); - changes.deleteNode(sourceFile, superCall); + changes.delete(sourceFile, superCall); } function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); if (token.kind !== 99 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); @@ -97710,7 +105617,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97718,7 +105625,7 @@ var ts; }); }, }); function getNode(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); return token.parent; } @@ -97744,7 +105651,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97754,13 +105661,13 @@ var ts; }); }, }); function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && heritageClauses[0].token === 85 /* ExtendsKeyword */ && @@ -97786,34 +105693,40 @@ var ts; var codefix; (function (codefix) { var fixId = "forgottenThisPropertyAccess"; - var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = getNode(sourceFile, context.span.start); - if (!token) { + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); - function getNode(sourceFile, pos) { - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); - return ts.isIdentifier(node) ? node : undefined; + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; } - function doChange(changes, sourceFile, token) { - if (!token) { - return; - } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper - ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97822,70 +105735,106 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var importDecl = tryGetFullImport(token); if (importDecl) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_import_from_0), [ts.showModuleSpecifier(importDecl)]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); - return [{ description: description, changes: changes, fixId: fixIdDelete }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: { + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); - return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + function tryGetFullImport(token) { + return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } - function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); - // this handles var ["computed"] = 12; - return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 149 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. @@ -97895,170 +105844,174 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 148 /* Parameter */: + case 149 /* Parameter */: return true; - case 230 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 220 /* ForOfStatement */: - case 219 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: return true; } } } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { - switch (token.kind) { - case 71 /* Identifier */: - tryDeleteIdentifier(changes, sourceFile, token); - break; - case 151 /* PropertyDeclaration */: - case 244 /* NamespaceImport */: - changes.deleteNode(sourceFile, token.parent); - break; - default: - tryDeleteDefault(changes, sourceFile, token); - } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); } - function tryDeleteDefault(changes, sourceFile, token) { - if (ts.isDeclarationName(token)) { - changes.deleteNode(sourceFile, token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - changes.deleteNode(sourceFile, token.parent.parent); - } - } - function tryDeleteIdentifier(changes, sourceFile, identifier) { - var parent = identifier.parent; - switch (parent.kind) { - case 230 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent); - break; - case 147 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 148 /* Parameter */: - var oldFunction = parent.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { - // Lambdas with exactly one parameter are special because, after removal, there - // must be an empty parameter list (i.e. `()`) and this won't necessarily be the - // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - // handle case where 'import a = A;' - case 241 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 241 /* ImportEqualsDeclaration */); - changes.deleteNode(sourceFile, importEquals); - break; - case 246 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - tryDeleteNamedImportBinding(changes, sourceFile, namedImports); - } - else { - // delete import specifier - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { // |import d from './file'| - changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */)); - } - else { - // import |d,| * as ns from './file' - var start = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); - changes.deleteRange(sourceFile, { pos: start, end: end }); - } - else { - changes.deleteNode(sourceFile, importClause.name); - } - } - break; - case 244 /* NamespaceImport */: - tryDeleteNamedImportBinding(changes, sourceFile, parent); - break; - default: - tryDeleteDefault(changes, sourceFile, identifier); - break; - } - } - function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ref.parent.kind === 187 /* PropertyAccessExpression */) + ref = ref.parent; + if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + changes.delete(sourceFile, ref.parent.parent); } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 242 /* ImportDeclaration */); - changes.deleteNode(sourceFile, importDecl); + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); } } - // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { - switch (varDecl.parent.parent.kind) { - case 218 /* ForStatement */: { - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - changes.deleteNode(sourceFile, forInitializer); - } - else { - changes.deleteNodeInList(sourceFile, varDecl); - } - break; - } - case 220 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 231 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); - break; - case 219 /* ForInStatement */: - case 228 /* TryStatement */: - break; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - changes.deleteNode(sourceFile, variableStatement); - } - else { - changes.deleteNodeInList(sourceFile, varDecl); - } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); } } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 154 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + return true; + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 157 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -98079,18 +106032,16 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; - if (typeNode.kind === 277 /* JSDocNullableType */) { + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 284 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = checker.typeToString(type); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]); + function fix(type, fixId, fixAllDescription) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], @@ -98102,16 +106053,16 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 277 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { - var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } @@ -98119,22 +106070,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 206 /* AsExpression */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 232 /* FunctionDeclaration */: - case 155 /* GetAccessor */: - case 159 /* IndexSignature */: - case 176 /* MappedType */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 156 /* SetAccessor */: - case 235 /* TypeAliasDeclaration */: - case 188 /* TypeAssertionExpression */: - case 230 /* VariableDeclaration */: + case 210 /* AsExpression */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 237 /* FunctionDeclaration */: + case 156 /* GetAccessor */: + case 160 /* IndexSignature */: + case 179 /* MappedType */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 157 /* SetAccessor */: + case 240 /* TypeAliasDeclaration */: + case 192 /* TypeAssertionExpression */: + case 235 /* VariableDeclaration */: return true; default: return false; @@ -98160,7 +106111,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -98181,24 +106132,27 @@ var ts; } } function getNodes(sourceFile, start) { - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -98220,708 +106174,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var ChangeTracker = ts.textChanges.ChangeTracker; - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: getImportCodeActions, - // TODO: GH#20315 - fixIds: [], - getAllCodeActions: ts.notImplemented, - }); - function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); - // TODO: GH#20315 - return { description: description, changes: changes, fixId: undefined }; - } - function convertToImportCodeFixContext(context, symbolToken, symbolName) { - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var program = context.program; - var checker = program.getTypeChecker(); - return { - host: context.host, - formatContext: context.formatContext, - sourceFile: context.sourceFile, - program: program, - checker: checker, - compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], - getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), - symbolName: symbolName, - symbolToken: symbolToken - }; - } - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { - var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); - ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); - // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; - return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; - } - codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { - var result = []; - forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { - var exported = _a[_i]; - if (ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); - } - } - }); - return result; - } - function getCodeActionsForImport(exportInfos, context) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var useExistingImportActions = !context.symbolToken || !ts.isIdentifier(context.symbolToken) ? ts.emptyArray : ts.mapDefined(existingImports, function (_a) { - var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - return getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken); - } - } - }); - return useExistingImportActions.concat(getCodeActionsForAddImport(exportInfos, context, existingImports)); - } - function getNamespaceImportName(declaration) { - if (declaration.kind === 242 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 244 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } - // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; - }); - } - return cached; - } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242 /* ImportDeclaration */: - return parent; - case 252 /* ExternalModuleReference */: - return parent.parent; - case 248 /* ExportDeclaration */: - case 185 /* CallExpression */: // For "require()" calls - // Ignore these, can't add imports to them. - return undefined; - default: - ts.Debug.fail(); - } - } - function getCodeActionForNewImport(context, _a) { - var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); - var importDecl = importKind !== 3 /* Equals */ - ? ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier) - : ts.createImportEqualsDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); - var changes = ChangeTracker.with(context, function (changeTracker) { - if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); - } - else { - changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); - } - }); - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); - } - function createStringLiteralWithQuoteStyle(sourceFile, text) { - var literal = ts.createLiteral(text); - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - return literal; - } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } - function createImportClauseOfKind(kind, symbolName) { - var id = ts.createIdentifier(symbolName); - switch (kind) { - case 1 /* Default */: - return ts.createImportClause(id, /*namedBindings*/ undefined); - case 2 /* Namespace */: - return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); - case 0 /* Named */: - return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); - default: - ts.Debug.assertNever(kind); - } - } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var addJsExtension = usesJsExtensionOnImports(sourceFile); - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); - }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); - } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // 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; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; - } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 242 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - return [fromExistingImport]; - } - var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - var newImportInfos = existingDeclaration - ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); - return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); - } - function newImportInfoFromExistingSpecifier(_a) { - var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 242 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 252 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) ? { moduleSpecifier: expression.text, importKind: importKind } : undefined; - } - function tryUpdateExistingImport(context, importClause, importKind) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - var name = importClause.name; - var namedBindings = (importClause.kind !== 241 /* ImportEqualsDeclaration */ && importClause).namedBindings; - switch (importKind) { - case 1 /* Default */: - return name ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); - }); - case 0 /* Named */: { - var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); - if (namedBindings && namedBindings.kind === 245 /* NamedImports */ && namedBindings.elements.length !== 0) { - // There are already named imports; add another. - return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); - } - if (!namedBindings || namedBindings.kind === 245 /* NamedImports */ && namedBindings.elements.length === 0) { - return ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); - }); - } - return undefined; - } - case 2 /* Namespace */: - return namedBindings ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); - }); - case 3 /* Equals */: - return undefined; - default: - ts.Debug.assertNever(importKind); - } - } - function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - var changes = ChangeTracker.with(context, function (tracker) { - return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); - }); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); - } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } - function getActionsForUMDImport(context) { - var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var umdSymbol; - if (ts.isIdentifier(token)) { - // try the identifier to see if it is the umd symbol - umdSymbol = checker.getSymbolAtLocation(token); - } - if (!ts.isUMDExportSymbol(umdSymbol)) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - var parent = token.parent; - var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); - if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); - } - } - if (ts.isUMDExportSymbol(umdSymbol)) { - var symbol = checker.getAliasedSymbol(umdSymbol); - if (symbol) { - return getCodeActionsForImport([{ moduleSymbol: symbol, importKind: getUmdImportKind(context.program.getCompilerOptions()) }], convertToImportCodeFixContext(context, token, umdSymbol.name)); - } - } - return undefined; - } - function getUmdImportKind(compilerOptions) { - // Import a synthetic `default` if enabled. - if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { - return 1 /* Default */; - } - // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. - var moduleKind = ts.getEmitModuleKind(compilerOptions); - switch (moduleKind) { - case ts.ModuleKind.AMD: - case ts.ModuleKind.CommonJS: - case ts.ModuleKind.UMD: - return 3 /* Equals */; - case ts.ModuleKind.System: - case ts.ModuleKind.ES2015: - case ts.ModuleKind.ESNext: - case ts.ModuleKind.None: - // Fall back to the `import * as ns` style import. - return 2 /* Namespace */; - default: - return ts.Debug.assertNever(moduleKind); - } - } - function getActionsForNonUMDImport(context) { - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. - var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; - var checker = program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { - return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); - // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. - // Maps symbol id to info for modules providing that symbol (original export + re-exports). - var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); - } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { - cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || - getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { - addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); - } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); - } - function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { - if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.escapedText; - } - } - else if (ts.isExportSpecifier(declaration)) { - ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } - } - }); - } - }); - return ts.arrayFrom(ts.flatMapIterator(originalSymbolToExportInfos.values(), function (exportInfos) { return getCodeActionsForImport(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName)); })); - } - function checkSymbolHasMeaning(_a, meaning) { - var declarations = _a.declarations; - return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); - } - function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { - forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { - if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { - cb(module); - } - }); - } - codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); - } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); - } - } - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); - } - function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); - } - codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; - function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { - var res = ""; - var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); - if (ts.isIdentifierStart(firstCharCode, target)) { - res += String.fromCharCode(firstCharCode); - } - else { - lastCharWasValid = false; - } - for (var i = 1; i < moduleSpecifier.length; i++) { - var ch = moduleSpecifier.charCodeAt(i); - var isValid = ts.isIdentifierPart(ch, target); - if (isValid) { - var char = String.fromCharCode(ch); - if (!lastCharWasValid) { - char = char.toUpperCase(); - } - res += char; - } - lastCharWasValid = isValid; - } - // Need `|| "_"` to ensure result isn't empty. - return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; - } - codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var codefix; - (function (codefix) { + var fixName = "disableJsDiagnostics"; var fixId = "disableJsDiagnostics"; var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { var diag = ts.Diagnostics[key]; @@ -98935,23 +106188,15 @@ var ts; return undefined; } var fixes = [ - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective - ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), - ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - } + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), ]; - if (isValidSuppressLocation(sourceFile, span.start)) { - fixes.unshift({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), - fixId: fixId, - }); + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; }, @@ -98959,32 +106204,18 @@ var ts; getAllCodeActions: function (context) { var seenLines = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - if (isValidSuppressLocation(diag.file, diag.start)) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function isValidSuppressLocation(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); - } function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; // Only need to add `// @ts-ignore` for a line once. - if (seenLines && !ts.addToSeen(seenLines, lineNumber)) { - return; + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); - var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); - // First try to see if we can put the '// @ts-ignore' on the previous line. - // We need to make sure that we are not in the middle of a string literal or a comment. - // If so, we do not want to separate the node from its comment if we can. - // Otherwise, add an extra new line immediately before the error span. - var insertAtLineStart = isValidSuppressLocation(sourceFile, startPosition); - var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - var clone = ts.setStartsOnNewLine(ts.getSynthesizedDeepClone(token), true); - ts.addSyntheticLeadingComment(clone, 2 /* SingleLineCommentTrivia */, " @ts-ignore"); - changes.replaceNode(sourceFile, token, clone, { preserveLeadingWhitespace: true, prefix: insertAtLineStart ? undefined : changes.newLineCharacter }); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -98999,12 +106230,12 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } @@ -99012,30 +106243,29 @@ var ts; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; - // Clone name to remove leading trivia. - var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 150 /* PropertySignature */: - case 151 /* PropertyDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 151 /* PropertySignature */: + case 152 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 152 /* MethodSignature */: - case 153 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 154 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -99050,21 +106280,21 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. - outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -99075,7 +106305,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 153 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } @@ -99086,24 +106316,35 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function getSynthesizedDeepClones(nodes) { - return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); - } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { - var typeArguments = _a.typeArguments, args = _a.arguments; + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) { + var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + var type = checker.getTypeAtLocation(arg); + if (type === undefined) { + return undefined; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + return checker.typeToTypeNode(type); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ undefined, methodName, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), - /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, inJs) { + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -99112,13 +106353,13 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -99138,7 +106379,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -99150,16 +106391,16 @@ var ts; } return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined); + /*returnType*/ undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { + function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), - /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], /*multiline*/ true); } function createVisibilityModifier(flags) { @@ -99202,50 +106443,53 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); - if (changes.length === 0) - return undefined; - var name = ts.getNameOfDeclaration(declaration).getText(); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name]); - return [{ description: description, changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } + var parent = token.parent; switch (errorCode) { // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - annotateVariableDeclaration(changes, sourceFile, token.parent, program, cancellationToken); - return token.parent; + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -99261,8 +106505,8 @@ var ts; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { - var param = ts.cast(token.parent, ts.isParameter); + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; } @@ -99286,19 +106530,6 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { if (ts.isIdentifier(declaration.name)) { annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); @@ -99306,11 +106537,11 @@ var ts; } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: return true; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return !!declaration.name; } return false; @@ -99342,13 +106573,14 @@ var ts; function annotate(changes, sourceFile, declaration, type, program) { var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); if (typeNode) - changes.insertTypeAnnotation(sourceFile, declaration, typeNode); + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } function getTypeNodeIfAccessible(type, enclosingScope, checker) { var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; }, reportInaccessibleThisError: notAccessible, @@ -99368,11 +106600,11 @@ var ts; } function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { switch (containingFunction.kind) { - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 154 /* Constructor */; + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 155 /* Constructor */; var searchToken = isConstructor ? ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : containingFunction.name; @@ -99406,7 +106638,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - var isConstructor = declaration.kind === 154 /* Constructor */; + var isConstructor = declaration.kind === 155 /* Constructor */; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; @@ -99438,21 +106670,21 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: usageContext.isNumber = true; break; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); break; - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpressionContext(node.parent, checker, usageContext); } @@ -99460,12 +106692,22 @@ var ts; inferTypeFromContextualType(node, checker, usageContext); } break; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 235 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -99526,7 +106768,7 @@ var ts; case 29 /* GreaterThanToken */: case 31 /* GreaterThanEqualsToken */: var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 272 /* EnumLike */) { + if (operandType.flags & 544 /* EnumLike */) { addCandidateType(usageContext, operandType); } else { @@ -99536,13 +106778,13 @@ var ts; case 59 /* PlusEqualsToken */: case 37 /* PlusToken */: var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 272 /* EnumLike */) { + if (otherOperandType.flags & 544 /* EnumLike */) { addCandidateType(usageContext, otherOperandType); } - else if (otherOperandType.flags & 84 /* NumberLike */) { + else if (otherOperandType.flags & 168 /* NumberLike */) { usageContext.isNumber = true; } - else if (otherOperandType.flags & 524322 /* StringLike */) { + else if (otherOperandType.flags & 68 /* StringLike */) { usageContext.isString = true; } else { @@ -99565,7 +106807,7 @@ var ts; // LogicalOperator case 54 /* BarBarToken */: if (node === parent.left && - (node.parent.parent.kind === 230 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); @@ -99593,7 +106835,7 @@ var ts; } } inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 185 /* CallExpression */) { + if (parent.kind === 189 /* CallExpression */) { (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); } else { @@ -99618,7 +106860,7 @@ var ts; var indexType = checker.getTypeAtLocation(parent); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 84 /* NumberLike */) { + if (indexType.flags & 168 /* NumberLike */) { usageContext.numberIndexContext = indexUsageContext; } else { @@ -99637,10 +106879,10 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } @@ -99648,7 +106890,7 @@ var ts; return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_5 = ts.createUnderscoreEscapedMap(); + var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; @@ -99657,7 +106899,7 @@ var ts; usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_5.set(name, symbol); + members_6.set(name, symbol); }); } if (usageContext.callContexts) { @@ -99673,12 +106915,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 } if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -99713,15 +106955,16 @@ var ts; parameters.push(symbol); } var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 16384 /* Never */)) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { (context.candidateTypes || (context.candidateTypes = [])).push(type); } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -99731,29 +106974,14 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], - getCodeActions: getActionsForInvalidImport - }); - function getActionsForInvalidImport(context) { - var sourceFile = context.sourceFile; - // This is the whole import statement, eg: - // import * as Bluebird from 'bluebird'; - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; - if (!ts.isImportDeclaration(node)) { - // No import quick fix for import calls - return []; - } - return getCodeFixesForImportDeclaration(context, node); - } + var fixName = "invalidImportSyntax"; function getCodeFixesForImportDeclaration(context, node) { var sourceFile = ts.getSourceFileOfNode(node); var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -99763,12 +106991,8 @@ var ts; return variations; } function createAction(context, sourceFile, node, replacement) { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -99779,25 +107003,55 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 185 /* CallExpression */ : 186 /* NewExpression */; - var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; } var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } var fixes = []; - var relatedImport = type.symbol.originatingImport; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -99807,6 +107061,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixName = "strictClassInitialization"; var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; var fixIdAddInitializer = "addMissingPropertyInitializer"; @@ -99817,24 +107072,22 @@ var ts; var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); if (!propertyDeclaration) return; - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); var result = [ getActionForAddMissingUndefinedType(context, propertyDeclaration), - getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) ]; - ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter)); + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: function (context) { - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); if (!propertyDeclaration) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter); + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); break; case fixIdAddUndefinedType: addUndefinedType(changes, diag.file, propertyDeclaration); @@ -99844,7 +107097,7 @@ var ts; var initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return; - addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter); + addInitializer(changes, diag.file, propertyDeclaration, initializer); break; default: ts.Debug.fail(JSON.stringify(context.fixId)); @@ -99853,75 +107106,101 @@ var ts; }, }); function getPropertyDeclaration(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; } - function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); }); - return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions }; + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } - function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) { + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); - return { description: description, changes: changes, fixId: fixIdAddUndefinedType }; + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); - var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } - function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) { + function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); var initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); }); - return { description: description, changes: changes, fixId: fixIdAddInitializer }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); } - function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) { + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 2 /* String */) { - return ts.createLiteral(""); + if (type.flags & 256 /* BooleanLiteral */) { + return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); } - else if (type.flags & 4 /* Number */) { - return ts.createNumericLiteral("0"); - } - else if (type.flags & 8 /* Boolean */) { - return ts.createFalse(); - } - else if (type.flags & 224 /* Literal */) { + else if (type.isLiteral()) { return ts.createLiteral(type.value); } - else if (type.flags & 131072 /* Union */) { + else if (type.isUnion()) { return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); } - else if (ts.getObjectFlags(type) & 1 /* Class */) { + else if (type.isClass()) { var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) return undefined; - var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); if (constructorDeclaration && constructorDeclaration.parameters.length) return undefined; return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } return undefined; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -99934,19 +107213,18 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); - return [{ description: description, changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { - var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(sourceFile, pos); if (!ts.isIdentifier(name)) return undefined; // bad input var parent = name.parent; @@ -99958,37 +107236,421 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 91 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return undefined; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 217 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + break; + case 217 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 248 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 249 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + if (spec.kind === 251 /* ImportSpecifier */) { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(spec.name.text); + if (spec.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, spec.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, spec); + changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); + } + } + else { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return undefined; + var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 249 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_25 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_25(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -100003,7 +107665,7 @@ var ts; * Exported for tests. */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -100072,8 +107734,8 @@ var ts; extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); - var targetRange = rangeToExtract.targetRange; + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { var index = +parsedFunctionIndexMatch[1]; @@ -100144,9 +107806,9 @@ var ts; } // 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); + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); // Do the same for the ending position - var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var end = ts.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. @@ -100165,7 +107827,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -100198,7 +107861,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -100240,20 +107903,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 151 /* PropertyDeclaration */) { + if (current.kind === 152 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 148 /* Parameter */) { + else if (current.kind === 149 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 154 /* Constructor */) { + if (ctorOrMethod.kind === 155 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 153 /* MethodDeclaration */) { + else if (current.kind === 154 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -100277,7 +107940,7 @@ var ts; if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (nodeToCheck.flags & 2097152 /* Ambient */) { + if (nodeToCheck.flags & 4194304 /* Ambient */) { 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) @@ -100296,8 +107959,11 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 230 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } @@ -100305,15 +107971,15 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); 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 === 185 /* CallExpression */) { + if (node.parent.kind === 189 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; @@ -100324,10 +107990,10 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -100339,20 +108005,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 215 /* IfStatement */: + case 220 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 228 /* TryStatement */: + case 233 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 211 /* Block */: - if (node.parent && node.parent.kind === 228 /* TryStatement */ && node.parent.finallyBlock === node) { + case 216 /* Block */: + if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 264 /* CaseClause */: + case 269 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -100364,11 +108030,11 @@ var ts; break; } switch (node.kind) { - case 173 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -100376,8 +108042,8 @@ var ts; seenLabels.pop(); break; } - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: { var label = node.label; if (label) { @@ -100387,20 +108053,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 222 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -100454,7 +108120,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 148 /* Parameter */) { + if (current.kind === 149 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -100465,7 +108131,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 272 /* SourceFile */) { + if (current.kind === 277 /* SourceFile */) { return scopes; } } @@ -100474,7 +108140,7 @@ var ts; function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { @@ -100555,32 +108221,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: return "constructor"; - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return "arrow function"; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return "method '" + scope.name.getText(); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 233 /* ClassDeclaration */ + return scope.kind === 238 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 238 /* ModuleBlock */ + return scope.kind === 243 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -100589,13 +108255,6 @@ var ts; SpecialScope[SpecialScope["Module"] = 0] = "Module"; SpecialScope[SpecialScope["Global"] = 1] = "Global"; })(SpecialScope || (SpecialScope = {})); - function getUniqueName(baseName, fileText) { - var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { - nameText = baseName + "_" + i; - } - return nameText; - } /** * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors @@ -100605,7 +108264,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -100646,7 +108305,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -100796,7 +108455,7 @@ var ts; var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; function getTypeDeepCloneUnionUndefined(typeNode) { if (typeNode === undefined) { @@ -100821,11 +108480,11 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable var file = scope.getSourceFile(); - var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -100841,14 +108500,14 @@ var ts; /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion - ? ts.createIdentifier(scope.name.getText()) + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 : ts.createThis(), ts.createIdentifier(localNameText)); // Declare var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -100863,14 +108522,14 @@ var ts; changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 214 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement( @@ -100884,19 +108543,19 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 214 /* ExpressionStatement */) { + if (node.parent.kind === 219 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. - changeTracker.deleteNode(context.file, node.parent, ts.textChanges.useNonAdjustedPositions); + changeTracker.delete(context.file, node.parent); } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } var edits = changeTracker.getChanges(); var renameFilename = node.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { @@ -100912,36 +108571,6 @@ var ts; node = node.parent; } } - /** - * @return The index of the (only) reference to the extracted symbol. We want the cursor - * to be on the reference, rather than the declaration, because it's closer to where the - * user was before extracting it. - */ - function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { - var delta = 0; - var lastPos = -1; - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; - ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { - var change = textChanges_3[_b]; - var span_14 = change.span, newText = change.newText; - var index = newText.indexOf(functionNameText); - if (index !== -1) { - lastPos = span_14.start + delta + index; - // If the reference comes first, return immediately. - if (!isDeclaredBeforeUse) { - return lastPos; - } - } - delta += newText.length - span_14.length; - } - } - // If the declaration comes first, return the position of the last occurrence. - ts.Debug.assert(isDeclaredBeforeUse); - ts.Debug.assert(lastPos >= 0); - return lastPos; - } function getFirstDeclaration(type) { var firstDeclaration; var symbol = type.symbol; @@ -100965,7 +108594,7 @@ var ts; function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); if (ts.isClassLike(scope)) { - var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 return ts.createPropertyAccess(lhs, functionReference); } else { @@ -101001,7 +108630,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 223 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -101037,7 +108666,7 @@ var ts; } function getStatementsOrClassElements(scope) { if (ts.isFunctionLikeDeclaration(scope)) { - var body = scope.body; + var body = scope.body; // TODO: GH#18217 if (ts.isBlock(body)) { return body.statements; } @@ -101067,8 +108696,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember; var allProperties = true; - for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { - var member = members_6[_i]; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -101082,7 +108711,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -101109,18 +108739,15 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined @@ -101173,7 +108800,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -101181,7 +108808,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 232 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -101206,7 +108833,7 @@ var ts; // will use the contextual type of an expression as the return type of the extracted // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { - var contextualType = checker.getContextualType(targetRange.range); + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { @@ -101221,8 +108848,8 @@ var ts; i_1++; } // Note that we add the current node's type parameters *after* updating the corresponding scope. - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -101244,7 +108871,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_11 = function (i) { + var _loop_26 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -101284,21 +108911,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_11(i); + _loop_26(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { // PERF: This is potentially very expensive. `type` could be a library type with @@ -101308,7 +108925,7 @@ var ts; var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 32768 /* TypeParameter */) { + if (visitedType.isTypeParameter()) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } @@ -101497,20 +109114,6 @@ var ts; : 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; - } - } - 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. @@ -101519,31 +109122,32 @@ var ts; * in the sense of something that you could extract on */ function isExtractableExpression(node) { - switch (node.parent.kind) { - case 271 /* EnumMember */: + var parent = node.parent; + switch (parent.kind) { + case 276 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 242 /* ImportDeclaration */ && - node.parent.kind !== 246 /* ImportSpecifier */; - case 202 /* SpreadElement */: - case 178 /* ObjectBindingPattern */: - case 180 /* BindingElement */: + return parent.kind !== 247 /* ImportDeclaration */ && + parent.kind !== 251 /* ImportSpecifier */; + case 206 /* SpreadElement */: + case 182 /* ObjectBindingPattern */: + case 184 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 180 /* BindingElement */ && - node.parent.kind !== 246 /* ImportSpecifier */ && - node.parent.kind !== 250 /* ExportSpecifier */; + return parent.kind !== 184 /* BindingElement */ && + parent.kind !== 251 /* ImportSpecifier */ && + parent.kind !== 255 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 211 /* Block */: - case 272 /* SourceFile */: - case 238 /* ModuleBlock */: - case 264 /* CaseClause */: + case 216 /* Block */: + case 277 /* SourceFile */: + case 243 /* ModuleBlock */: + case 269 /* CaseClause */: return true; default: return false; @@ -101552,48 +109156,948 @@ var ts; })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return undefined; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJavaScript(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + return true; + case 246 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 217 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_27 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_28 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_28(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_27(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 246 /* ImportEqualsDeclaration */: + return node.name; + case 235 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 247 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 246 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 235 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_3 = addExport(statement, useEs6Exports); + if (exports_3) + return exports_3; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 247 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 246 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 235 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 250 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 183 /* ArrayBindingPattern */: + break; + case 182 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: + return true; + case 235 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 184 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 247 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 246 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 235 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 249 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71 /* Identifier */: + return keep(name) ? name : undefined; + case 183 /* ArrayBindingPattern */: + return name; + case 182 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return cb(statement); + case 217 /* VariableStatement */: + return ts.forEach(statement.declarationList.declarations, cb); + case 219 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 237 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 238 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 217 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 242 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 241 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 240 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 239 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 246 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 219 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 217 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 219 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; - node.flags = parent.flags & 6387712 /* ContextFlags */; + node.flags = parent.flags & 12679168 /* ContextFlags */; return node; } var NodeObject = /** @class */ (function () { @@ -101601,7 +110105,7 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; + this.transformFlags = undefined; // TODO: GH#18217 this.parent = undefined; this.kind = kind; } @@ -101647,104 +110151,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - /** Don't add trivia for "tokens" since this is in a comment. */ - var children_4 = []; - this.forEachChild(function (child) { children_4.push(child); }); - this._children = children_4; - return; - } - var children = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; - }; - // jsDocComments need to be the first children - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - // For syntactic classifications, all trivia are classcified together, including jsdoc comments. - // For that to work, the jsdoc comments should still be the leading trivia of the first child. - // Restoring the scanner position ensures that. - pos = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); - if (!this._children) - this.createChildren(sourceFile); - return this._children; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -101752,8 +110167,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 274 /* FirstJSDocNode */ || kid.kind > 292 /* LastJSDocNode */; }); - return child.kind < 145 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; }); + return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -101764,13 +110179,76 @@ var ts; if (!child) { return undefined; } - return child.kind < 145 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject @@ -101813,10 +110291,10 @@ var ts; return 0; }; TokenOrIdentifierObject.prototype.getChildAt = function () { - return undefined; + return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { - return ts.emptyArray; + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; }; TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; @@ -101854,28 +110332,9 @@ var ts; return this.declarations; }; SymbolObject.prototype.getDocumentationComment = function (checker) { - if (this.documentationComment === undefined) { - if (this.declarations) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); - if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { - if (checker) { - for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); - if (inheritedDocs.length > 0) { - if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); - } - this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); - break; - } - } - } - } - } - else { - this.documentationComment = []; - } + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); } return this.documentationComment; }; @@ -101944,9 +110403,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 65536 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) - ? this.checker.getBaseTypes(this) - : undefined; + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); @@ -101957,6 +110414,33 @@ var ts; TypeObject.prototype.getDefault = function () { return this.checker.getDefaultFromTypeParameter(this); }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 262144 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 524288 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 786432 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 192 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 64 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 128 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 65536 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; return TypeObject; }()); var SignatureObject = /** @class */ (function () { @@ -101976,22 +110460,7 @@ var ts; return this.checker.getReturnTypeOfSignature(this); }; SignatureObject.prototype.getDocumentationComment = function () { - if (this.documentationComment === undefined) { - if (this.declaration) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); - if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { - var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); - if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); - } - this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); - } - } - else { - this.documentationComment = []; - } - } - return this.documentationComment; + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { @@ -102009,6 +110478,21 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } /** * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses * implemented interfaces until a symbol is found with the same name and with documentation. @@ -102018,38 +110502,13 @@ var ts; * @returns A filled array of documentation comments if any were found, otherwise an empty array. */ function findInheritedJSDocComments(declaration, propertyName, typeChecker) { - var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { - if (foundDocs) { - return ts.emptyArray; - } + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { var superType = typeChecker.getTypeAtLocation(superTypeNode); - if (!superType) { - return ts.emptyArray; - } - var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); - if (!baseProperty) { - return ts.emptyArray; - } - var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); - foundDocs = inheritedDocs.length > 0; - return inheritedDocs; + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; }); } - /** - * Finds and returns the `TypeNode` for all super classes and implemented interfaces given a declaration. - * @param declaration The possibly-inherited declaration. - * @returns A filled array of `TypeNode`s containing all super classes and implemented interfaces if any exist, otherwise an empty array. - */ - function getAllSuperTypeNodes(declaration) { - var container = declaration.parent; - if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { - return ts.emptyArray; - } - var extended = ts.getClassExtendsHeritageClauseElement(container); - var types = extended ? [extended] : ts.emptyArray; - return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; - } var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -102089,7 +110548,7 @@ var ts; }; SourceFileObject.prototype.computeNamedDeclarations = function () { var result = ts.createMultiMap(); - ts.forEachChild(this, visit); + this.forEachChild(visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); @@ -102105,16 +110564,16 @@ var ts; return declarations; } function getDeclarationName(declaration) { - var name = ts.getNameOfDeclaration(declaration); - return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : - name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); } function visit(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -102134,31 +110593,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 165 /* TypeLiteral */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 166 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 148 /* Parameter */: + case 149 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: { + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -102169,31 +110628,31 @@ var ts; } } // falls through - case 271 /* EnumMember */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 276 /* EnumMember */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: addDeclaration(node); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addDeclaration(importClause); + addDeclaration(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 244 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -102202,7 +110661,7 @@ var ts; } } break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -102301,6 +110760,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -102327,20 +110789,29 @@ var ts; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; + return ts.isString(info) ? undefined : info; // TODO: GH#18217 }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); // TODO: GH#18217 }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); // TODO: GH#18217 }; return HostCache; }()); @@ -102443,7 +110914,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -102482,13 +110953,14 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; - function createLanguageService(host, documentRegistry) { + function createLanguageService(host, documentRegistry, syntaxOnly) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; var lastTypesRootVersion = 0; - var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -102500,7 +110972,9 @@ var ts; host.log(message); } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -102509,6 +110983,7 @@ var ts; return sourceFile; } function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); // perform fast check if host supports it if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); @@ -102522,7 +110997,7 @@ var ts; var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; if (lastTypesRootVersion !== typeRootsVersion) { log("TypeRoots version has changed; provide new program"); - program = undefined; + program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } // Get a fresh cache of the host information @@ -102530,7 +111005,7 @@ var ts; var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -102545,7 +111020,7 @@ var ts; getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, - useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, @@ -102554,7 +111029,7 @@ var ts; readFile: function (fileName) { // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); if (entry) { return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } @@ -102583,20 +111058,31 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } // Release any files we have acquired in the old program but are // not part of the new program. @@ -102608,11 +111094,11 @@ var ts; return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined); + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path); + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); if (!hostFileInformation) { return undefined; } @@ -102656,19 +111142,24 @@ var ts; return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } + // TODO: GH#18217 frequently asserted as defined function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } synchronizeHostData(); return program; } function cleanupSemanticCache() { - program = undefined; + program = undefined; // TODO: GH#18217 } function dispose() { if (program) { ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); - program = undefined; + program = undefined; // TODO: GH#18217 } host = undefined; } @@ -102696,29 +111187,33 @@ var ts; } function getSuggestionDiagnostics(fileName) { synchronizeHostData(); - return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { // Avoid giving quickInfo for the sourceFile as a whole. return undefined; @@ -102734,25 +111229,27 @@ var ts; return undefined; } // falls through - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: case 99 /* ThisKeyword */: - case 173 /* ThisType */: + case 176 /* ThisType */: case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position - var type = typeChecker.getTypeAtLocation(node); - return type && { + var type_4 = typeChecker.getTypeAtLocation(node); + return type_4 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), + documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined }; } return undefined; } - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -102794,58 +111291,62 @@ var ts; } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { - var canonicalFileName = getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { - ts.Debug.assert(getCanonicalFileName(ts.normalizeSlashes(entry.fileName)) === canonicalFileName); // Get occurrences only supports reporting occurrences for the file queried. - return { - fileName: entry.fileName, - textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, - isDefinition: false, - isInString: highlightSpan.isInString, - }; - }); }); + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function findRenameLocations(fileName, position, findInStrings, findInComments) { - return getReferences(fileName, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - } - function getReferencesAtPosition(fileName, position) { - return getReferences(fileName, position); - } - function getReferences(fileName, position, options) { synchronizeHostData(); - // Exclude default library when renaming as commonly user don't want to change that file. - var sourceFiles = []; - if (options && options.isForRename) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - sourceFiles.push(sourceFile); - } - } + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); } else { - sourceFiles = program.getSourceFiles().slice(); + var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); + return refs && refs.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return ({ fileName: fileName, textSpan: textSpan }); + }); } - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + } + function getReferences(node, position, options) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); } function findReferences(fileName, position) { synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -102855,40 +111356,38 @@ var ts; /** * This is a semantic operation. */ - function getSignatureHelpItems(fileName, position) { + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); } /// Syntactic features function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } - function getSourceFile(fileName) { - return getNonBoundSourceFile(fileName); - } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); + var node = ts.getTouchingPropertyName(sourceFile, startPos); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: case 9 /* StringLiteral */: case 86 /* FalseKeyword */: case 101 /* TrueKeyword */: case 95 /* NullKeyword */: case 97 /* SuperKeyword */: case 99 /* ThisKeyword */: - case 173 /* ThisType */: + case 176 /* ThisType */: case 71 /* Identifier */: break; // Cant create the text span default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -102900,7 +111399,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 237 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 242 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -102970,7 +111469,7 @@ var ts; braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTouchingToken(sourceFile, position); var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); // We want to order the braces when we return the result. @@ -103010,29 +111509,36 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -103045,7 +111551,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); // TODO: Debug.assertNever(action); will only work if there is more than one type. } } @@ -103081,10 +111587,26 @@ var ts; } return true; } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); - return range && ts.createTextSpanFromRange(range); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually @@ -103136,7 +111658,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { @@ -103211,10 +111734,9 @@ var ts; } function getRenameInfo(fileName, position) { synchronizeHostData(); - var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -103224,17 +111746,20 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, @@ -103276,19 +111801,21 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, - getSourceFile: getSourceFile, getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; - var _a; } ts.createLanguageService = createLanguageService; /* @internal */ @@ -103297,7 +111824,7 @@ var ts; if (!sourceFile.nameTable) { initializeNameTable(sourceFile); } - return sourceFile.nameTable; + return sourceFile.nameTable; // TODO: GH#18217 } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { @@ -103324,7 +111851,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 252 /* ExternalModuleReference */ || + node.parent.kind === 257 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -103336,13 +111863,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 146 /* ComputedPropertyName */) { + if (node.parent.kind === 147 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 182 /* ObjectLiteralExpression */ || node.parent.parent.kind === 261 /* JsxAttributes */) && + (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -103351,28 +111878,28 @@ var ts; /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - return getPropertySymbolsFromType(contextualType, node.name); + var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 + return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; /* @internal */ function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -103381,7 +111908,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 184 /* ElementAccessExpression */ && + node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -103399,9 +111926,6 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; ts.objectAllocator = getServicesObjectAllocator(); })(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// /* @internal */ var ts; (function (ts) { @@ -103415,7 +111939,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line @@ -103423,14 +111947,15 @@ var ts; // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // It's a blank line - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } // Cannot set breakpoint in ambient declarations - if (tokenAtLocation.flags & 2097152 /* Ambient */) { + if (tokenAtLocation.flags & 4194304 /* Ambient */) { return undefined; } // Get the span in the node based on its syntax @@ -103442,7 +111967,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -103457,119 +111982,120 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 230 /* VariableDeclaration */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return spanInVariableDeclaration(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return spanInParameterDeclaration(node); - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanInBlock(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return spanInBlock(node.block); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 216 /* DoStatement */: + case 221 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 229 /* DebuggerStatement */: + case 234 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 215 /* IfStatement */: + case 220 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return spanInForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 228 /* TryStatement */: + case 233 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 180 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 184 /* BindingElement */: // span on complete node return textSpan(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 149 /* Decorator */: - return spanInNodeArray(node.parent.decorators); - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 150 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: return undefined; // Tokens: case 25 /* SemicolonToken */: @@ -103599,7 +112125,7 @@ var ts; case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: return spanInNextNode(node); - case 144 /* OfKeyword */: + case 145 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -103612,13 +112138,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || - node.kind === 202 /* SpreadElement */ || - node.kind === 268 /* PropertyAssignment */ || - node.kind === 269 /* ShorthandPropertyAssignment */) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + node.kind === 206 /* SpreadElement */ || + node.kind === 273 /* PropertyAssignment */ || + node.kind === 274 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 198 /* BinaryExpression */) { + if (node.kind === 202 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -103639,23 +112165,23 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { - case 216 /* DoStatement */: + switch (parent.kind) { + case 221 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 149 /* Decorator */: + case 150 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return textSpan(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (node.parent.operatorToken.kind === 26 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -103664,21 +112190,21 @@ var ts; } } switch (node.parent.kind) { - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: { + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -103686,7 +112212,7 @@ var ts; } break; } - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -103716,9 +112242,10 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 219 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -103727,7 +112254,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) { + parent.parent.kind === 225 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -103768,7 +112295,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 233 /* ClassDeclaration */ && functionDeclaration.kind !== 154 /* Constructor */); + (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -103791,26 +112318,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 217 /* WhileStatement */: - case 215 /* IfStatement */: - case 219 /* ForInStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 224 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 231 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -103835,21 +112362,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 204 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 180 /* BindingElement */) { + if (bindingPattern.parent.kind === 184 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 179 /* ArrayBindingPattern */ && node.kind !== 178 /* ObjectBindingPattern */); - var elements = node.kind === 181 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 204 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); + var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -103857,18 +112384,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 198 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 202 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -103876,25 +112403,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 236 /* EnumDeclaration */: - case 233 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 267 /* CatchClause */: + case 272 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -103902,7 +112429,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 178 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -103918,7 +112445,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 179 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -103933,12 +112460,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 216 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 185 /* CallExpression */ || - node.parent.kind === 186 /* NewExpression */) { + if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 189 /* CallExpression */ || + node.parent.kind === 190 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 189 /* ParenthesizedExpression */) { + if (node.parent.kind === 193 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -103947,21 +112474,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 189 /* ParenthesizedExpression */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 193 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -103971,20 +112498,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 268 /* PropertyAssignment */ || - node.parent.kind === 148 /* Parameter */) { + node.parent.kind === 273 /* PropertyAssignment */ || + node.parent.kind === 149 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 188 /* TypeAssertionExpression */) { + if (node.parent.kind === 192 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 216 /* DoStatement */) { + if (node.parent.kind === 221 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -103992,7 +112519,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 220 /* ForOfStatement */) { + if (node.parent.kind === 225 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -104004,8 +112531,6 @@ var ts; BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); })(ts || (ts = {})); -/// -/// var ts; (function (ts) { /** @@ -104016,7 +112541,7 @@ var ts; */ function transform(source, transformers, compilerOptions) { var diagnostics = []; - compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 var nodes = ts.isArray(source) ? source : [source]; var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); @@ -104038,7 +112563,6 @@ var ts; // See the License for the specific language governing permissions and // limitations under the License. // -/// /* @internal */ var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. @@ -104066,16 +112590,16 @@ var ts; var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); if (encoded === null) { - return null; + return null; // TODO: GH#18217 } - var decoded = JSON.parse(encoded); + var decoded = JSON.parse(encoded); // TODO: GH#18217 return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? } }; return ScriptSnapshotShimAdapter; @@ -104090,10 +112614,10 @@ var ts; // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { - var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 }); }; } @@ -104102,8 +112626,8 @@ var ts; } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 }; } } @@ -104123,7 +112647,7 @@ var ts; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion - return undefined; + return undefined; // TODO: GH#18217 } return this.shimHost.getProjectVersion(); }; @@ -104156,7 +112680,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 } else { return 0 /* Unknown */; @@ -104192,7 +112716,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -104213,11 +112737,11 @@ var ts; this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } if ("realpath" in this.shimHost) { - this.realpath = function (path) { return _this.shimHost.realpath(path); }; + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -104289,7 +112813,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -104414,9 +112939,9 @@ var ts; return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP - LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); }; /// GOTO DEFINITION /** @@ -104510,16 +113035,16 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -104595,10 +113120,12 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { @@ -104660,7 +113187,8 @@ var ts; importedFiles: _this.convertFileReferences(result.importedFiles), ambientExternalModules: result.ambientExternalModules, isLibFile: result.isLibFile, - typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives) + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) }; }); }; @@ -104733,7 +113261,7 @@ var ts; this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); - var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); return new LanguageServiceShimObject(this, host, languageService); } catch (err) { @@ -104799,7 +113327,7 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; - +//# sourceMappingURL=typescriptServices.out.js.map // MONACOCHANGE // Defining the entire module name because r.js has an issue and cannot bundle this file // correctly with an anonymous define call diff --git a/src/lib/typescriptServices.d.ts b/src/lib/typescriptServices.d.ts index 47cc9cee..1e666671 100644 --- a/src/lib/typescriptServices.d.ts +++ b/src/lib/typescriptServices.d.ts @@ -13,6 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +declare namespace ts { + const versionMajorMinor = "3.0"; + /** The version of the TypeScript compiler release */ + const version: string; +} declare namespace ts { /** * Type of objects whose values are all of the same type. @@ -22,6 +27,9 @@ declare namespace ts { interface MapLike { [index: string]: T; } + interface SortedArray extends Array { + " __sortedArrayBrand": any; + } /** ES6 Map interface, only read methods included. */ interface ReadonlyMap { get(key: string): T | undefined; @@ -52,6 +60,8 @@ declare namespace ts { interface Push { push(...values: T[]): void; } +} +declare namespace ts { type Path = string & { __pathBrand: any; }; @@ -59,7 +69,8 @@ declare namespace ts { pos: number; end: number; } - type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.Unknown; + type JsxTokenSyntaxKind = SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.JsxText | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -203,164 +214,174 @@ declare namespace ts { TypeKeyword = 139, UndefinedKeyword = 140, UniqueKeyword = 141, - FromKeyword = 142, - GlobalKeyword = 143, - OfKeyword = 144, - QualifiedName = 145, - ComputedPropertyName = 146, - TypeParameter = 147, - Parameter = 148, - Decorator = 149, - PropertySignature = 150, - PropertyDeclaration = 151, - MethodSignature = 152, - MethodDeclaration = 153, - Constructor = 154, - GetAccessor = 155, - SetAccessor = 156, - CallSignature = 157, - ConstructSignature = 158, - IndexSignature = 159, - TypePredicate = 160, - TypeReference = 161, - FunctionType = 162, - ConstructorType = 163, - TypeQuery = 164, - TypeLiteral = 165, - ArrayType = 166, - TupleType = 167, - UnionType = 168, - IntersectionType = 169, - ConditionalType = 170, - InferType = 171, - ParenthesizedType = 172, - ThisType = 173, - TypeOperator = 174, - IndexedAccessType = 175, - MappedType = 176, - LiteralType = 177, - ObjectBindingPattern = 178, - ArrayBindingPattern = 179, - BindingElement = 180, - ArrayLiteralExpression = 181, - ObjectLiteralExpression = 182, - PropertyAccessExpression = 183, - ElementAccessExpression = 184, - CallExpression = 185, - NewExpression = 186, - TaggedTemplateExpression = 187, - TypeAssertionExpression = 188, - ParenthesizedExpression = 189, - FunctionExpression = 190, - ArrowFunction = 191, - DeleteExpression = 192, - TypeOfExpression = 193, - VoidExpression = 194, - AwaitExpression = 195, - PrefixUnaryExpression = 196, - PostfixUnaryExpression = 197, - BinaryExpression = 198, - ConditionalExpression = 199, - TemplateExpression = 200, - YieldExpression = 201, - SpreadElement = 202, - ClassExpression = 203, - OmittedExpression = 204, - ExpressionWithTypeArguments = 205, - AsExpression = 206, - NonNullExpression = 207, - MetaProperty = 208, - TemplateSpan = 209, - SemicolonClassElement = 210, - Block = 211, - VariableStatement = 212, - EmptyStatement = 213, - ExpressionStatement = 214, - IfStatement = 215, - DoStatement = 216, - WhileStatement = 217, - ForStatement = 218, - ForInStatement = 219, - ForOfStatement = 220, - ContinueStatement = 221, - BreakStatement = 222, - ReturnStatement = 223, - WithStatement = 224, - SwitchStatement = 225, - LabeledStatement = 226, - ThrowStatement = 227, - TryStatement = 228, - DebuggerStatement = 229, - VariableDeclaration = 230, - VariableDeclarationList = 231, - FunctionDeclaration = 232, - ClassDeclaration = 233, - InterfaceDeclaration = 234, - TypeAliasDeclaration = 235, - EnumDeclaration = 236, - ModuleDeclaration = 237, - ModuleBlock = 238, - CaseBlock = 239, - NamespaceExportDeclaration = 240, - ImportEqualsDeclaration = 241, - ImportDeclaration = 242, - ImportClause = 243, - NamespaceImport = 244, - NamedImports = 245, - ImportSpecifier = 246, - ExportAssignment = 247, - ExportDeclaration = 248, - NamedExports = 249, - ExportSpecifier = 250, - MissingDeclaration = 251, - ExternalModuleReference = 252, - JsxElement = 253, - JsxSelfClosingElement = 254, - JsxOpeningElement = 255, - JsxClosingElement = 256, - JsxFragment = 257, - JsxOpeningFragment = 258, - JsxClosingFragment = 259, - JsxAttribute = 260, - JsxAttributes = 261, - JsxSpreadAttribute = 262, - JsxExpression = 263, - CaseClause = 264, - DefaultClause = 265, - HeritageClause = 266, - CatchClause = 267, - PropertyAssignment = 268, - ShorthandPropertyAssignment = 269, - SpreadAssignment = 270, - EnumMember = 271, - SourceFile = 272, - Bundle = 273, - JSDocTypeExpression = 274, - JSDocAllType = 275, - JSDocUnknownType = 276, - JSDocNullableType = 277, - JSDocNonNullableType = 278, - JSDocOptionalType = 279, - JSDocFunctionType = 280, - JSDocVariadicType = 281, - JSDocComment = 282, - JSDocTypeLiteral = 283, - JSDocTag = 284, - JSDocAugmentsTag = 285, - JSDocClassTag = 286, - JSDocParameterTag = 287, - JSDocReturnTag = 288, - JSDocTypeTag = 289, - JSDocTemplateTag = 290, - JSDocTypedefTag = 291, - JSDocPropertyTag = 292, - SyntaxList = 293, - NotEmittedStatement = 294, - PartiallyEmittedExpression = 295, - CommaListExpression = 296, - MergeDeclarationMarker = 297, - EndOfDeclarationMarker = 298, - Count = 299, + UnknownKeyword = 142, + FromKeyword = 143, + GlobalKeyword = 144, + OfKeyword = 145, + QualifiedName = 146, + ComputedPropertyName = 147, + TypeParameter = 148, + Parameter = 149, + Decorator = 150, + PropertySignature = 151, + PropertyDeclaration = 152, + MethodSignature = 153, + MethodDeclaration = 154, + Constructor = 155, + GetAccessor = 156, + SetAccessor = 157, + CallSignature = 158, + ConstructSignature = 159, + IndexSignature = 160, + TypePredicate = 161, + TypeReference = 162, + FunctionType = 163, + ConstructorType = 164, + TypeQuery = 165, + TypeLiteral = 166, + ArrayType = 167, + TupleType = 168, + OptionalType = 169, + RestType = 170, + UnionType = 171, + IntersectionType = 172, + ConditionalType = 173, + InferType = 174, + ParenthesizedType = 175, + ThisType = 176, + TypeOperator = 177, + IndexedAccessType = 178, + MappedType = 179, + LiteralType = 180, + ImportType = 181, + ObjectBindingPattern = 182, + ArrayBindingPattern = 183, + BindingElement = 184, + ArrayLiteralExpression = 185, + ObjectLiteralExpression = 186, + PropertyAccessExpression = 187, + ElementAccessExpression = 188, + CallExpression = 189, + NewExpression = 190, + TaggedTemplateExpression = 191, + TypeAssertionExpression = 192, + ParenthesizedExpression = 193, + FunctionExpression = 194, + ArrowFunction = 195, + DeleteExpression = 196, + TypeOfExpression = 197, + VoidExpression = 198, + AwaitExpression = 199, + PrefixUnaryExpression = 200, + PostfixUnaryExpression = 201, + BinaryExpression = 202, + ConditionalExpression = 203, + TemplateExpression = 204, + YieldExpression = 205, + SpreadElement = 206, + ClassExpression = 207, + OmittedExpression = 208, + ExpressionWithTypeArguments = 209, + AsExpression = 210, + NonNullExpression = 211, + MetaProperty = 212, + SyntheticExpression = 213, + TemplateSpan = 214, + SemicolonClassElement = 215, + Block = 216, + VariableStatement = 217, + EmptyStatement = 218, + ExpressionStatement = 219, + IfStatement = 220, + DoStatement = 221, + WhileStatement = 222, + ForStatement = 223, + ForInStatement = 224, + ForOfStatement = 225, + ContinueStatement = 226, + BreakStatement = 227, + ReturnStatement = 228, + WithStatement = 229, + SwitchStatement = 230, + LabeledStatement = 231, + ThrowStatement = 232, + TryStatement = 233, + DebuggerStatement = 234, + VariableDeclaration = 235, + VariableDeclarationList = 236, + FunctionDeclaration = 237, + ClassDeclaration = 238, + InterfaceDeclaration = 239, + TypeAliasDeclaration = 240, + EnumDeclaration = 241, + ModuleDeclaration = 242, + ModuleBlock = 243, + CaseBlock = 244, + NamespaceExportDeclaration = 245, + ImportEqualsDeclaration = 246, + ImportDeclaration = 247, + ImportClause = 248, + NamespaceImport = 249, + NamedImports = 250, + ImportSpecifier = 251, + ExportAssignment = 252, + ExportDeclaration = 253, + NamedExports = 254, + ExportSpecifier = 255, + MissingDeclaration = 256, + ExternalModuleReference = 257, + JsxElement = 258, + JsxSelfClosingElement = 259, + JsxOpeningElement = 260, + JsxClosingElement = 261, + JsxFragment = 262, + JsxOpeningFragment = 263, + JsxClosingFragment = 264, + JsxAttribute = 265, + JsxAttributes = 266, + JsxSpreadAttribute = 267, + JsxExpression = 268, + CaseClause = 269, + DefaultClause = 270, + HeritageClause = 271, + CatchClause = 272, + PropertyAssignment = 273, + ShorthandPropertyAssignment = 274, + SpreadAssignment = 275, + EnumMember = 276, + SourceFile = 277, + Bundle = 278, + UnparsedSource = 279, + InputFiles = 280, + JSDocTypeExpression = 281, + JSDocAllType = 282, + JSDocUnknownType = 283, + JSDocNullableType = 284, + JSDocNonNullableType = 285, + JSDocOptionalType = 286, + JSDocFunctionType = 287, + JSDocVariadicType = 288, + JSDocComment = 289, + JSDocTypeLiteral = 290, + JSDocSignature = 291, + JSDocTag = 292, + JSDocAugmentsTag = 293, + JSDocClassTag = 294, + JSDocCallbackTag = 295, + JSDocParameterTag = 296, + JSDocReturnTag = 297, + JSDocThisTag = 298, + JSDocTypeTag = 299, + JSDocTemplateTag = 300, + JSDocTypedefTag = 301, + JSDocPropertyTag = 302, + SyntaxList = 303, + NotEmittedStatement = 304, + PartiallyEmittedExpression = 305, + CommaListExpression = 306, + MergeDeclarationMarker = 307, + EndOfDeclarationMarker = 308, + Count = 309, FirstAssignment = 58, LastAssignment = 70, FirstCompoundAssignment = 59, @@ -368,15 +389,15 @@ declare namespace ts { FirstReservedWord = 72, LastReservedWord = 107, FirstKeyword = 72, - LastKeyword = 144, + LastKeyword = 145, FirstFutureReservedWord = 108, LastFutureReservedWord = 116, - FirstTypeNode = 160, - LastTypeNode = 177, + FirstTypeNode = 161, + LastTypeNode = 181, FirstPunctuation = 17, LastPunctuation = 70, FirstToken = 0, - LastToken = 144, + LastToken = 145, FirstTriviaToken = 2, LastTriviaToken = 7, FirstLiteralToken = 8, @@ -385,11 +406,11 @@ declare namespace ts { LastTemplateToken = 16, FirstBinaryOperator = 27, LastBinaryOperator = 70, - FirstNode = 145, - FirstJSDocNode = 274, - LastJSDocNode = 292, - FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + FirstNode = 146, + FirstJSDocNode = 281, + LastJSDocNode = 302, + FirstJSDocTagNode = 292, + LastJSDocTagNode = 302 } enum NodeFlags { None = 0, @@ -412,12 +433,13 @@ declare namespace ts { JavaScriptFile = 65536, ThisNodeOrAnySubNodesHasError = 131072, HasAggregatedChildData = 262144, - JSDoc = 1048576, + JSDoc = 2097152, + JsonFile = 16777216, BlockScoped = 3, ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, - ContextFlags = 6387712, - TypeExcludesFlags = 20480, + ContextFlags = 12679168, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -438,6 +460,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -445,14 +468,14 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; decorators?: NodeArray; modifiers?: ModifiersArray; - parent?: Node; + parent: Node; } interface JSDocContainer { } @@ -517,12 +540,12 @@ declare namespace ts { } interface Decorator extends Node { kind: SyntaxKind.Decorator; - parent?: NamedDeclaration; + parent: NamedDeclaration; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; - parent?: DeclarationWithTypeParameters | InferTypeNode; + parent: DeclarationWithTypeParameters | InferTypeNode; name: Identifier; constraint?: TypeNode; default?: TypeNode; @@ -533,7 +556,7 @@ declare namespace ts { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; - type: TypeNode | undefined; + type?: TypeNode; } type SignatureDeclaration = CallSignatureDeclaration | ConstructSignatureDeclaration | MethodSignature | IndexSignatureDeclaration | FunctionTypeNode | ConstructorTypeNode | JSDocFunctionType | FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | AccessorDeclaration | FunctionExpression | ArrowFunction; interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement { @@ -545,7 +568,7 @@ declare namespace ts { type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; - parent?: VariableDeclarationList | CatchClause; + parent: VariableDeclarationList | CatchClause; name: BindingName; exclamationToken?: ExclamationToken; type?: TypeNode; @@ -553,12 +576,12 @@ declare namespace ts { } interface VariableDeclarationList extends Node { kind: SyntaxKind.VariableDeclarationList; - parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.Parameter; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; name: BindingName; questionToken?: QuestionToken; @@ -567,7 +590,7 @@ declare namespace ts { } interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; - parent?: BindingPattern; + parent: BindingPattern; propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: BindingName; @@ -582,6 +605,7 @@ declare namespace ts { } interface PropertyDeclaration extends ClassElement, JSDocContainer { kind: SyntaxKind.PropertyDeclaration; + parent: ClassLikeDeclaration; name: PropertyName; questionToken?: QuestionToken; exclamationToken?: ExclamationToken; @@ -619,12 +643,12 @@ declare namespace ts { } interface ObjectBindingPattern extends Node { kind: SyntaxKind.ObjectBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } interface ArrayBindingPattern extends Node { kind: SyntaxKind.ArrayBindingPattern; - parent?: VariableDeclaration | ParameterDeclaration | BindingElement; + parent: VariableDeclaration | ParameterDeclaration | BindingElement; elements: NodeArray; } type BindingPattern = ObjectBindingPattern | ArrayBindingPattern; @@ -643,7 +667,7 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { @@ -653,67 +677,79 @@ declare namespace ts { } interface MethodSignature extends SignatureDeclarationBase, TypeElement { kind: SyntaxKind.MethodSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent: ObjectTypeDeclaration; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.MethodDeclaration; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer { kind: SyntaxKind.Constructor; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; body?: FunctionBody; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ interface SemicolonClassElement extends ClassElement { kind: SyntaxKind.SemicolonClassElement; - parent?: ClassLikeDeclaration; + parent: ClassLikeDeclaration; } interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.GetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer { kind: SyntaxKind.SetAccessor; - parent?: ClassLikeDeclaration | ObjectLiteralExpression; + parent: ClassLikeDeclaration | ObjectLiteralExpression; name: PropertyName; body?: FunctionBody; } type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement { kind: SyntaxKind.IndexSignature; - parent?: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + parent: ObjectTypeDeclaration; } interface TypeNode extends Node { _typeNodeBrand: any; } interface KeywordTypeNode extends TypeNode { - kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + kind: SyntaxKind.AnyKeyword | SyntaxKind.UnknownKeyword | SyntaxKind.NumberKeyword | SyntaxKind.ObjectKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.ThisKeyword | SyntaxKind.VoidKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.NullKeyword | SyntaxKind.NeverKeyword; + } + interface ImportTypeNode extends NodeWithTypeArguments { + kind: SyntaxKind.ImportType; + isTypeOf?: boolean; + argument: TypeNode; + qualifier?: EntityName; } interface ThisTypeNode extends TypeNode { kind: SyntaxKind.ThisType; } type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; - interface FunctionTypeNode extends TypeNode, SignatureDeclarationBase { + interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; + type: TypeNode; + } + interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.FunctionType; } - interface ConstructorTypeNode extends TypeNode, SignatureDeclarationBase { + interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase { kind: SyntaxKind.ConstructorType; } + interface NodeWithTypeArguments extends TypeNode { + typeArguments?: NodeArray; + } type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; - interface TypeReferenceNode extends TypeNode { + interface TypeReferenceNode extends NodeWithTypeArguments { kind: SyntaxKind.TypeReference; typeName: EntityName; - typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { kind: SyntaxKind.TypePredicate; - parent?: SignatureDeclaration; + parent: SignatureDeclaration; parameterName: Identifier | ThisTypeNode; type: TypeNode; } @@ -733,6 +769,14 @@ declare namespace ts { kind: SyntaxKind.TupleType; elementTypes: NodeArray; } + interface OptionalTypeNode extends TypeNode { + kind: SyntaxKind.OptionalType; + type: TypeNode; + } + interface RestTypeNode extends TypeNode { + kind: SyntaxKind.RestType; + type: TypeNode; + } type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; interface UnionTypeNode extends TypeNode { kind: SyntaxKind.UnionType; @@ -857,6 +901,11 @@ declare namespace ts { asteriskToken?: AsteriskToken; expression?: Expression; } + interface SyntheticExpression extends Expression { + kind: SyntaxKind.SyntheticExpression; + isSpread: boolean; + type: Type; + } type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; @@ -942,15 +991,15 @@ declare namespace ts { } interface TemplateHead extends LiteralLikeNode { kind: SyntaxKind.TemplateHead; - parent?: TemplateExpression; + parent: TemplateExpression; } interface TemplateMiddle extends LiteralLikeNode { kind: SyntaxKind.TemplateMiddle; - parent?: TemplateSpan; + parent: TemplateSpan; } interface TemplateTail extends LiteralLikeNode { kind: SyntaxKind.TemplateTail; - parent?: TemplateSpan; + parent: TemplateSpan; } type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { @@ -960,7 +1009,7 @@ declare namespace ts { } interface TemplateSpan extends Node { kind: SyntaxKind.TemplateSpan; - parent?: TemplateExpression; + parent: TemplateExpression; expression: Expression; literal: TemplateMiddle | TemplateTail; } @@ -974,7 +1023,7 @@ declare namespace ts { } interface SpreadElement extends Expression { kind: SyntaxKind.SpreadElement; - parent?: ArrayLiteralExpression | CallExpression | NewExpression; + parent: ArrayLiteralExpression | CallExpression | NewExpression; expression: Expression; } /** @@ -1007,7 +1056,7 @@ declare namespace ts { interface ElementAccessExpression extends MemberExpression { kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; - argumentExpression?: Expression; + argumentExpression: Expression; } interface SuperElementAccessExpression extends ElementAccessExpression { expression: SuperExpression; @@ -1025,11 +1074,10 @@ declare namespace ts { interface ImportCall extends CallExpression { expression: ImportExpression; } - interface ExpressionWithTypeArguments extends TypeNode { + interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent?: HeritageClause; + parent: HeritageClause; expression: LeftHandSideExpression; - typeArguments?: NodeArray; } interface NewExpression extends PrimaryExpression, Declaration { kind: SyntaxKind.NewExpression; @@ -1040,6 +1088,7 @@ declare namespace ts { interface TaggedTemplateExpression extends MemberExpression { kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; + typeArguments?: NodeArray; template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement; @@ -1060,7 +1109,7 @@ declare namespace ts { } interface MetaProperty extends PrimaryExpression { kind: SyntaxKind.MetaProperty; - keywordToken: SyntaxKind.NewKeyword; + keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; name: Identifier; } interface JsxElement extends PrimaryExpression { @@ -1071,19 +1120,24 @@ declare namespace ts { } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; - type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; + type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess; + interface JsxTagNamePropertyAccess extends PropertyAccessExpression { + expression: JsxTagNameExpression; + } interface JsxAttributes extends ObjectLiteralExpressionBase { - parent?: JsxOpeningLikeElement; + parent: JsxOpeningLikeElement; } interface JsxOpeningElement extends Expression { kind: SyntaxKind.JsxOpeningElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxSelfClosingElement extends PrimaryExpression { kind: SyntaxKind.JsxSelfClosingElement; tagName: JsxTagNameExpression; + typeArguments?: NodeArray; attributes: JsxAttributes; } interface JsxFragment extends PrimaryExpression { @@ -1094,38 +1148,38 @@ declare namespace ts { } interface JsxOpeningFragment extends Expression { kind: SyntaxKind.JsxOpeningFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxClosingFragment extends Expression { kind: SyntaxKind.JsxClosingFragment; - parent?: JsxFragment; + parent: JsxFragment; } interface JsxAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends ObjectLiteralElement { kind: SyntaxKind.JsxSpreadAttribute; - parent?: JsxAttributes; + parent: JsxAttributes; expression: Expression; } interface JsxClosingElement extends Node { kind: SyntaxKind.JsxClosingElement; - parent?: JsxElement; + parent: JsxElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { kind: SyntaxKind.JsxExpression; - parent?: JsxElement | JsxAttributeLike; + parent: JsxElement | JsxAttributeLike; dotDotDotToken?: Token; expression?: Expression; } interface JsxText extends Node { kind: SyntaxKind.JsxText; containsOnlyWhiteSpaces: boolean; - parent?: JsxElement; + parent: JsxElement; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment; interface Statement extends Node { @@ -1135,7 +1189,7 @@ declare namespace ts { kind: SyntaxKind.NotEmittedStatement; } /** - * A list of comma-seperated expressions. This node is only created by transformations. + * A list of comma-separated expressions. This node is only created by transformations. */ interface CommaListExpression extends Expression { kind: SyntaxKind.CommaListExpression; @@ -1147,7 +1201,7 @@ declare namespace ts { interface DebuggerStatement extends Statement { kind: SyntaxKind.DebuggerStatement; } - interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + interface MissingDeclaration extends DeclarationStatement { kind: SyntaxKind.MissingDeclaration; name?: Identifier; } @@ -1226,18 +1280,18 @@ declare namespace ts { } interface CaseBlock extends Node { kind: SyntaxKind.CaseBlock; - parent?: SwitchStatement; + parent: SwitchStatement; clauses: NodeArray; } interface CaseClause extends Node { kind: SyntaxKind.CaseClause; - parent?: CaseBlock; + parent: CaseBlock; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { kind: SyntaxKind.DefaultClause; - parent?: CaseBlock; + parent: CaseBlock; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; @@ -1248,7 +1302,7 @@ declare namespace ts { } interface ThrowStatement extends Statement { kind: SyntaxKind.ThrowStatement; - expression: Expression; + expression?: Expression; } interface TryStatement extends Statement { kind: SyntaxKind.TryStatement; @@ -1258,11 +1312,12 @@ declare namespace ts { } interface CatchClause extends Node { kind: SyntaxKind.CatchClause; - parent?: TryStatement; + parent: TryStatement; variableDeclaration?: VariableDeclaration; block: Block; } - type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag; + type ObjectTypeDeclaration = ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode; + type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTemplateTag | JSDocTypedefTag | JSDocCallbackTag | JSDocSignature; interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; name?: Identifier; @@ -1297,7 +1352,7 @@ declare namespace ts { } interface HeritageClause extends Node { kind: SyntaxKind.HeritageClause; - parent?: InterfaceDeclaration | ClassLikeDeclaration; + parent: InterfaceDeclaration | ClassLikeDeclaration; token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; types: NodeArray; } @@ -1309,7 +1364,7 @@ declare namespace ts { } interface EnumMember extends NamedDeclaration, JSDocContainer { kind: SyntaxKind.EnumMember; - parent?: EnumDeclaration; + parent: EnumDeclaration; name: PropertyName; initializer?: Expression; } @@ -1322,7 +1377,7 @@ declare namespace ts { type ModuleBody = NamespaceBody | JSDocNamespaceBody; interface ModuleDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ModuleDeclaration; - parent?: ModuleBody | SourceFile; + parent: ModuleBody | SourceFile; name: ModuleName; body?: ModuleBody | JSDocNamespaceDeclaration; } @@ -1334,11 +1389,11 @@ declare namespace ts { type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; interface JSDocNamespaceDeclaration extends ModuleDeclaration { name: Identifier; - body: JSDocNamespaceBody; + body?: JSDocNamespaceBody; } interface ModuleBlock extends Node, Statement { kind: SyntaxKind.ModuleBlock; - parent?: ModuleDeclaration; + parent: ModuleDeclaration; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; @@ -1349,18 +1404,18 @@ declare namespace ts { */ interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { kind: SyntaxKind.ImportEqualsDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { kind: SyntaxKind.ExternalModuleReference; - parent?: ImportEqualsDeclaration; - expression?: Expression; + parent: ImportEqualsDeclaration; + expression: Expression; } interface ImportDeclaration extends Statement { kind: SyntaxKind.ImportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; importClause?: ImportClause; /** If this is not a StringLiteral it will be a grammar error. */ moduleSpecifier: Expression; @@ -1368,13 +1423,13 @@ declare namespace ts { type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; - parent?: ImportDeclaration; + parent: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; - parent?: ImportClause; + parent: ImportClause; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { @@ -1383,7 +1438,7 @@ declare namespace ts { } interface ExportDeclaration extends DeclarationStatement { kind: SyntaxKind.ExportDeclaration; - parent?: SourceFile | ModuleBlock; + parent: SourceFile | ModuleBlock; /** Will not be assigned in the case of `export * from "foo";` */ exportClause?: NamedExports; /** If this is not a StringLiteral it will be a grammar error. */ @@ -1391,24 +1446,24 @@ declare namespace ts { } interface NamedImports extends Node { kind: SyntaxKind.NamedImports; - parent?: ImportClause; + parent: ImportClause; elements: NodeArray; } interface NamedExports extends Node { kind: SyntaxKind.NamedExports; - parent?: ExportDeclaration; + parent: ExportDeclaration; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; - parent?: NamedImports; + parent: NamedImports; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; - parent?: NamedExports; + parent: NamedExports; propertyName?: Identifier; name: Identifier; } @@ -1419,7 +1474,7 @@ declare namespace ts { */ interface ExportAssignment extends DeclarationStatement { kind: SyntaxKind.ExportAssignment; - parent?: SourceFile; + parent: SourceFile; isExportEquals?: boolean; expression: Expression; } @@ -1474,15 +1529,15 @@ declare namespace ts { type JSDocTypeReferencingNode = JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDoc extends Node { kind: SyntaxKind.JSDocComment; - parent?: HasJSDoc; - tags: NodeArray | undefined; - comment: string | undefined; + parent: HasJSDoc; + tags?: NodeArray; + comment?: string; } interface JSDocTag extends Node { - parent: JSDoc; + parent: JSDoc | JSDocTypeLiteral; atToken: AtToken; tagName: Identifier; - comment: string | undefined; + comment?: string; } interface JSDocUnknownTag extends JSDocTag { kind: SyntaxKind.JSDocTag; @@ -1500,17 +1555,21 @@ declare namespace ts { interface JSDocClassTag extends JSDocTag { kind: SyntaxKind.JSDocClassTag; } + interface JSDocThisTag extends JSDocTag { + kind: SyntaxKind.JSDocThisTag; + typeExpression?: JSDocTypeExpression; + } interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { kind: SyntaxKind.JSDocReturnTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { kind: SyntaxKind.JSDocTypeTag; - typeExpression: JSDocTypeExpression; + typeExpression?: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { parent: JSDoc; @@ -1519,6 +1578,19 @@ declare namespace ts { name?: Identifier; typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } + interface JSDocCallbackTag extends JSDocTag, NamedDeclaration { + parent: JSDoc; + kind: SyntaxKind.JSDocCallbackTag; + fullName?: JSDocNamespaceDeclaration | Identifier; + name?: Identifier; + typeExpression: JSDocSignature; + } + interface JSDocSignature extends JSDocType, Declaration { + kind: SyntaxKind.JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; + type: JSDocReturnTag | undefined; + } interface JSDocPropertyLikeTag extends JSDocTag, Declaration { parent: JSDoc; name: EntityName; @@ -1554,7 +1626,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1575,7 +1647,7 @@ declare namespace ts { container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNodeBase { - antecedents: FlowNode[]; + antecedents: FlowNode[] | undefined; } interface FlowAssignment extends FlowNodeBase { node: Expression | VariableDeclaration | BindingElement; @@ -1602,7 +1674,7 @@ declare namespace ts { } interface AmdDependency { path: string; - name: string; + name?: string; } interface SourceFile extends Declaration { kind: SyntaxKind.SourceFile; @@ -1611,9 +1683,10 @@ declare namespace ts { fileName: string; text: string; amdDependencies: ReadonlyArray; - moduleName: string; + moduleName?: string; referencedFiles: ReadonlyArray; typeReferenceDirectives: ReadonlyArray; + libReferenceDirectives: ReadonlyArray; languageVariant: LanguageVariant; isDeclarationFile: boolean; /** @@ -1629,12 +1702,38 @@ declare namespace ts { } interface Bundle extends Node { kind: SyntaxKind.Bundle; + prepends: ReadonlyArray; sourceFiles: ReadonlyArray; } + interface InputFiles extends Node { + kind: SyntaxKind.InputFiles; + javascriptText: string; + javascriptMapPath?: string; + javascriptMapText?: string; + declarationText: string; + declarationMapPath?: string; + declarationMapText?: string; + } + interface UnparsedSource extends Node { + kind: SyntaxKind.UnparsedSource; + text: string; + sourceMapPath?: string; + sourceMapText?: string; + } interface JsonSourceFile extends SourceFile { - jsonObject?: ObjectLiteralExpression; + statements: NodeArray; + } + interface TsConfigSourceFile extends JsonSourceFile { extendedSourceFiles?: string[]; } + interface JsonMinusNumericLiteral extends PrefixUnaryExpression { + kind: SyntaxKind.PrefixUnaryExpression; + operator: SyntaxKind.MinusToken; + operand: NumericLiteral; + } + interface JsonObjectExpressionStatement extends ExpressionStatement { + expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral; + } interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; getSourceFile(fileName: string): SourceFile | undefined; @@ -1651,7 +1750,15 @@ declare namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; } - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray) => void; + /** + * Branded string for keeping track of when we've turned an ambiguous path + * specified like "./blah" to an absolute path to an actual + * tsconfig file, e.g. "/root/blah/tsconfig.json" + */ + type ResolvedConfigFileName = string & { + _isResolvedConfigFileName: never; + }; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -1681,20 +1788,30 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Gets a type checker that can be used to semantically analyze source files in the program. */ getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; + isSourceFileDefaultLibrary(file: SourceFile): boolean; + getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + } + interface ResolvedProjectReference { + commandLine: ParsedCommandLine; + sourceFile: SourceFile; } interface CustomTransformers { - /** Custom transformers to evaluate before built-in transformations. */ + /** Custom transformers to evaluate before built-in .js transformations. */ before?: TransformerFactory[]; - /** Custom transformers to evaluate after built-in transformations. */ + /** Custom transformers to evaluate after built-in .js transformations. */ after?: TransformerFactory[]; + /** Custom transformers to evaluate after built-in .d.ts transformations. */ + afterDeclarations?: TransformerFactory[]; } interface SourceMapSpan { /** Line number in the .js file. */ @@ -1716,23 +1833,22 @@ declare namespace ts { sourceMapFile: string; sourceMapSourceRoot: string; sourceMapSources: string[]; - sourceMapSourcesContent?: string[]; + sourceMapSourcesContent?: (string | null)[]; inputSourceFileNames: string[]; sourceMapNames?: string[]; sourceMapMappings: string; - sourceMapDecodedMappings: SourceMapSpan[]; } /** Return code used by getEmitOutput function to indicate status of the function */ enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; /** Contains declaration emit diagnostics */ diagnostics: ReadonlyArray; - emittedFiles: string[]; + emittedFiles?: string[]; } interface TypeChecker { getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; @@ -1740,7 +1856,7 @@ declare namespace ts { getPropertiesOfType(type: Type): Symbol[]; getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; - getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; + getSignaturesOfType(type: Type, kind: SignatureKind): ReadonlyArray; getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; getBaseTypeOfLiteralType(type: Type): Type; @@ -1749,11 +1865,11 @@ declare namespace ts { getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; + typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode | undefined; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1769,6 +1885,10 @@ declare namespace ts { getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; + /** + * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. + * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. + */ getShorthandAssignmentValueSymbol(location: Node): Symbol | undefined; getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol | undefined; /** @@ -1787,27 +1907,23 @@ declare namespace ts { typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - /** - * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead - * This will be removed in a future version. - */ - getSymbolDisplayBuilder(): SymbolDisplayBuilder; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): Symbol[]; getContextualType(node: Expression): Type | undefined; /** * returns unknownSignature in the case of an error. + * returns undefined if the node is not valid. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature; + getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; + isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; getExportsOfModule(moduleSymbol: Symbol): Symbol[]; @@ -1817,16 +1933,22 @@ declare namespace ts { getAmbientModules(): Symbol[]; tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; getApparentType(type: Type): Type; - getSuggestionForNonexistentProperty(node: Identifier, containingType: Type): string | undefined; - getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; getBaseConstraintOfType(type: Type): Type | undefined; getDefaultFromTypeParameter(type: Type): Type | undefined; + /** + * Depending on the operation performed, it may be appropriate to throw away the checker + * if the cancellation token is triggered. Typically, if it is used for error checking + * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. + */ + runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; } enum NodeBuilderFlags { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + GenerateNamesForShadowedTypeParams = 4, UseStructuralFallback = 8, + ForbidIndexedAccessSymbolReferences = 16, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, UseOnlyExternalAliasing = 128, @@ -1848,7 +1970,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1871,51 +1993,18 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, - } - /** - * @deprecated - */ - interface SymbolDisplayBuilder { - /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - } - /** - * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString - */ - interface SymbolWriter extends SymbolTracker { - writeKeyword(text: string): void; - writeOperator(text: string): void; - writePunctuation(text: string): void; - writeSpace(text: string): void; - writeStringLiteral(text: string): void; - writeParameter(text: string): void; - writeProperty(text: string): void; - writeSymbol(text: string, symbol: Symbol): void; - writeLine(): void; - increaseIndent(): void; - decreaseIndent(): void; - clear(): void; + UseAliasDefinedOutsideCurrentScope = 8 } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1986,17 +2075,15 @@ declare namespace ts { AliasExcludes = 2097152, ModuleMember = 2623475, ExportHasLocal = 944, - HasExports = 1952, - HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; escapedName: __String; - declarations?: Declaration[]; - valueDeclaration?: Declaration; + declarations: Declaration[]; + valueDeclaration: Declaration; members?: SymbolTable; exports?: SymbolTable; globalExports?: SymbolTable; @@ -2017,7 +2104,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2052,60 +2139,62 @@ declare namespace ts { type SymbolTable = UnderscoreEscapedMap; enum TypeFlags { Any = 1, - String = 2, - Number = 4, - Boolean = 8, - Enum = 16, - StringLiteral = 32, - NumberLiteral = 64, - BooleanLiteral = 128, - EnumLiteral = 256, - ESSymbol = 512, - UniqueESSymbol = 1024, - Void = 2048, - Undefined = 4096, - Null = 8192, - Never = 16384, - TypeParameter = 32768, - Object = 65536, - Union = 131072, - Intersection = 262144, - Index = 524288, - IndexedAccess = 1048576, - Conditional = 2097152, - Substitution = 4194304, - NonPrimitive = 134217728, - Literal = 224, - Unit = 13536, - StringOrNumberLiteral = 96, - PossiblyFalsy = 14574, - StringLike = 524322, - NumberLike = 84, - BooleanLike = 136, - EnumLike = 272, - ESSymbolLike = 1536, - UnionOrIntersection = 393216, - StructuredType = 458752, - TypeVariable = 1081344, - InstantiableNonPrimitive = 7372800, - InstantiablePrimitive = 524288, - Instantiable = 7897088, - StructuredOrInstantiable = 8355840, - Narrowable = 142575359, - NotUnionOrUnit = 134283777, + Unknown = 2, + String = 4, + Number = 8, + Boolean = 16, + Enum = 32, + StringLiteral = 64, + NumberLiteral = 128, + BooleanLiteral = 256, + EnumLiteral = 512, + ESSymbol = 1024, + UniqueESSymbol = 2048, + Void = 4096, + Undefined = 8192, + Null = 16384, + Never = 32768, + TypeParameter = 65536, + Object = 131072, + Union = 262144, + Intersection = 524288, + Index = 1048576, + IndexedAccess = 2097152, + Conditional = 4194304, + Substitution = 8388608, + NonPrimitive = 16777216, + Literal = 448, + Unit = 27072, + StringOrNumberLiteral = 192, + PossiblyFalsy = 29148, + StringLike = 68, + NumberLike = 168, + BooleanLike = 272, + EnumLike = 544, + ESSymbolLike = 3072, + VoidLike = 12288, + UnionOrIntersection = 786432, + StructuredType = 917504, + TypeVariable = 2162688, + InstantiableNonPrimitive = 14745600, + InstantiablePrimitive = 1048576, + Instantiable = 15794176, + StructuredOrInstantiable = 16711680, + Narrowable = 33492479, + NotUnionOrUnit = 16909315 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { flags: TypeFlags; - symbol?: Symbol; + symbol: Symbol; pattern?: DestructuringPattern; aliasSymbol?: Symbol; - aliasTypeArguments?: Type[]; + aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { value: string | number; - freshType?: LiteralType; - regularType?: LiteralType; + freshType: LiteralType; + regularType: LiteralType; } interface UniqueESSymbolType extends Type { symbol: Symbol; @@ -2133,25 +2222,25 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[]; - outerTypeParameters: TypeParameter[]; - localTypeParameters: TypeParameter[]; - thisType: TypeParameter; + typeParameters: TypeParameter[] | undefined; + outerTypeParameters: TypeParameter[] | undefined; + localTypeParameters: TypeParameter[] | undefined; + thisType: TypeParameter | undefined; } type BaseType = ObjectType | IntersectionType; interface InterfaceTypeWithDeclaredMembers extends InterfaceType { declaredProperties: Symbol[]; declaredCallSignatures: Signature[]; declaredConstructSignatures: Signature[]; - declaredStringIndexInfo: IndexInfo; - declaredNumberIndexInfo: IndexInfo; + declaredStringIndexInfo?: IndexInfo; + declaredNumberIndexInfo?: IndexInfo; } /** * Type references (ObjectFlags.Reference). When a class or interface has type parameters or @@ -2165,10 +2254,18 @@ declare namespace ts { */ interface TypeReference extends ObjectType { target: GenericType; - typeArguments?: Type[]; + typeArguments?: ReadonlyArray; } interface GenericType extends InterfaceType, TypeReference { } + interface TupleType extends GenericType { + minLength: number; + hasRestElement: boolean; + associatedNames?: __String[]; + } + interface TupleTypeReference extends TypeReference { + target: TupleType; + } interface UnionOrIntersectionType extends Type { types: Type[]; } @@ -2189,6 +2286,7 @@ declare namespace ts { objectType: Type; indexType: Type; constraint?: Type; + simplified?: Type; } type TypeVariable = TypeParameter | IndexedAccessType; interface IndexType extends InstantiableType { @@ -2201,11 +2299,11 @@ declare namespace ts { trueType: Type; falseType: Type; isDistributive: boolean; - inferTypeParameters: TypeParameter[]; + inferTypeParameters?: TypeParameter[]; outerTypeParameters?: TypeParameter[]; instantiations?: Map; - aliasSymbol: Symbol; - aliasTypeArguments: Type[]; + aliasSymbol?: Symbol; + aliasTypeArguments?: Type[]; } interface ConditionalType extends InstantiableType { root: ConditionalRoot; @@ -2220,21 +2318,21 @@ declare namespace ts { } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { - declaration: SignatureDeclaration; - typeParameters?: TypeParameter[]; - parameters: Symbol[]; + declaration?: SignatureDeclaration | JSDocSignature; + typeParameters?: ReadonlyArray; + parameters: ReadonlyArray; } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; isReadonly: boolean; - declaration?: SignatureDeclaration; + declaration?: IndexSignatureDeclaration; } enum InferencePriority { NakedTypeVariable = 1, @@ -2244,9 +2342,11 @@ declare namespace ts { LiteralKeyof = 16, NoConstraints = 32, AlwaysStrict = 64, - PriorityImpliesCombination = 28, + PriorityImpliesCombination = 28 } - interface JsFileExtensionInfo { + /** @deprecated Use FileExtensionInfo instead. */ + type JsFileExtensionInfo = FileExtensionInfo; + interface FileExtensionInfo { extension: string; isMixedContent: boolean; scriptKind?: ScriptKind; @@ -2256,6 +2356,7 @@ declare namespace ts { category: DiagnosticCategory; code: number; message: string; + reportsUnnecessary?: {}; } /** * A linked list of formatted diagnostic messages to be used as part of a multiline message. @@ -2269,29 +2370,49 @@ declare namespace ts { code: number; next?: DiagnosticMessageChain; } - interface Diagnostic { + interface Diagnostic extends DiagnosticRelatedInformation { + /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ + reportsUnnecessary?: {}; + source?: string; + relatedInformation?: DiagnosticRelatedInformation[]; + } + interface DiagnosticRelatedInformation { + category: DiagnosticCategory; + code: number; file: SourceFile | undefined; start: number | undefined; length: number | undefined; messageText: string | DiagnosticMessageChain; - category: DiagnosticCategory; - code: number; - source?: string; + } + interface DiagnosticWithLocation extends Diagnostic { + file: SourceFile; + start: number; + length: number; } enum DiagnosticCategory { Warning = 0, Error = 1, Suggestion = 2, - Message = 3, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; } - type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | null | undefined; + interface ProjectReference { + /** A normalized path on disk */ + path: string; + /** The path as the user originally wrote it */ + originalPath?: string; + /** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */ + prepend?: boolean; + /** True if it is intended that this reference form a circularity */ + circular?: boolean; + } + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -2302,6 +2423,7 @@ declare namespace ts { charset?: string; checkJs?: boolean; declaration?: boolean; + declarationMap?: boolean; emitDeclarationOnly?: boolean; declarationDir?: string; disableSizeLimit?: boolean; @@ -2315,6 +2437,7 @@ declare namespace ts { inlineSources?: boolean; isolatedModules?: boolean; jsx?: JsxEmit; + keyofStringsOnly?: boolean; lib?: string[]; locale?: string; mapRoot?: string; @@ -2345,6 +2468,7 @@ declare namespace ts { project?: string; reactNamespace?: string; jsxFactory?: string; + composite?: boolean; removeComments?: boolean; rootDir?: string; rootDirs?: string[]; @@ -2360,11 +2484,12 @@ declare namespace ts { suppressImplicitAnyIndexErrors?: boolean; target?: ScriptTarget; traceResolution?: boolean; + resolveJsonModule?: boolean; types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; esModuleInterop?: boolean; - [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; + [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } interface TypeAcquisition { enableAutoDiscovery?: boolean; @@ -2380,17 +2505,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2405,6 +2530,11 @@ declare namespace ts { TSX = 4, External = 5, JSON = 6, + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + Deferred = 7 } enum ScriptTarget { ES3 = 0, @@ -2414,17 +2544,19 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + JSON = 100, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { options: CompilerOptions; typeAcquisition?: TypeAcquisition; fileNames: string[]; + projectReferences?: ReadonlyArray; raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; @@ -2432,12 +2564,29 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; + projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } + interface CreateProgramOptions { + rootNames: ReadonlyArray; + options: CompilerOptions; + projectReferences?: ReadonlyArray; + host?: CompilerHost; + oldProgram?: Program; + configFileParsingDiagnostics?: ReadonlyArray; + } + interface UpToDateHost { + fileExists(fileName: string): boolean; + getModifiedTime(fileName: string): Date; + getUnchangedTime?(fileName: string): Date | undefined; + getLastStatus?(fileName: string): UpToDateStatus | undefined; + setLastStatus?(fileName: string, status: UpToDateStatus): void; + parseConfigFile?(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined; + } interface ModuleResolutionHost { fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; @@ -2502,7 +2651,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2513,7 +2662,7 @@ declare namespace ts { packageId?: PackageId; } interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective; + readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; readonly failedLookupLocations: ReadonlyArray; } interface CompilerHost extends ModuleResolutionHost { @@ -2528,13 +2677,17 @@ declare namespace ts { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; + readDirectory?(rootDir: string, extensions: ReadonlyArray, excludes: ReadonlyArray | undefined, includes: ReadonlyArray, depth?: number): string[]; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): (ResolvedModule | undefined)[]; /** * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; - getEnvironmentVariable?(name: string): string; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + getEnvironmentVariable?(name: string): string | undefined; createHash?(data: string): string; + getModifiedTime?(fileName: string): Date; + setModifiedTime?(fileName: string, date: Date): void; + deleteFile?(fileName: string): void; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2545,6 +2698,7 @@ declare namespace ts { skipTrivia?: (pos: number) => number; } enum EmitFlags { + None = 0, SingleLine = 1, AdviseOnEmitNode = 2, NoSubstitution = 4, @@ -2572,20 +2726,21 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; readonly scoped: boolean; - readonly text: string; + readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); readonly priority?: number; } + type EmitHelperUniqueNameCallback = (name: string) => string; enum EmitHint { SourceFile = 0, Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2597,7 +2752,7 @@ declare namespace ts { /** Resumes a suspended lexical environment, usually before visiting a function body. */ resumeLexicalEnvironment(): void; /** Ends a lexical environment, returning any declarations. */ - endLexicalEnvironment(): Statement[]; + endLexicalEnvironment(): Statement[] | undefined; /** Hoists a function declaration to the containing scope. */ hoistFunctionDeclaration(node: FunctionDeclaration): void; /** Hoists a variable declaration to the containing scope. */ @@ -2641,7 +2796,7 @@ declare namespace ts { /** Gets the transformed source files. */ transformed: T[]; /** Gets diagnostics for the transformation. */ - diagnostics?: Diagnostic[]; + diagnostics?: DiagnosticWithLocation[]; /** * Gets a substitute for a node, if one is available; otherwise, returns the original node. * @@ -2728,7 +2883,7 @@ declare namespace ts { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + onEmitNode?(hint: EmitHint, node: Node | undefined, emitCallback: (hint: EmitHint, node: Node | undefined) => void): void; /** * A hook used by the Printer to perform just-in-time substitution of a node. This is * primarily used by node transformations that need to substitute one node for another, @@ -2751,13 +2906,11 @@ declare namespace ts { removeComments?: boolean; newLine?: NewLineKind; omitTrailingSemicolon?: boolean; + noEmitHelpers?: boolean; } - /** @deprecated See comment on SymbolWriter */ - interface SymbolTracker { - trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError?(): void; - reportPrivateInBaseOfClassExpression?(propertyName: string): void; - reportInaccessibleUniqueSymbolError?(): void; + interface GetEffectiveTypeRootsHost { + directoryExists?(directoryName: string): boolean; + getCurrentDirectory?(): string; } interface TextSpan { start: number; @@ -2767,9 +2920,6 @@ declare namespace ts { span: TextSpan; newLength: number; } - interface SortedArray extends Array { - " __sortedArrayBrand": any; - } interface SyntaxList extends Node { _children: Node[]; } @@ -2803,9 +2953,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2821,12 +2971,12 @@ declare namespace ts { VariableDeclarationList = 272, SingleLineFunctionBodyStatements = 384, MultiLineFunctionBodyStatements = 1, - ClassHeritageClauses = 256, + ClassHeritageClauses = 0, ClassMembers = 65, InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2836,25 +2986,16 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } -declare namespace ts { - const versionMajorMinor = "2.8"; - /** The version of the TypeScript compiler release */ - const version: string; -} -declare namespace ts { - function isExternalModuleNameRelative(moduleName: string): boolean; - function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): Diagnostic[]; -} declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -2863,6 +3004,7 @@ declare namespace ts { newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; + writeOutputIsTTY?(): boolean; readFile(path: string, encoding?: string): string | undefined; getFileSize?(path: string): number; writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; @@ -2881,22 +3023,27 @@ declare namespace ts { getDirectories(path: string): string[]; readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; + setModifiedTime?(path: string, time: Date): void; + deleteFile?(path: string): void; /** - * This should be cryptographically secure. * A good implementation is node.js' `crypto.createHash`. (https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm) */ createHash?(data: string): string; + /** This must be cryptographically secure. Only implement this method using `crypto.createHash("sha256")`. */ + createSHA256Hash?(data: string): string; getMemoryUsage?(): number; exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; clearScreen?(): void; + base64decode?(input: string): string; + base64encode?(input: string): string; } interface FileWatcher { close(): void; } - function getNodeMajorVersion(): number; + function getNodeMajorVersion(): number | undefined; let sys: System; } declare namespace ts { @@ -2918,13 +3065,13 @@ declare namespace ts { reScanTemplateToken(): SyntaxKind; scanJsxIdentifier(): SyntaxKind; scanJsxAttributeValue(): SyntaxKind; - reScanJsxToken(): SyntaxKind; - scanJsxToken(): SyntaxKind; + reScanJsxToken(): JsxTokenSyntaxKind; + scanJsxToken(): JsxTokenSyntaxKind; scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; - setText(text: string, start?: number, length?: number): void; - setOnError(onError: ErrorCallback): void; + setText(text: string | undefined, start?: number, length?: number): void; + setOnError(onError: ErrorCallback | undefined): void; setScriptTarget(scriptTarget: ScriptTarget): void; setLanguageVariant(variant: LanguageVariant): void; setTextPos(textPos: number): void; @@ -2933,7 +3080,7 @@ declare namespace ts { tryScan(callback: () => T): T; } function tokenToString(t: SyntaxKind): string | undefined; - function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; + function getPositionOfLineAndCharacter(sourceFile: SourceFileLike, line: number, character: number): number; function getLineAndCharacterOfPosition(sourceFile: SourceFileLike, position: number): LineAndCharacter; function isWhiteSpaceLike(ch: number): boolean; /** Does not include line breaks. For that, see isWhiteSpaceLike. */ @@ -2944,15 +3091,20 @@ declare namespace ts { function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; - function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; - function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; + function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; + function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U | undefined; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined; /** Optionally, get the shebang */ function getShebang(text: string): string | undefined; - function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; - function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; - function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; + function isIdentifierStart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function isIdentifierPart(ch: number, languageVersion: ScriptTarget | undefined): boolean; + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, textInitial?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; +} +/** Non-internal stuff goes here */ +declare namespace ts { + function isExternalModuleNameRelative(moduleName: string): boolean; + function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[]; } declare namespace ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -2961,12 +3113,12 @@ declare namespace ts { function textSpanContainsPosition(span: TextSpan, position: number): boolean; function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; - function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; - function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined; function createTextSpan(start: number, length: number): TextSpan; function createTextSpanFromBounds(start: number, end: number): TextSpan; function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; @@ -2982,11 +3134,16 @@ declare namespace ts { * Vn. */ function collapseTextChangeRangesAcrossMultipleVersions(changes: ReadonlyArray): TextChangeRange; - function getTypeParameterOwner(d: Declaration): Declaration; - function isParameterPropertyDeclaration(node: Node): boolean; + function getTypeParameterOwner(d: Declaration): Declaration | undefined; + type ParameterPropertyDeclaration = ParameterDeclaration & { + parent: ConstructorDeclaration; + name: Identifier; + }; + function isParameterPropertyDeclaration(node: Node): node is ParameterPropertyDeclaration; function isEmptyBindingPattern(node: BindingName): node is BindingPattern; function isEmptyBindingElement(node: BindingElement): boolean; - function getCombinedModifierFlags(node: Node): ModifierFlags; + function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration; + function getCombinedModifierFlags(node: Declaration): ModifierFlags; function getCombinedNodeFlags(node: Node): NodeFlags; /** * Checks to see if the locale is in the appropriate format, @@ -3000,6 +3157,8 @@ declare namespace ts { }, errors?: Push): void; function getOriginalNode(node: Node): Node; function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; + function getOriginalNode(node: Node | undefined): Node | undefined; + function getOriginalNode(node: Node | undefined, nodeTest: (node: Node | undefined) => node is T): T | undefined; /** * Gets a value indicating whether a node originated in the parse tree. * @@ -3020,7 +3179,7 @@ declare namespace ts { * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. * @returns The original parse tree node if found; otherwise, undefined. */ - function getParseTreeNode(node: Node, nodeTest?: (node: Node) => node is T): T; + function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined; /** * Remove extra underscore from escaped identifier text content. * @@ -3030,13 +3189,6 @@ declare namespace ts { function unescapeLeadingUnderscores(identifier: __String): string; function idText(identifier: Identifier): string; function symbolName(symbol: Symbol): string; - /** - * Remove extra underscore from escaped identifier text content. - * @deprecated Use `id.text` for the unescaped text. - * @param identifier The escaped identifier text. - * @returns The unescaped identifier text. - */ - function unescapeIdentifier(id: string): string; function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | undefined; function getNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined; /** @@ -3052,7 +3204,7 @@ declare namespace ts { * Does not return tags for binding patterns, because JSDoc matches * parameters by name and binding patterns do not have a name. */ - function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray | undefined; + function getJSDocParameterTags(param: ParameterDeclaration): ReadonlyArray; /** * Return true if the node has JSDoc parameter tags. * @@ -3064,6 +3216,8 @@ declare namespace ts { function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node: Node): JSDocClassTag | undefined; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node: Node): JSDocThisTag | undefined; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node: Node): JSDocReturnTag | undefined; /** Gets the JSDoc template tag for the node if present */ @@ -3083,16 +3237,21 @@ declare namespace ts { */ function getJSDocType(node: Node): TypeNode | undefined; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node: Node): TypeNode | undefined; /** Get all JSDoc tags related to a node, including those on parent nodes. */ - function getJSDocTags(node: Node): ReadonlyArray | undefined; + function getJSDocTags(node: Node): ReadonlyArray; /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ - function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray | undefined; + function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): ReadonlyArray; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray; } declare namespace ts { function isNumericLiteral(node: Node): node is NumericLiteral; @@ -3137,6 +3296,7 @@ declare namespace ts { function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode; function isMappedTypeNode(node: Node): node is MappedTypeNode; function isLiteralTypeNode(node: Node): node is LiteralTypeNode; + function isImportTypeNode(node: Node): node is ImportTypeNode; function isObjectBindingPattern(node: Node): node is ObjectBindingPattern; function isArrayBindingPattern(node: Node): node is ArrayBindingPattern; function isBindingElement(node: Node): node is BindingElement; @@ -3236,6 +3396,7 @@ declare namespace ts { function isEnumMember(node: Node): node is EnumMember; function isSourceFile(node: Node): node is SourceFile; function isBundle(node: Node): node is Bundle; + function isUnparsedSource(node: Node): node is UnparsedSource; function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression; function isJSDocAllType(node: JSDocAllType): node is JSDocAllType; function isJSDocUnknownType(node: Node): node is JSDocUnknownType; @@ -3246,6 +3407,8 @@ declare namespace ts { function isJSDocVariadicType(node: Node): node is JSDocVariadicType; function isJSDoc(node: Node): node is JSDoc; function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag; + function isJSDocClassTag(node: Node): node is JSDocClassTag; + function isJSDocThisTag(node: Node): node is JSDocThisTag; function isJSDocParameterTag(node: Node): node is JSDocParameterTag; function isJSDocReturnTag(node: Node): node is JSDocReturnTag; function isJSDocTypeTag(node: Node): node is JSDocTypeTag; @@ -3254,6 +3417,8 @@ declare namespace ts { function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag; function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag; function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral; + function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag; + function isJSDocSignature(node: Node): node is JSDocSignature; } declare namespace ts { /** @@ -3263,8 +3428,10 @@ declare namespace ts { */ function isToken(n: Node): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; + type TemplateLiteralToken = NoSubstitutionTemplateLiteral | TemplateHead | TemplateMiddle | TemplateTail; + function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; - function isStringTextContainingNode(node: Node): boolean; + function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; function isModifier(node: Node): node is Modifier; function isEntityName(node: Node): node is EntityName; function isPropertyName(node: Node): node is PropertyName; @@ -3274,6 +3441,7 @@ declare namespace ts { function isClassLike(node: Node): node is ClassLikeDeclaration; function isAccessor(node: Node): node is AccessorDeclaration; function isTypeElement(node: Node): node is TypeElement; + function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement; function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike; /** * Node test that determines whether a node is a valid type node. @@ -3315,7 +3483,7 @@ declare namespace ts { */ function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined; function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; - function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName; + function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined; /** * Parse json text into SyntaxTree and return node and parse errors if any * @param fileName @@ -3326,10 +3494,79 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - interface GetEffectiveTypeRootsHost { - directoryExists?(directoryName: string): boolean; - getCurrentDirectory?(): string; + function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; } + /** + * Interface extending ParseConfigHost to support ParseConfigFile that reads config file and reports errors + */ + interface ParseConfigFileHost extends ParseConfigHost, ConfigFileDiagnosticsReporter { + getCurrentDirectory(): string; + } + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName: string, optionsToExtend: CompilerOptions, host: ParseConfigFileHost): ParsedCommandLine | undefined; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { + config?: any; + error?: Diagnostic; + }; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName: string, jsonText: string): { + config?: any; + error?: Diagnostic; + }; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile; + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; + function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: CompilerOptions; + errors: Diagnostic[]; + }; + function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { + options: TypeAcquisition; + errors: Diagnostic[]; + }; +} +declare namespace ts { function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined; /** * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. @@ -3361,10 +3598,11 @@ declare namespace ts { getOrCreateCacheForModuleName(nonRelativeModuleName: string): PerModuleNameCache; } interface PerModuleNameCache { - get(directory: string): ResolvedModuleWithFailedLookupLocations; + get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined; set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void; } function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string): ModuleResolutionCache; + function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined; function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations; function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations; @@ -3377,6 +3615,8 @@ declare namespace ts { function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; + function createStringLiteral(text: string): StringLiteral; + function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; function createIdentifier(text: string): Identifier; function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ @@ -3385,14 +3625,20 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ - function getGeneratedNameForNode(node: Node): Identifier; + function getGeneratedNameForNode(node: Node | undefined): Identifier; function createToken(token: TKind): Token; function createSuper(): SuperExpression; function createThis(): ThisExpression & Token; function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3417,9 +3663,9 @@ declare namespace ts { function updateGetAccessor(node: GetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; function createSetAccessor(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; function updateSetAccessor(node: SetAccessorDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: PropertyName, parameters: ReadonlyArray, body: Block | undefined): SetAccessorDeclaration; - function createCallSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; + function createCallSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): CallSignatureDeclaration; function updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - function createConstructSignature(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; + function createConstructSignature(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructSignatureDeclaration; function updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; function createIndexSignature(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; function updateIndexSignature(node: IndexSignatureDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode): IndexSignatureDeclaration; @@ -3428,27 +3674,33 @@ declare namespace ts { function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode): TypePredicateNode; function createTypeReferenceNode(typeName: string | EntityName, typeArguments: ReadonlyArray | undefined): TypeReferenceNode; function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - function createFunctionTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): FunctionTypeNode; + function createFunctionTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): FunctionTypeNode; function updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): FunctionTypeNode; - function createConstructorTypeNode(typeParameters: TypeParameterDeclaration[] | undefined, parameters: ParameterDeclaration[], type: TypeNode | undefined): ConstructorTypeNode; + function createConstructorTypeNode(typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined): ConstructorTypeNode; function updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructorTypeNode; function createTypeQueryNode(exprName: EntityName): TypeQueryNode; function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode; - function createTypeLiteralNode(members: ReadonlyArray): TypeLiteralNode; + function createTypeLiteralNode(members: ReadonlyArray | undefined): TypeLiteralNode; function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; function createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; function createTupleTypeNode(elementTypes: ReadonlyArray): TupleTypeNode; - function updateTypleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode; - function createUnionTypeNode(types: TypeNode[]): UnionTypeNode; + function updateTupleTypeNode(node: TupleTypeNode, elementTypes: ReadonlyArray): TupleTypeNode; + function createOptionalTypeNode(type: TypeNode): OptionalTypeNode; + function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; + function createRestTypeNode(type: TypeNode): RestTypeNode; + function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; + function createUnionTypeNode(types: ReadonlyArray): UnionTypeNode; function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; - function createIntersectionTypeNode(types: TypeNode[]): IntersectionTypeNode; + function createIntersectionTypeNode(types: ReadonlyArray): IntersectionTypeNode; function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: ReadonlyArray): UnionOrIntersectionTypeNode; function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; function createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; + function createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; + function updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier?: EntityName, typeArguments?: ReadonlyArray, isTypeOf?: boolean): ImportTypeNode; function createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; function createThisTypeNode(): ThisTypeNode; @@ -3471,24 +3723,26 @@ declare namespace ts { function updateArrayLiteral(node: ArrayLiteralExpression, elements: ReadonlyArray): ArrayLiteralExpression; function createObjectLiteral(properties?: ReadonlyArray, multiLine?: boolean): ObjectLiteralExpression; function updateObjectLiteral(node: ObjectLiteralExpression, properties: ReadonlyArray): ObjectLiteralExpression; - function createPropertyAccess(expression: Expression, name: string | Identifier): PropertyAccessExpression; + function createPropertyAccess(expression: Expression, name: string | Identifier | undefined): PropertyAccessExpression; function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier): PropertyAccessExpression; function createElementAccess(expression: Expression, index: number | Expression): ElementAccessExpression; function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; + function createCall(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): CallExpression; function updateCall(node: CallExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray): CallExpression; function createNew(expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: ReadonlyArray | undefined, argumentsArray: ReadonlyArray | undefined): NewExpression; function createTaggedTemplate(tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, typeArguments: ReadonlyArray | undefined, template: TemplateLiteral): TaggedTemplateExpression; function createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; function createParen(expression: Expression): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; + function createFunctionExpression(modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block): FunctionExpression; function createArrowFunction(modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; + /** @deprecated */ function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: ConciseBody): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: ReadonlyArray | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, equalsGreaterThanToken: Token, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): DeleteExpression; @@ -3506,7 +3760,7 @@ declare namespace ts { function updateBinary(node: BinaryExpression, left: Expression, right: Expression, operator?: BinaryOperator | BinaryOperatorToken): BinaryExpression; function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; + /** @deprecated */ function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, questionToken: Token, whenTrue: Expression, colonToken: Token, whenFalse: Expression): ConditionalExpression; function createTemplateExpression(head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: ReadonlyArray): TemplateExpression; @@ -3515,15 +3769,15 @@ declare namespace ts { function createTemplateTail(text: string): TemplateTail; function createNoSubstitutionTemplateLiteral(text: string): NoSubstitutionTemplateLiteral; function createYield(expression?: Expression): YieldExpression; - function createYield(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; + function createYield(asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function updateYield(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression): YieldExpression; function createSpread(expression: Expression): SpreadElement; function updateSpread(node: SpreadElement, expression: Expression): SpreadElement; - function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; - function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassExpression; + function createClassExpression(modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; + function updateClassExpression(node: ClassExpression, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassExpression; function createOmittedExpression(): OmittedExpression; - function createExpressionWithTypeArguments(typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray, expression: Expression): ExpressionWithTypeArguments; + function createExpressionWithTypeArguments(typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; + function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: ReadonlyArray | undefined, expression: Expression): ExpressionWithTypeArguments; function createAsExpression(expression: Expression, type: TypeNode): AsExpression; function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; function createNonNullExpression(expression: Expression): NonNullExpression; @@ -3538,8 +3792,12 @@ declare namespace ts { function createVariableStatement(modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList | ReadonlyArray): VariableStatement; function updateVariableStatement(node: VariableStatement, modifiers: ReadonlyArray | undefined, declarationList: VariableDeclarationList): VariableStatement; function createEmptyStatement(): EmptyStatement; - function createStatement(expression: Expression): ExpressionStatement; - function updateStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + function createExpressionStatement(expression: Expression): ExpressionStatement; + function updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + const createStatement: typeof createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + const updateStatement: typeof updateExpressionStatement; function createIf(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; function updateIf(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; function createDo(statement: Statement, expression: Expression): DoStatement; @@ -3550,8 +3808,8 @@ declare namespace ts { function updateFor(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createForOf(awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createForOf(awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function updateForOf(node: ForOfStatement, awaitModifier: AwaitKeywordToken | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; function createContinue(label?: string | Identifier): ContinueStatement; function updateContinue(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; function createBreak(label?: string | Identifier): BreakStatement; @@ -3575,8 +3833,8 @@ declare namespace ts { function updateVariableDeclarationList(node: VariableDeclarationList, declarations: ReadonlyArray): VariableDeclarationList; function createFunctionDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, parameters: ReadonlyArray, type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; - function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray, members: ReadonlyArray): ClassDeclaration; + function createClassDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; + function updateClassDeclaration(node: ClassDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier | undefined, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): ClassDeclaration; function createInterfaceDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, typeParameters: ReadonlyArray | undefined, heritageClauses: ReadonlyArray | undefined, members: ReadonlyArray): InterfaceDeclaration; function createTypeAliasDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, typeParameters: ReadonlyArray | undefined, type: TypeNode): TypeAliasDeclaration; @@ -3593,8 +3851,8 @@ declare namespace ts { function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; function createImportEqualsDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; function updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier?: Expression): ImportDeclaration; - function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression | undefined): ImportDeclaration; + function createImportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; + function updateImportDeclaration(node: ImportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration; function createImportClause(name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function updateImportClause(node: ImportClause, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; function createNamespaceImport(name: Identifier): NamespaceImport; @@ -3603,7 +3861,7 @@ declare namespace ts { function updateNamedImports(node: NamedImports, elements: ReadonlyArray): NamedImports; function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean, expression: Expression): ExportAssignment; + function createExportAssignment(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; function updateExportAssignment(node: ExportAssignment, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, expression: Expression): ExportAssignment; function createExportDeclaration(decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier?: Expression): ExportDeclaration; function updateExportDeclaration(node: ExportDeclaration, decorators: ReadonlyArray | undefined, modifiers: ReadonlyArray | undefined, exportClause: NamedExports | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration; @@ -3615,10 +3873,10 @@ declare namespace ts { function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; function createJsxElement(openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: ReadonlyArray, closingElement: JsxClosingElement): JsxElement; - function createJsxSelfClosingElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxSelfClosingElement; - function createJsxOpeningElement(tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; - function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, attributes: JsxAttributes): JsxOpeningElement; + function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxSelfClosingElement; + function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; + function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: ReadonlyArray | undefined, attributes: JsxAttributes): JsxOpeningElement; function createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; function createJsxFragment(openingFragment: JsxOpeningFragment, children: ReadonlyArray, closingFragment: JsxClosingFragment): JsxFragment; @@ -3647,7 +3905,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"], hasNoDefaultLib?: boolean, libReferences?: SourceFile["libReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -3671,12 +3929,16 @@ declare namespace ts { function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; function createCommaList(elements: ReadonlyArray): CommaListExpression; function updateCommaList(node: CommaListExpression, elements: ReadonlyArray): CommaListExpression; - function createBundle(sourceFiles: ReadonlyArray): Bundle; - function updateBundle(node: Bundle, sourceFiles: ReadonlyArray): Bundle; - function createImmediatelyInvokedFunctionExpression(statements: Statement[]): CallExpression; - function createImmediatelyInvokedFunctionExpression(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; - function createImmediatelyInvokedArrowFunction(statements: Statement[]): CallExpression; - function createImmediatelyInvokedArrowFunction(statements: Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createBundle(sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createUnparsedSourceFile(text: string): UnparsedSource; + function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; + function createInputFiles(javascript: string, declaration: string): InputFiles; + function createInputFiles(javascript: string, declaration: string, javascriptMapPath: string | undefined, javascriptMapText: string | undefined, declarationMapPath: string | undefined, declarationMapText: string | undefined): InputFiles; + function updateBundle(node: Bundle, sourceFiles: ReadonlyArray, prepends?: ReadonlyArray): Bundle; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedFunctionExpression(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray): CallExpression; + function createImmediatelyInvokedArrowFunction(statements: ReadonlyArray, param: ParameterDeclaration, paramValue: Expression): CallExpression; function createComma(left: Expression, right: Expression): Expression; function createLessThan(left: Expression, right: Expression): Expression; function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; @@ -3731,15 +3993,16 @@ declare namespace ts { */ function setCommentRange(node: T, range: TextRange): T; function getSyntheticLeadingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticLeadingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticLeadingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; function getSyntheticTrailingComments(node: Node): SynthesizedComment[] | undefined; - function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[]): T; + function setSyntheticTrailingComments(node: T, comments: SynthesizedComment[] | undefined): T; function addSyntheticTrailingComment(node: T, kind: SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia, text: string, hasTrailingNewLine?: boolean): T; + function moveSyntheticComments(node: T, original: Node): T; /** * Gets the constant value to emit for an expression. */ - function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): string | number | undefined; /** * Sets the constant value to emit for an expression. */ @@ -3775,7 +4038,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T; /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -3784,7 +4047,7 @@ declare namespace ts { * @param test A callback to execute to verify the Node is valid. * @param lift An optional callback to execute to lift a NodeArray into a valid Node. */ - function visitNode(node: T | undefined, visitor: Visitor, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; + function visitNode(node: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: NodeArray) => T): T | undefined; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3794,7 +4057,7 @@ declare namespace ts { * @param start An optional value indicating the starting offset at which to start visiting. * @param count An optional value indicating the maximum number of nodes to visit. */ - function visitNodes(nodes: NodeArray, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; + function visitNodes(nodes: NodeArray | undefined, visitor: Visitor, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray; /** * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place. * @@ -3814,7 +4077,7 @@ declare namespace ts { * Starts a new lexical environment and visits a parameter list, suspending the lexical * environment upon completion. */ - function visitParameterList(nodes: NodeArray, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; + function visitParameterList(nodes: NodeArray | undefined, visitor: Visitor, context: TransformationContext, nodesVisitor?: typeof visitNodes): NodeArray; /** * Resumes a suspended lexical environment and visits a function body, ending the lexical * environment and merging hoisted declarations upon completion. @@ -3863,7 +4126,19 @@ declare namespace ts { function formatDiagnostics(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string; function formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray, host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain | undefined, newLine: string): string; + function getConfigFileParsingDiagnostics(configFileParseResult: ParsedCommandLine): ReadonlyArray; + /** + * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' + * that represent a compilation unit. + * + * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and + * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. + * + * @param createProgramOptions - The options for creating a program. + * @returns A 'Program' object. + */ + function createProgram(createProgramOptions: CreateProgramOptions): Program; /** * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' * that represent a compilation unit. @@ -3875,9 +4150,18 @@ declare namespace ts { * @param options - The compiler options which should be used. * @param host - The host interacts with the underlying file system. * @param oldProgram - Reuses an old program structure. + * @param configFileParsingDiagnostics - error during config file parsing * @returns A 'Program' object. */ - function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; + function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { @@ -3938,6 +4222,10 @@ declare namespace ts { * Get the diagnostics that dont belong to any file */ getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics from config file parsing + */ + getConfigFileParsingDiagnostics(): ReadonlyArray; /** * Get the syntax diagnostics, for all source files if source file is not supplied */ @@ -3997,24 +4285,24 @@ declare namespace ts { /** * Create the builder to manage semantic diagnostics and cache them */ - function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ - function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; } declare namespace ts { - type DiagnosticReporter = (diagnostic: Diagnostic) => void; type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; - type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; interface WatchCompilerHost { /** * Used to create the program when need for program creation or recreation detected @@ -4051,11 +4339,11 @@ declare namespace ts { /** If provided would be used to write log about compilation */ trace?(s: string): void; /** If provided is used to get the environment variable */ - getEnvironmentVariable?(name: string): string; + getEnvironmentVariable?(name: string): string | undefined; /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; /** Used to watch changes in source files, missing files needed to update the program or config file */ watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ @@ -4074,19 +4362,6 @@ declare namespace ts { /** Compiler options */ options: CompilerOptions; } - /** - * Reports config file diagnostics - */ - interface ConfigFileDiagnosticsReporter { - /** - * Reports the diagnostics in reading/writing or parsing of the config file - */ - onConfigFileDiagnostic: DiagnosticReporter; - /** - * Reports unrecoverable error when parsing config file - */ - onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; - } /** * Host to create watch with config file */ @@ -4132,57 +4407,252 @@ declare namespace ts { function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; } declare namespace ts { - function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; + interface BuildHost { + verbose(diag: DiagnosticMessage, ...args: string[]): void; + error(diag: DiagnosticMessage, ...args: string[]): void; + errorDiagnostic(diag: Diagnostic): void; + message(diag: DiagnosticMessage, ...args: string[]): void; + } /** - * Read tsconfig.json file - * @param fileName The path to the config file + * A BuildContext tracks what's going on during the course of a build. + * + * Callers may invoke any number of build requests within the same context; + * until the context is reset, each project will only be built at most once. + * + * Example: In a standard setup where project B depends on project A, and both are out of date, + * a failed build of A will result in A remaining out of date. When we try to build + * B, we should immediately bail instead of recomputing A's up-to-date status again. + * + * This also matters for performing fast (i.e. fake) downstream builds of projects + * when their upstream .d.ts files haven't changed content (but have newer timestamps) */ - function readConfigFile(fileName: string, readFile: (path: string) => string | undefined): { - config?: any; - error?: Diagnostic; + interface BuildContext { + options: BuildOptions; + /** + * Map from output file name to its pre-build timestamp + */ + unchangedOutputs: FileMap; + /** + * Map from config file name to up-to-date status + */ + projectStatus: FileMap; + invalidatedProjects: FileMap; + queuedProjects: FileMap; + missingRoots: Map; + } + type Mapper = ReturnType; + interface DependencyGraph { + buildQueue: ResolvedConfigFileName[]; + dependencyMap: Mapper; + } + interface BuildOptions { + dry: boolean; + force: boolean; + verbose: boolean; + } + enum UpToDateStatusType { + Unbuildable = 0, + UpToDate = 1, + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateWithUpstreamTypes = 2, + OutputMissing = 3, + OutOfDateWithSelf = 4, + OutOfDateWithUpstream = 5, + UpstreamOutOfDate = 6, + UpstreamBlocked = 7, + /** + * Projects with no outputs (i.e. "solution" files) + */ + ContainerOnly = 8 + } + type UpToDateStatus = Status.Unbuildable | Status.UpToDate | Status.OutputMissing | Status.OutOfDateWithSelf | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked | Status.ContainerOnly; + namespace Status { + /** + * The project can't be built at all in its current state. For example, + * its config file cannot be parsed, or it has a syntax error or missing file + */ + interface Unbuildable { + type: UpToDateStatusType.Unbuildable; + reason: string; + } + /** + * This project doesn't have any outputs, so "is it up to date" is a meaningless question. + */ + interface ContainerOnly { + type: UpToDateStatusType.ContainerOnly; + } + /** + * The project is up to date with respect to its inputs. + * We track what the newest input file is. + */ + interface UpToDate { + type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes; + newestInputFileTime?: Date; + newestInputFileName?: string; + newestDeclarationFileContentChangedTime?: Date; + newestOutputFileTime?: Date; + newestOutputFileName?: string; + oldestOutputFileName?: string; + } + /** + * One or more of the outputs of the project does not exist. + */ + interface OutputMissing { + type: UpToDateStatusType.OutputMissing; + /** + * The name of the first output file that didn't exist + */ + missingOutputFileName: string; + } + /** + * One or more of the project's outputs is older than its newest input. + */ + interface OutOfDateWithSelf { + type: UpToDateStatusType.OutOfDateWithSelf; + outOfDateOutputFileName: string; + newerInputFileName: string; + } + /** + * This project depends on an out-of-date project, so shouldn't be built yet + */ + interface UpstreamOutOfDate { + type: UpToDateStatusType.UpstreamOutOfDate; + upstreamProjectName: string; + } + /** + * This project depends an upstream project with build errors + */ + interface UpstreamBlocked { + type: UpToDateStatusType.UpstreamBlocked; + upstreamProjectName: string; + } + /** + * One or more of the project's outputs is older than the newest output of + * an upstream project. + */ + interface OutOfDateWithUpstream { + type: UpToDateStatusType.OutOfDateWithUpstream; + outOfDateOutputFileName: string; + newerProjectName: string; + } + } + interface FileMap { + setValue(fileName: string, value: T): void; + getValue(fileName: string): T | never; + getValueOrUndefined(fileName: string): T | undefined; + hasKey(fileName: string): boolean; + removeKey(fileName: string): void; + getKeys(): string[]; + } + function createDependencyMapper(): { + addReference: (childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName) => void; + getReferencesTo: (parentConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; + getReferencesOf: (childConfigFileName: ResolvedConfigFileName) => ResolvedConfigFileName[]; + getKeys: () => ReadonlyArray; + }; + function createBuildContext(options: BuildOptions): BuildContext; + function performBuild(args: string[], compilerHost: CompilerHost, buildHost: BuildHost, system?: System): number | undefined; + /** + * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but + * can dynamically add/remove other projects based on changes on the rootNames' references + */ + function createSolutionBuilder(compilerHost: CompilerHost, buildHost: BuildHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions, system?: System): { + buildAllProjects: () => ExitStatus; + getUpToDateStatus: (project: ParsedCommandLine | undefined) => UpToDateStatus; + getUpToDateStatusOfFile: (configFileName: ResolvedConfigFileName) => UpToDateStatus; + cleanAllProjects: () => ExitStatus.Success | ExitStatus.DiagnosticsPresent_OutputsSkipped; + resetBuildContext: (opts?: BuildOptions) => void; + getBuildGraph: (configFileNames: ReadonlyArray) => DependencyGraph | undefined; + invalidateProject: (configFileName: string) => void; + buildInvalidatedProjects: () => void; + buildDependentInvalidatedProjects: () => void; + resolveProjectName: (name: string) => ResolvedConfigFileName | undefined; + startWatching: () => void; }; /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file + * Gets the UpToDateStatus for a project */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { - config?: any; - error?: Diagnostic; - }; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile; - /** - * Convert the json syntax tree into the json value - */ - function convertToObject(sourceFile: JsonSourceFile, errors: Push): any; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; - /** - * Parse the contents of a config file (tsconfig.json). - * @param jsonNode The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray): ParsedCommandLine; - function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; - errors: Diagnostic[]; - }; - function convertTypeAcquisitionFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: TypeAcquisition; - errors: Diagnostic[]; - }; + function getUpToDateStatus(host: UpToDateHost, project: ParsedCommandLine | undefined): UpToDateStatus; + function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray; + function formatUpToDateStatus(configFileName: string, status: UpToDateStatus, relName: (fileName: string) => string, formatMessage: (message: DiagnosticMessage, ...args: string[]) => T): T | undefined; +} +declare namespace ts.server { + type ActionSet = "action::set"; + type ActionInvalidate = "action::invalidate"; + type ActionPackageInstalled = "action::packageInstalled"; + type EventTypesRegistry = "event::typesRegistry"; + type EventBeginInstallTypes = "event::beginInstallTypes"; + type EventEndInstallTypes = "event::endInstallTypes"; + type EventInitializationFailed = "event::initializationFailed"; + interface SortedReadonlyArray extends ReadonlyArray { + " __sortedArrayBrand": any; + } + interface TypingInstallerResponse { + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed; + } + interface TypingInstallerRequestWithProjectName { + readonly projectName: string; + } + interface DiscoverTypings extends TypingInstallerRequestWithProjectName { + readonly fileNames: string[]; + readonly projectRootPath: Path; + readonly compilerOptions: CompilerOptions; + readonly typeAcquisition: TypeAcquisition; + readonly unresolvedImports: SortedReadonlyArray; + readonly cachePath?: string; + readonly kind: "discover"; + } + interface CloseProject extends TypingInstallerRequestWithProjectName { + readonly kind: "closeProject"; + } + interface TypesRegistryRequest { + readonly kind: "typesRegistry"; + } + interface InstallPackageRequest extends TypingInstallerRequestWithProjectName { + readonly kind: "installPackage"; + readonly fileName: Path; + readonly packageName: string; + readonly projectRootPath: Path; + } + interface PackageInstalledResponse extends ProjectResponse { + readonly kind: ActionPackageInstalled; + readonly success: boolean; + readonly message: string; + } + interface InitializationFailedResponse extends TypingInstallerResponse { + readonly kind: EventInitializationFailed; + readonly message: string; + } + interface ProjectResponse extends TypingInstallerResponse { + readonly projectName: string; + } + interface InvalidateCachedTypings extends ProjectResponse { + readonly kind: ActionInvalidate; + } + interface InstallTypes extends ProjectResponse { + readonly kind: EventBeginInstallTypes | EventEndInstallTypes; + readonly eventId: number; + readonly typingsInstallerVersion: string; + readonly packagesToInstall: ReadonlyArray; + } + interface BeginInstallTypes extends InstallTypes { + readonly kind: EventBeginInstallTypes; + } + interface EndInstallTypes extends InstallTypes { + readonly kind: EventEndInstallTypes; + readonly installSuccess: boolean; + } + interface SetTypings extends ProjectResponse { + readonly typeAcquisition: TypeAcquisition; + readonly compilerOptions: CompilerOptions; + readonly typings: string[]; + readonly unresolvedImports: SortedReadonlyArray; + readonly kind: ActionSet; + } } declare namespace ts { interface Node { @@ -4193,13 +4663,13 @@ declare namespace ts { getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; getFullStart(): number; getEnd(): number; - getWidth(sourceFile?: SourceFile): number; + getWidth(sourceFile?: SourceFileLike): number; getFullWidth(): number; getLeadingTriviaWidth(sourceFile?: SourceFile): number; getFullText(sourceFile?: SourceFile): string; getText(sourceFile?: SourceFile): string; - getFirstToken(sourceFile?: SourceFile): Node; - getLastToken(sourceFile?: SourceFile): Node; + getFirstToken(sourceFile?: SourceFile): Node | undefined; + getLastToken(sourceFile?: SourceFile): Node | undefined; forEachChild(cbNode: (node: Node) => T | undefined, cbNodeArray?: (nodes: NodeArray) => T | undefined): T | undefined; } interface Identifier { @@ -4220,14 +4690,23 @@ declare namespace ts { getProperties(): Symbol[]; getProperty(propertyName: string): Symbol | undefined; getApparentProperties(): Symbol[]; - getCallSignatures(): Signature[]; - getConstructSignatures(): Signature[]; + getCallSignatures(): ReadonlyArray; + getConstructSignatures(): ReadonlyArray; getStringIndexType(): Type | undefined; getNumberIndexType(): Type | undefined; getBaseTypes(): BaseType[] | undefined; getNonNullableType(): Type; getConstraint(): Type | undefined; getDefault(): Type | undefined; + isUnion(): this is UnionType; + isIntersection(): this is IntersectionType; + isUnionOrIntersection(): this is UnionOrIntersectionType; + isLiteral(): this is LiteralType; + isStringLiteral(): this is StringLiteralType; + isNumberLiteral(): this is NumberLiteralType; + isTypeParameter(): this is TypeParameter; + isClassOrInterface(): this is InterfaceType; + isClass(): this is InterfaceType; } interface Signature { getDeclaration(): SignatureDeclaration; @@ -4277,8 +4756,9 @@ declare namespace ts { interface PreProcessedFileInfo { referencedFiles: FileReference[]; typeReferenceDirectives: FileReference[]; + libReferenceDirectives: FileReference[]; importedFiles: FileReference[]; - ambientExternalModules: string[]; + ambientExternalModules?: string[]; isLibFile: boolean; } interface HostCancellationToken { @@ -4296,6 +4776,7 @@ declare namespace ts { getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): IScriptSnapshot | undefined; + getProjectReferences?(): ReadonlyArray | undefined; getLocalizedDiagnosticMessages?(): any; getCancellationToken?(): HostCancellationToken; getCurrentDirectory(): string; @@ -4310,6 +4791,7 @@ declare namespace ts { fileExists?(path: string): boolean; getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; getDirectories?(directoryName: string): string[]; /** @@ -4319,11 +4801,20 @@ declare namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; } + interface UserPreferences { + readonly disableSuggestions?: boolean; + readonly quotePreference?: "double" | "single"; + readonly includeCompletionsForModuleExports?: boolean; + readonly includeCompletionsWithInsertText?: boolean; + readonly importModuleSpecifierPreference?: "relative" | "non-relative"; + readonly allowTextChangesInNewFiles?: boolean; + } interface LanguageService { cleanupSemanticCache(): void; - getSyntacticDiagnostics(fileName: string): Diagnostic[]; + getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; + /** The first time this is called, it will return global diagnostics (no location). */ getSemanticDiagnostics(fileName: string): Diagnostic[]; - getSuggestionDiagnostics(fileName: string): Diagnostic[]; + getSuggestionDiagnostics(fileName: string): DiagnosticWithLocation[]; getCompilerOptionsDiagnostics(): Diagnostic[]; /** * @deprecated Use getEncodedSyntacticClassifications instead. @@ -4335,24 +4826,24 @@ declare namespace ts { getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; - getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo; - getCompletionEntryDetails(fileName: string, position: number, name: string, options: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined): CompletionEntryDetails; - getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol; - getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; - getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; - getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; - getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; + getCompletionsAtPosition(fileName: string, position: number, options: GetCompletionsAtPositionOptions | undefined): CompletionInfo | undefined; + getCompletionEntryDetails(fileName: string, position: number, name: string, formatOptions: FormatCodeOptions | FormatCodeSettings | undefined, source: string | undefined, preferences: UserPreferences | undefined): CompletionEntryDetails | undefined; + getCompletionEntrySymbol(fileName: string, position: number, name: string, source: string | undefined): Symbol | undefined; + getQuickInfoAtPosition(fileName: string, position: number): QuickInfo | undefined; + getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; + getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; + getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; - getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan; - getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; - getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[]; - getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - findReferences(fileName: string, position: number): ReferencedSymbol[]; - getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] | undefined; + getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] | undefined; + getImplementationAtPosition(fileName: string, position: number): ImplementationLocation[] | undefined; + getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; + findReferences(fileName: string, position: number): ReferencedSymbol[] | undefined; + getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[] | undefined; /** @deprecated */ - getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; + getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] | undefined; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; getNavigationTree(fileName: string): NavigationTree; @@ -4363,11 +4854,17 @@ declare namespace ts { getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; - getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; + getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion | undefined; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; - getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; + /** + * This will return a defined result if the position is after the `>` of the opening tag, or somewhere in the text, of a JSXElement with no closing tag. + * Editors should call this after `>` is typed. + */ + getJsxClosingTagAtPosition(fileName: string, position: number): JsxClosingTagInfo | undefined; + getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean): TextSpan | undefined; + toLineColumnOffset?(fileName: string, position: number): LineAndCharacter; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings, preferences: UserPreferences): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings, preferences: UserPreferences): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4377,21 +4874,71 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; - getApplicableRefactors(fileName: string, positionOrRaneg: number | TextRange): ApplicableRefactorInfo[]; - getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string): RefactorEditInfo | undefined; - organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings): ReadonlyArray; + getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined): ApplicableRefactorInfo[]; + getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; + getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): ReadonlyArray; getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; - getProgram(): Program; + getProgram(): Program | undefined; dispose(): void; } + interface JsxClosingTagInfo { + readonly newText: string; + } interface CombinedCodeFixScope { type: "file"; fileName: string; } type OrganizeImportsScope = CombinedCodeFixScope; - interface GetCompletionsAtPositionOptions { - includeExternalModuleExports: boolean; - includeInsertTextCompletions: boolean; + type CompletionsTriggerCharacter = "." | '"' | "'" | "`" | "/" | "@" | "<"; + interface GetCompletionsAtPositionOptions extends UserPreferences { + /** + * If the editor is asking for completions because a certain character was typed + * (as opposed to when the user explicitly requested them) this should be set. + */ + triggerCharacter?: CompletionsTriggerCharacter; + /** @deprecated Use includeCompletionsForModuleExports */ + includeExternalModuleExports?: boolean; + /** @deprecated Use includeCompletionsWithInsertText */ + includeInsertTextCompletions?: boolean; + } + type SignatureHelpTriggerCharacter = "," | "(" | "<"; + type SignatureHelpRetriggerCharacter = SignatureHelpTriggerCharacter | ")"; + interface SignatureHelpItemsOptions { + triggerReason?: SignatureHelpTriggerReason; + } + type SignatureHelpTriggerReason = SignatureHelpInvokedReason | SignatureHelpCharacterTypedReason | SignatureHelpRetriggeredReason; + /** + * Signals that the user manually requested signature help. + * The language service will unconditionally attempt to provide a result. + */ + interface SignatureHelpInvokedReason { + kind: "invoked"; + triggerCharacter?: undefined; + } + /** + * Signals that the signature help request came from a user typing a character. + * Depending on the character and the syntactic context, the request may or may not be served a result. + */ + interface SignatureHelpCharacterTypedReason { + kind: "characterTyped"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter: SignatureHelpTriggerCharacter; + } + /** + * Signals that this signature help request came from typing a character or moving the cursor. + * This should only occur if a signature help session was already active and the editor needs to see if it should adjust. + * The language service will unconditionally attempt to provide a result. + * `triggerCharacter` can be `undefined` for a retrigger caused by a cursor move. + */ + interface SignatureHelpRetriggeredReason { + kind: "retrigger"; + /** + * Character that was responsible for triggering signature help. + */ + triggerCharacter?: SignatureHelpRetriggerCharacter; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4435,6 +4982,7 @@ declare namespace ts { * There will be more than one if this is the result of merging. */ spans: TextSpan[]; + nameSpan: TextSpan | undefined; /** Present if non-empty */ childItems?: NavigationTree[]; } @@ -4454,6 +5002,7 @@ declare namespace ts { interface FileTextChanges { fileName: string; textChanges: TextChange[]; + isNewFile?: boolean; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -4467,15 +5016,18 @@ declare namespace ts { commands?: CodeActionCommand[]; } interface CodeFixAction extends CodeAction { + /** Short name to identify the fix, for use by telemetry. */ + fixName: string; /** * If present, one may call 'getCombinedCodeFix' with this fixId. * This may be omitted to indicate that the code fix can't be applied in a group. */ fixId?: {}; + fixAllDescription?: string; } interface CombinedCodeActions { changes: ReadonlyArray; - commands: ReadonlyArray | undefined; + commands?: ReadonlyArray; } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { @@ -4525,8 +5077,8 @@ declare namespace ts { */ interface RefactorEditInfo { edits: FileTextChanges[]; - renameFilename: string | undefined; - renameLocation: number | undefined; + renameFilename?: string; + renameLocation?: number; commands?: CodeActionCommand[]; } interface TextInsertion { @@ -4537,6 +5089,12 @@ declare namespace ts { interface DocumentSpan { textSpan: TextSpan; fileName: string; + /** + * If the span represents a location that was remapped (e.g. via a .d.ts.map file), + * then the original filename and span will be specified here + */ + originalTextSpan?: TextSpan; + originalFileName?: string; } interface RenameLocation extends DocumentSpan { } @@ -4557,7 +5115,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4569,7 +5127,7 @@ declare namespace ts { name: string; kind: ScriptElementKind; kindModifiers: string; - matchKind: string; + matchKind: "exact" | "prefix" | "substring" | "camelCase"; isCaseSensitive: boolean; fileName: string; textSpan: TextSpan; @@ -4579,7 +5137,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4632,17 +5190,16 @@ declare namespace ts { placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; insertSpaceBeforeTypeAnnotation?: boolean; + indentMultiLineObjectLiteralBeginningOnBlankLine?: boolean; } - interface DefinitionInfo { - fileName: string; - textSpan: TextSpan; + interface DefinitionInfo extends DocumentSpan { kind: ScriptElementKind; name: string; containerKind: ScriptElementKind; containerName: string; } interface DefinitionInfoAndBoundSpan { - definitions: ReadonlyArray; + definitions?: ReadonlyArray; textSpan: TextSpan; } interface ReferencedSymbolDefinitionInfo extends DefinitionInfo { @@ -4674,7 +5231,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4688,13 +5245,13 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; textSpan: TextSpan; - displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + displayParts?: SymbolDisplayPart[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; } interface RenameInfo { canRename: boolean; - localizedErrorMessage: string; + localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; @@ -4746,7 +5303,7 @@ declare namespace ts { interface CompletionEntry { name: string; kind: ScriptElementKind; - kindModifiers: string; + kindModifiers?: string; sortText: string; insertText?: string; /** @@ -4764,8 +5321,8 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; displayParts: SymbolDisplayPart[]; - documentation: SymbolDisplayPart[]; - tags: JSDocTagInfo[]; + documentation?: SymbolDisplayPart[]; + tags?: JSDocTagInfo[]; codeActions?: CodeAction[]; source?: SymbolDisplayPart[]; } @@ -4781,11 +5338,25 @@ declare namespace ts { * the 'Collapse to Definitions' command is invoked. */ autoCollapse: boolean; + /** + * Classification of the contents of the span + */ + kind: OutliningSpanKind; + } + enum OutliningSpanKind { + /** Single or multi-line comments */ + Comment = "comment", + /** Sections marked by '// #region' and '// #endregion' comments */ + Region = "region", + /** Declarations and expressions */ + Code = "code", + /** Contiguous blocks of import declarations */ + Imports = "imports" } enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4794,7 +5365,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4805,7 +5376,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4905,6 +5476,8 @@ declare namespace ts { * */ jsxAttribute = "JSX attribute", + /** String literal */ + string = "string" } enum ScriptElementKindModifier { none = "", @@ -4915,7 +5488,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4940,7 +5513,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4966,7 +5539,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { @@ -5060,15 +5633,15 @@ declare namespace ts { } declare namespace ts { /** The version of the language service API */ - const servicesVersion = "0.7"; + const servicesVersion = "0.8"; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; - function displayPartsToString(displayParts: SymbolDisplayPart[]): string; + function displayPartsToString(displayParts: SymbolDisplayPart[] | undefined): string; function getDefaultCompilerOptions(): CompilerOptions; function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; - function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; - function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange | undefined, aggressiveChecks?: boolean): SourceFile; + function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry, syntaxOnly?: boolean): LanguageService; /** * Get the path of the default library files (lib.d.ts) as distributed with the typescript * node package. diff --git a/src/lib/typescriptServices.js b/src/lib/typescriptServices.js index 4d36f184..bccad177 100644 --- a/src/lib/typescriptServices.js +++ b/src/lib/typescriptServices.js @@ -14,18 +14,55 @@ 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]; +var __assign = (this && this.__assign) || function () { + __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; + }; + return __assign.apply(this, arguments); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - return t; +}; +var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; }; var __extends = (this && this.__extends) || (function () { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + } return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } @@ -33,6 +70,13 @@ var __extends = (this && this.__extends) || (function () { }; })(); var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.0"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".1"; +})(ts || (ts = {})); (function (ts) { /* @internal */ var Comparison; @@ -41,7 +85,1953 @@ var ts; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; })(Comparison = ts.Comparison || (ts.Comparison = {})); - // token > SyntaxKind.Identifer => token is a keyword +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; + } + /** Create a new map. If a template object is provided, the map will copy entries from it. */ + function createMap() { + return new ts.MapCtr(); + } + ts.createMap = createMap; + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + function createMapFromTemplate(template) { + var map = new ts.MapCtr(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; + // Internet Explorer's Map doesn't support iteration, so don't use it. + // tslint:disable-next-line no-in-operator variable-name + ts.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 = /** @class */ (function () { + function MapIterator(data, selector) { + this.index = 0; + this.data = data; + this.selector = selector; + this.keys = Object.keys(data); + } + MapIterator.prototype.next = function () { + var index = this.index; + if (index < this.keys.length) { + this.index++; + return { value: this.selector(this.data, this.keys[index]), done: false }; + } + return { value: undefined, done: true }; + }; + return MapIterator; + }()); + return /** @class */ (function () { + function class_1() { + this.data = createDictionaryObject(); + this.size = 0; + } + class_1.prototype.get = function (key) { + return this.data[key]; + }; + class_1.prototype.set = function (key, value) { + if (!this.has(key)) { + this.size++; + } + this.data[key] = value; + return this; + }; + class_1.prototype.has = function (key) { + // tslint:disable-next-line:no-in-operator + return key in this.data; + }; + class_1.prototype.delete = function (key) { + if (this.has(key)) { + this.size--; + delete this.data[key]; + return true; + } + return false; + }; + class_1.prototype.clear = function () { + this.data = createDictionaryObject(); + this.size = 0; + }; + class_1.prototype.keys = function () { + return new MapIterator(this.data, function (_data, key) { return key; }); + }; + class_1.prototype.values = function () { + return new MapIterator(this.data, function (data, key) { return data[key]; }); + }; + class_1.prototype.entries = function () { + return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); + }; + class_1.prototype.forEach = function (action) { + for (var key in this.data) { + action(this.data[key], key); + } + }; + return class_1; + }()); + } + function length(array) { + return array ? array.length : 0; + } + ts.length = length; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEach(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + return undefined; + } + ts.forEach = forEach; + /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ + function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result !== undefined) { + return result; + } + } + return undefined; + } + ts.firstDefined = firstDefined; + function firstDefinedIterator(iter, callback) { + while (true) { + var _a = iter.next(), value = _a.value, done = _a.done; + if (done) { + return undefined; + } + var result = callback(value); + if (result !== undefined) { + return result; + } + } + } + ts.firstDefinedIterator = firstDefinedIterator; + function zipWith(arrayA, arrayB, callback) { + var result = []; + Debug.assertEqual(arrayA.length, arrayB.length); + for (var i = 0; i < arrayA.length; i++) { + result.push(callback(arrayA[i], arrayB[i], i)); + } + return result; + } + ts.zipWith = zipWith; + function zipToIterator(arrayA, arrayB) { + Debug.assertEqual(arrayA.length, arrayB.length); + var i = 0; + return { + next: function () { + if (i === arrayA.length) { + return { value: undefined, done: true }; + } + i++; + return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; + } + }; + } + ts.zipToIterator = zipToIterator; + function zipToMap(keys, values) { + Debug.assert(keys.length === values.length); + var map = createMap(); + for (var i = 0; i < keys.length; ++i) { + map.set(keys[i], values[i]); + } + return map; + } + ts.zipToMap = zipToMap; + /** + * Iterates through `array` by index and performs the callback on each element of array until the callback + * returns a falsey value, then returns false. + * If no such value is found, the callback is applied to each element of array and `true` is returned. + */ + function every(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (!callback(array[i], i)) { + return false; + } + } + } + return true; + } + ts.every = every; + function find(array, predicate) { + for (var i = 0; i < array.length; i++) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.find = find; + function findLast(array, predicate) { + for (var i = array.length - 1; i >= 0; i--) { + var value = array[i]; + if (predicate(value, i)) { + return value; + } + } + return undefined; + } + ts.findLast = findLast; + /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ + function findIndex(array, predicate, startIndex) { + for (var i = startIndex || 0; i < array.length; i++) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findIndex = findIndex; + function findLastIndex(array, predicate, startIndex) { + for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) { + if (predicate(array[i], i)) { + return i; + } + } + return -1; + } + ts.findLastIndex = findLastIndex; + /** + * Returns the first truthy result of `callback`, or else fails. + * This is like `forEach`, but never returns undefined. + */ + function findMap(array, callback) { + for (var i = 0; i < array.length; i++) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + return Debug.fail(); + } + ts.findMap = findMap; + function contains(array, value, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (array) { + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; + if (equalityComparer(v, value)) { + return true; + } + } + } + return false; + } + ts.contains = contains; + function arraysEqual(a, b, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); + } + ts.arraysEqual = arraysEqual; + function indexOfAnyCharCode(text, charCodes, start) { + for (var i = start || 0; i < text.length; i++) { + if (contains(charCodes, text.charCodeAt(i))) { + return i; + } + } + return -1; + } + ts.indexOfAnyCharCode = indexOfAnyCharCode; + function countWhere(array, predicate) { + var count = 0; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (predicate(v, i)) { + count++; + } + } + } + return count; + } + ts.countWhere = countWhere; + function filter(array, f) { + if (array) { + var len = array.length; + var i = 0; + while (i < len && f(array[i])) + i++; + if (i < len) { + var result = array.slice(0, i); + i++; + while (i < len) { + var item = array[i]; + if (f(item)) { + result.push(item); + } + i++; + } + return result; + } + } + return array; + } + ts.filter = filter; + function filterMutate(array, f) { + var outIndex = 0; + for (var i = 0; i < array.length; i++) { + if (f(array[i], i, array)) { + array[outIndex] = array[i]; + outIndex++; + } + } + array.length = outIndex; + } + ts.filterMutate = filterMutate; + function clear(array) { + array.length = 0; + } + ts.clear = clear; + function map(array, f) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + result.push(f(array[i], i)); + } + } + return result; + } + ts.map = map; + function mapIterator(iter, mapFn) { + return { + next: function () { + var iterRes = iter.next(); + return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; + } + }; + } + ts.mapIterator = mapIterator; + function sameMap(array, f) { + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = f(item, i); + if (item !== mapped) { + var result = array.slice(0, i); + result.push(mapped); + for (i++; i < array.length; i++) { + result.push(f(array[i], i)); + } + return result; + } + } + } + return array; + } + ts.sameMap = sameMap; + function flatten(array) { + var result; + if (array) { + result = []; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatten = flatten; + function flatMap(array, mapfn) { + var result; + if (array) { + result = []; + for (var i = 0; i < array.length; i++) { + var v = mapfn(array[i], i); + if (v) { + if (isArray(v)) { + addRange(result, v); + } + else { + result.push(v); + } + } + } + } + return result; + } + ts.flatMap = flatMap; + function flatMapIterator(iter, mapfn) { + var first = iter.next(); + if (first.done) { + return ts.emptyIterator; + } + var currentIter = getIterator(first.value); + return { + next: function () { + while (true) { + var currentRes = currentIter.next(); + if (!currentRes.done) { + return currentRes; + } + var iterRes = iter.next(); + if (iterRes.done) { + return iterRes; + } + currentIter = getIterator(iterRes.value); + } + }, + }; + function getIterator(x) { + var res = mapfn(x); + return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; + } + } + ts.flatMapIterator = flatMapIterator; + function sameFlatMap(array, mapfn) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var item = array[i]; + var mapped = mapfn(item, i); + if (result || item !== mapped || isArray(mapped)) { + if (!result) { + result = array.slice(0, i); + } + if (isArray(mapped)) { + addRange(result, mapped); + } + else { + result.push(mapped); + } + } + } + } + return result || array; + } + ts.sameFlatMap = sameFlatMap; + function mapAllOrFail(array, mapFn) { + var result = []; + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped === undefined) { + return undefined; + } + result.push(mapped); + } + return result; + } + ts.mapAllOrFail = mapAllOrFail; + function mapDefined(array, mapFn) { + var result = []; + if (array) { + for (var i = 0; i < array.length; i++) { + var mapped = mapFn(array[i], i); + if (mapped !== undefined) { + result.push(mapped); + } + } + } + return result; + } + ts.mapDefined = mapDefined; + function mapDefinedIterator(iter, mapFn) { + return { + next: function () { + while (true) { + var res = iter.next(); + if (res.done) { + return res; + } + var value = mapFn(res.value); + if (value !== undefined) { + return { value: value, done: false }; + } + } + } + }; + } + ts.mapDefinedIterator = mapDefinedIterator; + ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; + function singleIterator(value) { + var done = false; + return { + next: function () { + var wasDone = done; + done = true; + return wasDone ? { value: undefined, done: true } : { value: value, done: false }; + } + }; + } + ts.singleIterator = singleIterator; + function spanMap(array, keyfn, mapfn) { + var result; + if (array) { + result = []; + var len = array.length; + var previousKey = void 0; + var key = void 0; + var start = 0; + var pos = 0; + while (start < len) { + while (pos < len) { + var value = array[pos]; + key = keyfn(value, pos); + if (pos === 0) { + previousKey = key; + } + else if (key !== previousKey) { + break; + } + pos++; + } + if (start < pos) { + var v = mapfn(array.slice(start, pos), previousKey, start, pos); + if (v) { + result.push(v); + } + start = pos; + } + previousKey = key; + pos++; + } + } + return result; + } + ts.spanMap = spanMap; + function mapEntries(map, f) { + if (!map) { + return undefined; + } + var result = createMap(); + map.forEach(function (value, key) { + var _a = f(key, value), newKey = _a[0], newValue = _a[1]; + result.set(newKey, newValue); + }); + return result; + } + ts.mapEntries = mapEntries; + function some(array, predicate) { + if (array) { + if (predicate) { + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var v = array_3[_i]; + if (predicate(v)) { + return true; + } + } + } + else { + return array.length > 0; + } + } + return false; + } + ts.some = some; + /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ + function getRangesWhere(arr, pred, cb) { + var start; + for (var i = 0; i < arr.length; i++) { + if (pred(arr[i])) { + start = start === undefined ? i : start; + } + else { + if (start !== undefined) { + cb(start, i); + start = undefined; + } + } + } + if (start !== undefined) + cb(start, arr.length); + } + ts.getRangesWhere = getRangesWhere; + function concatenate(array1, array2) { + if (!some(array2)) + return array1; + if (!some(array1)) + return array2; + return array1.concat(array2); + } + ts.concatenate = concatenate; + function deduplicateRelational(array, equalityComparer, comparer) { + // Perform a stable sort of the array. This ensures the first entry in a list of + // duplicates remains the first entry in the result. + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + var last = array[indices[0]]; + var deduplicated = [indices[0]]; + for (var i = 1; i < indices.length; i++) { + var index = indices[i]; + var item = array[index]; + if (!equalityComparer(last, item)) { + deduplicated.push(index); + last = item; + } + } + // restore original order + deduplicated.sort(); + return deduplicated.map(function (i) { return array[i]; }); + } + function deduplicateEquality(array, equalityComparer) { + var result = []; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var item = array_4[_i]; + pushIfUnique(result, item, equalityComparer); + } + return result; + } + function deduplicate(array, equalityComparer, comparer) { + return !array ? undefined : + array.length === 0 ? [] : + array.length === 1 ? array.slice() : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : + deduplicateEquality(array, equalityComparer); + } + ts.deduplicate = deduplicate; + function deduplicateSorted(array, comparer) { + if (!array) + return undefined; + if (array.length === 0) + return []; + var last = array[0]; + var deduplicated = [last]; + for (var i = 1; i < array.length; i++) { + var next = array[i]; + switch (comparer(next, last)) { + // equality comparison + case true: + // relational comparison + case 0 /* EqualTo */: + continue; + case -1 /* LessThan */: + // If `array` is sorted, `next` should **never** be less than `last`. + return Debug.fail("Array is unsorted."); + } + deduplicated.push(last = next); + } + return deduplicated; + } + function insertSorted(array, insert, compare) { + if (array.length === 0) { + array.push(insert); + return; + } + var insertIndex = binarySearch(array, insert, identity, compare); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, insert); + } + } + ts.insertSorted = insertSorted; + function sortAndDeduplicate(array, comparer, equalityComparer) { + return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); + } + ts.sortAndDeduplicate = sortAndDeduplicate; + function arrayIsEqualTo(array1, array2, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (!array1 || !array2) { + return array1 === array2; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; i++) { + if (!equalityComparer(array1[i], array2[i])) { + return false; + } + } + return true; + } + ts.arrayIsEqualTo = arrayIsEqualTo; + function compact(array) { + var result; + if (array) { + for (var i = 0; i < array.length; i++) { + var v = array[i]; + if (result || !v) { + if (!result) { + result = array.slice(0, i); + } + if (v) { + result.push(v); + } + } + } + } + return result || array; + } + ts.compact = compact; + /** + * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that + * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted + * based on the provided comparer. + */ + function relativeComplement(arrayA, arrayB, comparer) { + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) + return arrayB; + var result = []; + loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { + if (offsetB > 0) { + // Ensure `arrayB` is properly sorted. + Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); + } + loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { + if (offsetA > startA) { + // Ensure `arrayA` is properly sorted. We only need to perform this check if + // `offsetA` has changed since we entered the loop. + Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); + } + switch (comparer(arrayB[offsetB], arrayA[offsetA])) { + case -1 /* LessThan */: + // If B is less than A, B does not exist in arrayA. Add B to the result and + // move to the next element in arrayB without changing the current position + // in arrayA. + result.push(arrayB[offsetB]); + continue loopB; + case 0 /* EqualTo */: + // If B is equal to A, B exists in arrayA. Move to the next element in + // arrayB without adding B to the result or changing the current position + // in arrayA. + continue loopB; + case 1 /* GreaterThan */: + // If B is greater than A, we need to keep looking for B in arrayA. Move to + // the next element in arrayA and recheck. + continue loopA; + } + } + } + return result; + } + ts.relativeComplement = relativeComplement; + function sum(array, prop) { + var result = 0; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var v = array_5[_i]; + result += v[prop]; + } + return result; + } + ts.sum = sum; + function append(to, value) { + if (value === undefined) + return to; + if (to === undefined) + return [value]; + to.push(value); + return to; + } + ts.append = append; + /** + * Gets the actual offset into an array for a relative offset. Negative offsets indicate a + * position offset from the end of the array. + */ + function toOffset(array, offset) { + return offset < 0 ? array.length + offset : offset; + } + function addRange(to, from, start, end) { + if (from === undefined || from.length === 0) + return to; + if (to === undefined) + return from.slice(start, end); + start = start === undefined ? 0 : toOffset(from, start); + end = end === undefined ? from.length : toOffset(from, end); + for (var i = start; i < end && i < from.length; i++) { + if (from[i] !== undefined) { + to.push(from[i]); + } + } + return to; + } + ts.addRange = addRange; + /** + * @return Whether the value was added. + */ + function pushIfUnique(array, toAdd, equalityComparer) { + if (contains(array, toAdd, equalityComparer)) { + return false; + } + else { + array.push(toAdd); + return true; + } + } + ts.pushIfUnique = pushIfUnique; + /** + * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. + */ + function appendIfUnique(array, toAdd, equalityComparer) { + if (array) { + pushIfUnique(array, toAdd, equalityComparer); + return array; + } + else { + return [toAdd]; + } + } + ts.appendIfUnique = appendIfUnique; + function stableSortIndices(array, indices, comparer) { + // sort indices by value then position + indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); + } + /** + * Returns a new sorted array. + */ + function sort(array, comparer) { + return array.slice().sort(comparer); + } + ts.sort = sort; + function arrayIterator(array) { + var i = 0; + return { next: function () { + if (i === array.length) { + return { value: undefined, done: true }; + } + else { + i++; + return { value: array[i - 1], done: false }; + } + } }; + } + ts.arrayIterator = arrayIterator; + /** + * Stable sort of an array. Elements equal to each other maintain their relative position in the array. + */ + function stableSort(array, comparer) { + var indices = array.map(function (_, i) { return i; }); + stableSortIndices(array, indices, comparer); + return indices.map(function (i) { return array[i]; }); + } + ts.stableSort = stableSort; + function rangeEquals(array1, array2, pos, end) { + while (pos < end) { + if (array1[pos] !== array2[pos]) { + return false; + } + pos++; + } + return true; + } + ts.rangeEquals = rangeEquals; + /** + * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. + * A negative offset indicates the element should be retrieved from the end of the array. + */ + function elementAt(array, offset) { + if (array) { + offset = toOffset(array, offset); + if (offset < array.length) { + return array[offset]; + } + } + return undefined; + } + ts.elementAt = elementAt; + /** + * Returns the first element of an array if non-empty, `undefined` otherwise. + */ + function firstOrUndefined(array) { + return array.length === 0 ? undefined : array[0]; + } + ts.firstOrUndefined = firstOrUndefined; + function first(array) { + Debug.assert(array.length !== 0); + return array[0]; + } + ts.first = first; + /** + * Returns the last element of an array if non-empty, `undefined` otherwise. + */ + function lastOrUndefined(array) { + return array.length === 0 ? undefined : array[array.length - 1]; + } + ts.lastOrUndefined = lastOrUndefined; + function last(array) { + Debug.assert(array.length !== 0); + return array[array.length - 1]; + } + ts.last = last; + /** + * Returns the only element of an array if it contains only one element, `undefined` otherwise. + */ + function singleOrUndefined(array) { + return array && array.length === 1 + ? array[0] + : undefined; + } + ts.singleOrUndefined = singleOrUndefined; + function singleOrMany(array) { + return array && array.length === 1 + ? array[0] + : array; + } + ts.singleOrMany = singleOrMany; + function replaceElement(array, index, value) { + var result = array.slice(0); + result[index] = value; + return result; + } + ts.replaceElement = replaceElement; + /** + * Performs a binary search, finding the index at which `value` occurs in `array`. + * If no such index is found, returns the 2's-complement of first index at which + * `array[index]` exceeds `value`. + * @param array A sorted array whose first element must be no larger than number + * @param value The value to be searched for in the array. + * @param keySelector A callback used to select the search key from `value` and each element of + * `array`. + * @param keyComparer A callback used to compare two keys in a sorted array. + * @param offset An offset into `array` at which to start the search. + */ + function binarySearch(array, value, keySelector, keyComparer, offset) { + if (!array || array.length === 0) { + return -1; + } + var low = offset || 0; + var high = array.length - 1; + var key = keySelector(value); + while (low <= high) { + var middle = low + ((high - low) >> 1); + var midKey = keySelector(array[middle]); + switch (keyComparer(midKey, key)) { + case -1 /* LessThan */: + low = middle + 1; + break; + case 0 /* EqualTo */: + return middle; + case 1 /* GreaterThan */: + high = middle - 1; + break; + } + } + return ~low; + } + ts.binarySearch = binarySearch; + function reduceLeft(array, f, initial, start, count) { + if (array && array.length > 0) { + var size = array.length; + if (size > 0) { + var pos = start === undefined || start < 0 ? 0 : start; + var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; + var result = void 0; + if (arguments.length <= 2) { + result = array[pos]; + pos++; + } + else { + result = initial; + } + while (pos <= end) { + result = f(result, array[pos], pos); + pos++; + } + return result; + } + } + return initial; + } + ts.reduceLeft = reduceLeft; + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Indicates whether a map-like contains an own property with the specified key. + * + * @param map A map-like. + * @param key A property key. + */ + function hasProperty(map, key) { + return hasOwnProperty.call(map, key); + } + ts.hasProperty = hasProperty; + /** + * Gets the value of an owned property in a map-like. + * + * @param map A map-like. + * @param key A property key. + */ + function getProperty(map, key) { + return hasOwnProperty.call(map, key) ? map[key] : undefined; + } + ts.getProperty = getProperty; + /** + * Gets the owned, enumerable property keys of a map-like. + */ + function getOwnKeys(map) { + var keys = []; + for (var key in map) { + if (hasOwnProperty.call(map, key)) { + keys.push(key); + } + } + return keys; + } + ts.getOwnKeys = getOwnKeys; + function getOwnValues(sparseArray) { + var values = []; + for (var key in sparseArray) { + if (hasOwnProperty.call(sparseArray, key)) { + values.push(sparseArray[key]); + } + } + return values; + } + ts.getOwnValues = getOwnValues; + function arrayFrom(iterator, map) { + var _a; + var result = []; + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + result.push(map ? map(value) : value); + } + return result; + } + ts.arrayFrom = arrayFrom; + function assign(t) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var arg = args_1[_a]; + for (var p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; // TODO: GH#23368 + } + } + } + return t; + } + ts.assign = assign; + /** + * Performs a shallow equality comparison of the contents of two map-likes. + * + * @param left A map-like whose properties should be compared. + * @param right A map-like whose properties should be compared. + */ + function equalOwnProperties(left, right, equalityComparer) { + if (equalityComparer === void 0) { equalityComparer = equateValues; } + if (left === right) + return true; + if (!left || !right) + return false; + for (var key in left) { + if (hasOwnProperty.call(left, key)) { + if (!hasOwnProperty.call(right, key) === undefined) + return false; + if (!equalityComparer(left[key], right[key])) + return false; + } + } + for (var key in right) { + if (hasOwnProperty.call(right, key)) { + if (!hasOwnProperty.call(left, key)) + return false; + } + } + return true; + } + ts.equalOwnProperties = equalOwnProperties; + function arrayToMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMap(); + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var value = array_6[_i]; + var key = makeKey(value); + if (key !== undefined) + result.set(key, makeValue(value)); + } + return result; + } + ts.arrayToMap = arrayToMap; + function arrayToNumericMap(array, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = []; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var value = array_7[_i]; + result[makeKey(value)] = makeValue(value); + } + return result; + } + ts.arrayToNumericMap = arrayToNumericMap; + function arrayToMultiMap(values, makeKey, makeValue) { + if (makeValue === void 0) { makeValue = identity; } + var result = createMultiMap(); + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var value = values_1[_i]; + result.add(makeKey(value), makeValue(value)); + } + return result; + } + ts.arrayToMultiMap = arrayToMultiMap; + function group(values, getGroupId) { + return arrayFrom(arrayToMultiMap(values, getGroupId).values()); + } + ts.group = group; + function clone(object) { + var result = {}; + for (var id in object) { + if (hasOwnProperty.call(object, id)) { + result[id] = object[id]; + } + } + return result; + } + ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + result[id] = second[id]; + } + } + for (var id in first) { + if (hasOwnProperty.call(first, id)) { + result[id] = first[id]; + } + } + return result; + } + ts.extend = extend; + function createMultiMap() { + var map = createMap(); + map.add = multiMapAdd; + map.remove = multiMapRemove; + return map; + } + ts.createMultiMap = createMultiMap; + function multiMapAdd(key, value) { + var values = this.get(key); + if (values) { + values.push(value); + } + else { + this.set(key, values = [value]); + } + return values; + } + function multiMapRemove(key, value) { + var values = this.get(key); + if (values) { + unorderedRemoveItem(values, value); + if (!values.length) { + this.delete(key); + } + } + } + /** + * Tests whether a value is an array. + */ + function isArray(value) { + return Array.isArray ? Array.isArray(value) : value instanceof Array; + } + ts.isArray = isArray; + function toArray(value) { + return isArray(value) ? value : [value]; + } + ts.toArray = toArray; + /** + * Tests whether a value is string + */ + function isString(text) { + return typeof text === "string"; + } + ts.isString = isString; + function tryCast(value, test) { + return value !== undefined && test(value) ? value : undefined; + } + ts.tryCast = tryCast; + function cast(value, test) { + if (value !== undefined && test(value)) + return value; + return Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + Debug.getFunctionName(test) + "'."); + } + ts.cast = cast; + /** Does nothing. */ + function noop(_) { } // tslint:disable-line no-empty + ts.noop = noop; + /** Do nothing and return false */ + function returnFalse() { return false; } + ts.returnFalse = returnFalse; + /** Do nothing and return true */ + function returnTrue() { return true; } + ts.returnTrue = returnTrue; + /** Returns its argument. */ + function identity(x) { return x; } + ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; + /** Throws an error because a function is not implemented. */ + function notImplemented() { + throw new Error("Not implemented"); + } + ts.notImplemented = notImplemented; + function memoize(callback) { + var value; + return function () { + if (callback) { + value = callback(); + callback = undefined; + } + return value; + }; + } + ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (_) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; + 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 /* None */; + Debug.isDebugging = false; + function shouldAssert(level) { + return Debug.currentAssertionLevel >= level; + } + Debug.shouldAssert = shouldAssert; + function assert(expression, message, verboseDebugInfo, stackCrawlMark) { + if (!expression) { + if (verboseDebugInfo) { + message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); + } + fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); + } + } + 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."); + if (Error.captureStackTrace) { + Error.captureStackTrace(e, stackCrawlMark || fail); + } + throw e; + } + Debug.fail = fail; + function assertDefined(value, message) { + if (value === undefined || value === null) + return fail(message); + return value; + } + Debug.assertDefined = assertDefined; + function assertEachDefined(value, message) { + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var v = value_1[_i]; + assertDefined(v, message); + } + return value; + } + Debug.assertEachDefined = assertEachDefined; + function assertNever(member, message, stackCrawlMark) { + return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); + } + Debug.assertNever = assertNever; + function getFunctionName(func) { + if (typeof func !== "function") { + return ""; + } + else if (func.hasOwnProperty("name")) { + return func.name; + } + else { + var text = Function.prototype.toString.call(func); + var match = /^function\s+([\w\$]+)\s*\(/.exec(text); + return match ? match[1] : ""; + } + } + Debug.getFunctionName = getFunctionName; + })(Debug = ts.Debug || (ts.Debug = {})); + function equateValues(a, b) { + return a === b; + } + ts.equateValues = equateValues; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function equateStringsCaseInsensitive(a, b) { + return a === b + || a !== undefined + && b !== undefined + && a.toUpperCase() === b.toUpperCase(); + } + ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; + /** + * Compare the equality of two strings using a case-sensitive ordinal comparison. + * + * Case-sensitive comparisons compare both strings one code-point at a time using the + * integer value of each code-point. + */ + function equateStringsCaseSensitive(a, b) { + return equateValues(a, b); + } + ts.equateStringsCaseSensitive = equateStringsCaseSensitive; + function compareComparableValues(a, b) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + a < b ? -1 /* LessThan */ : + 1 /* GreaterThan */; + } + /** + * Compare two numeric values for their order relative to each other. + * To compare strings, use any of the `compareStrings` functions. + */ + function compareValues(a, b) { + return compareComparableValues(a, b); + } + ts.compareValues = compareValues; + function min(a, b, compare) { + return compare(a, b) === -1 /* LessThan */ ? a : b; + } + ts.min = min; + /** + * Compare two strings using a case-insensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-insensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point after applying `toUpperCase` to each string. We always map both + * strings to their upper-case form as some unicode characters do not properly round-trip to + * lowercase (such as `ẞ` (German sharp capital s)). + */ + function compareStringsCaseInsensitive(a, b) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + a = a.toUpperCase(); + b = b.toUpperCase(); + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; + /** + * Compare two strings using a case-sensitive ordinal comparison. + * + * Ordinal comparisons are based on the difference between the unicode code points of both + * strings. Characters with multiple unicode representations are considered unequal. Ordinal + * comparisons provide predictable ordering, but place "a" after "B". + * + * Case-sensitive comparisons compare both strings one code-point at a time using the integer + * value of each code-point. + */ + function compareStringsCaseSensitive(a, b) { + return compareComparableValues(a, b); + } + ts.compareStringsCaseSensitive = compareStringsCaseSensitive; + function getStringComparer(ignoreCase) { + return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; + } + ts.getStringComparer = getStringComparer; + /** + * Creates a string comparer for use with string collation in the UI. + */ + var createUIStringComparer = (function () { + var defaultComparer; + var enUSComparer; + var stringComparerFactory = getStringComparerFactory(); + return createStringComparer; + function compareWithCallback(a, b, comparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var value = comparer(a, b); + return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + function createIntlCollatorStringComparer(locale) { + // Intl.Collator.prototype.compare is bound to the collator. See NOTE in + // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare + var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; + return function (a, b) { return compareWithCallback(a, b, comparer); }; + } + function createLocaleCompareStringComparer(locale) { + // if the locale is not the default locale (`undefined`), use the fallback comparer. + if (locale !== undefined) + return createFallbackStringComparer(); + return function (a, b) { return compareWithCallback(a, b, compareStrings); }; + function compareStrings(a, b) { + return a.localeCompare(b); + } + } + function createFallbackStringComparer() { + // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". + // We first sort case insensitively. So "Aaa" will come before "baa". + // Then we sort case sensitively, so "aaa" will come before "Aaa". + // + // For case insensitive comparisons we always map both strings to their + // upper-case form as some unicode characters do not properly round-trip to + // lowercase (such as `ẞ` (German sharp capital s)). + return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; + function compareDictionaryOrder(a, b) { + return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); + } + function compareStrings(a, b) { + return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; + } + } + function getStringComparerFactory() { + // If the host supports Intl, we use it for comparisons using the default locale. + if (typeof Intl === "object" && typeof Intl.Collator === "function") { + return createIntlCollatorStringComparer; + } + // If the host does not support Intl, we fall back to localeCompare. + // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. + if (typeof String.prototype.localeCompare === "function" && + typeof String.prototype.toLocaleUpperCase === "function" && + "a".localeCompare("B") < 0) { + return createLocaleCompareStringComparer; + } + // Otherwise, fall back to ordinal comparison: + return createFallbackStringComparer; + } + function createStringComparer(locale) { + // Hold onto common string comparers. This avoids constantly reallocating comparers during + // tests. + if (locale === undefined) { + return defaultComparer || (defaultComparer = stringComparerFactory(locale)); + } + else if (locale === "en-US") { + return enUSComparer || (enUSComparer = stringComparerFactory(locale)); + } + else { + return stringComparerFactory(locale); + } + } + })(); + var uiComparerCaseSensitive; + var uiLocale; + function getUILocale() { + return uiLocale; + } + ts.getUILocale = getUILocale; + function setUILocale(value) { + if (uiLocale !== value) { + uiLocale = value; + uiComparerCaseSensitive = undefined; + } + } + ts.setUILocale = setUILocale; + /** + * Compare two strings in a using the case-sensitive sort behavior of the UI locale. + * + * Ordering is not predictable between different host locales, but is best for displaying + * ordered data for UI presentation. Characters with multiple unicode representations may + * be considered equal. + * + * Case-sensitive comparisons compare strings that differ in base characters, or + * accents/diacritic marks, or case as unequal. + */ + function compareStringsCaseSensitiveUI(a, b) { + var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return comparer(a, b); + } + ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; + function compareProperties(a, b, key, comparer) { + return a === b ? 0 /* EqualTo */ : + a === undefined ? -1 /* LessThan */ : + b === undefined ? 1 /* GreaterThan */ : + comparer(a[key], b[key]); + } + ts.compareProperties = compareProperties; + /** True is greater than false. */ + function compareBooleans(a, b) { + return compareValues(a ? 1 : 0, b ? 1 : 0); + } + ts.compareBooleans = compareBooleans; + /** + * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. + * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance. + * + * If there is a candidate that's the same except for case, return that. + * If there is a candidate that's within one edit of the name, return that. + * Otherwise, return the candidate with the smallest Levenshtein distance, + * except for candidates: + * * With no name + * * Whose length differs from the target name by more than 0.34 of the length of the name. + * * Whose levenshtein distance is more than 0.4 of the length of the name + * (0.4 allows 1 substitution/transposition for every 5 characters, + * and 1 insertion/deletion at 3 characters) + */ + function getSpellingSuggestion(name, candidates, getName) { + var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); + var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. + var bestCandidate; + var justCheckExactMatches = false; + var nameLowerCase = name.toLowerCase(); + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; + var candidateName = getName(candidate); + if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) { + var candidateNameLowerCase = candidateName.toLowerCase(); + if (candidateNameLowerCase === nameLowerCase) { + if (candidateName === name) { + continue; + } + return candidate; + } + if (justCheckExactMatches) { + continue; + } + if (candidateName.length < 3) { + // Don't bother, user would have noticed a 2-character name having an extra character + continue; + } + // Only care about a result better than the best so far. + var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); + if (distance === undefined) { + continue; + } + if (distance < 3) { + justCheckExactMatches = true; + bestCandidate = candidate; + } + else { + Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined + bestDistance = distance; + bestCandidate = candidate; + } + } + } + return bestCandidate; + } + ts.getSpellingSuggestion = getSpellingSuggestion; + function levenshteinWithMax(s1, s2, max) { + var previous = new Array(s2.length + 1); + var current = new Array(s2.length + 1); + /** Represents any value > max. We don't care about the particular value. */ + var big = max + 1; + for (var i = 0; i <= s2.length; i++) { + previous[i] = i; + } + for (var i = 1; i <= s1.length; i++) { + var c1 = s1.charCodeAt(i - 1); + var minJ = i > max ? i - max : 1; + var maxJ = s2.length > max + i ? max + i : s2.length; + current[0] = i; + /** Smallest value of the matrix in the ith column. */ + var colMin = i; + for (var j = 1; j < minJ; j++) { + current[j] = big; + } + for (var j = minJ; j <= maxJ; j++) { + var dist = c1 === s2.charCodeAt(j - 1) + ? previous[j - 1] + : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); + current[j] = dist; + colMin = Math.min(colMin, dist); + } + for (var j = maxJ + 1; j <= s2.length; j++) { + current[j] = big; + } + if (colMin > max) { + // Give up -- everything in this column is > max and it can't get better in future columns. + return undefined; + } + var temp = previous; + previous = current; + current = temp; + } + var res = previous[s2.length]; + return res > max ? undefined : res; + } + function endsWith(str, suffix) { + var expectedPos = str.length - suffix.length; + return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; + } + ts.endsWith = endsWith; + function removeSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; + } + ts.removeSuffix = removeSuffix; + function tryRemoveSuffix(str, suffix) { + return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; + } + ts.tryRemoveSuffix = tryRemoveSuffix; + function stringContains(str, substring) { + return str.indexOf(substring) !== -1; + } + ts.stringContains = stringContains; + function fileExtensionIs(path, extension) { + return path.length > extension.length && endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Takes a string like "jquery-min.4.2.3" and returns "jquery" + */ + function removeMinAndVersionNumbers(fileName) { + // Match a "." or "-" followed by a version number or 'min' at the end of the name + var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; + // The "min" or version may both be present, in either order, so try applying the above twice. + return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); + } + ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; + /** Remove an item from an array, moving everything to its right one space left. */ + function orderedRemoveItem(array, item) { + for (var i = 0; i < array.length; i++) { + if (array[i] === item) { + orderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + ts.orderedRemoveItem = orderedRemoveItem; + /** Remove an item by index from an array, moving everything to its right one space left. */ + function orderedRemoveItemAt(array, index) { + // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. + for (var i = index; i < array.length - 1; i++) { + array[i] = array[i + 1]; + } + array.pop(); + } + ts.orderedRemoveItemAt = orderedRemoveItemAt; + function unorderedRemoveItemAt(array, index) { + // Fill in the "hole" left at `index`. + array[index] = array[array.length - 1]; + array.pop(); + } + ts.unorderedRemoveItemAt = unorderedRemoveItemAt; + /** Remove the *first* occurrence of `item` from the array. */ + function unorderedRemoveItem(array, item) { + return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); + } + ts.unorderedRemoveItem = unorderedRemoveItem; + /** Remove the *first* element satisfying `predicate`. */ + function unorderedRemoveFirstItemWhere(array, predicate) { + for (var i = 0; i < array.length; i++) { + if (predicate(array[i])) { + unorderedRemoveItemAt(array, i); + return true; + } + } + return false; + } + function createGetCanonicalFileName(useCaseSensitiveFileNames) { + return useCaseSensitiveFileNames ? identity : toLowerCase; + } + ts.createGetCanonicalFileName = createGetCanonicalFileName; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { + var v = values_2[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function startsWith(str, prefix) { + return str.lastIndexOf(prefix, 0) === 0; + } + ts.startsWith = startsWith; + function removePrefix(str, prefix) { + return startsWith(str, prefix) ? str.substr(prefix.length) : str; + } + ts.removePrefix = removePrefix; + function tryRemovePrefix(str, prefix, getCanonicalFileName) { + if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; } + return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; + } + ts.tryRemovePrefix = tryRemovePrefix; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function and(f, g) { + return function (arg) { return f(arg) && g(arg); }; + } + ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; + function assertTypeIsNever(_) { } // tslint:disable-line no-empty + ts.assertTypeIsNever = assertTypeIsNever; + function singleElementArray(t) { + return t === undefined ? undefined : [t]; + } + ts.singleElementArray = singleElementArray; + function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { + unchanged = unchanged || noop; + 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 = comparer(newItem, oldItem); + if (compareResult === -1 /* LessThan */) { + inserted(newItem); + newIndex++; + } + else if (compareResult === 1 /* GreaterThan */) { + deleted(oldItem); + oldIndex++; + } + else { + unchanged(oldItem, newItem); + newIndex++; + oldIndex++; + } + } + while (newIndex < newLen) { + inserted(newItems[newIndex++]); + } + while (oldIndex < oldLen) { + deleted(oldItems[oldIndex++]); + } + } + ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + /** Gets a timestamp with (at least) ms resolution */ + ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; +})(ts || (ts = {})); +/*@internal*/ +/** Performance measurements for the compiler. */ +(function (ts) { + var performance; + (function (performance) { + // NOTE: cannot use ts.noop as core.ts loads after this + var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; + var enabled = false; + var profilerStart = 0; + var counts; + var marks; + var measures; + /** + * Marks a performance event. + * + * @param markName The name of the mark. + */ + function mark(markName) { + if (enabled) { + marks.set(markName, ts.timestamp()); + counts.set(markName, (counts.get(markName) || 0) + 1); + profilerEvent(markName); + } + } + performance.mark = mark; + /** + * Adds a performance measurement with the specified name. + * + * @param measureName The name of the performance measurement. + * @param startMarkName The name of the starting mark. If not supplied, the point at which the + * profiler was enabled is used. + * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is + * used. + */ + function measure(measureName, startMarkName, endMarkName) { + if (enabled) { + var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); + var start = startMarkName && marks.get(startMarkName) || profilerStart; + measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); + } + } + performance.measure = measure; + /** + * Gets the number of times a marker was encountered. + * + * @param markName The name of the mark. + */ + function getCount(markName) { + return counts && counts.get(markName) || 0; + } + performance.getCount = getCount; + /** + * Gets the total duration of all measurements with the supplied name. + * + * @param measureName The name of the measure whose durations should be accumulated. + */ + function getDuration(measureName) { + return measures && measures.get(measureName) || 0; + } + performance.getDuration = getDuration; + /** + * Iterate over each measure, performing some action + * + * @param cb The action to perform for each measure + */ + function forEachMeasure(cb) { + measures.forEach(function (measure, key) { + cb(key, measure); + }); + } + performance.forEachMeasure = forEachMeasure; + /** Enables (and resets) performance measurements for the compiler. */ + function enable() { + counts = ts.createMap(); + marks = ts.createMap(); + measures = ts.createMap(); + enabled = true; + profilerStart = ts.timestamp(); + } + performance.enable = enable; + /** Disables performance measurements for the compiler. */ + function disable() { + enabled = false; + } + performance.disable = disable; + })(performance = ts.performance || (ts.performance = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + // token > SyntaxKind.Identifier => token is a keyword // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync var SyntaxKind; (function (SyntaxKind) { @@ -198,185 +2188,195 @@ var ts; SyntaxKind[SyntaxKind["TypeKeyword"] = 139] = "TypeKeyword"; SyntaxKind[SyntaxKind["UndefinedKeyword"] = 140] = "UndefinedKeyword"; SyntaxKind[SyntaxKind["UniqueKeyword"] = 141] = "UniqueKeyword"; - SyntaxKind[SyntaxKind["FromKeyword"] = 142] = "FromKeyword"; - SyntaxKind[SyntaxKind["GlobalKeyword"] = 143] = "GlobalKeyword"; - SyntaxKind[SyntaxKind["OfKeyword"] = 144] = "OfKeyword"; + SyntaxKind[SyntaxKind["UnknownKeyword"] = 142] = "UnknownKeyword"; + SyntaxKind[SyntaxKind["FromKeyword"] = 143] = "FromKeyword"; + SyntaxKind[SyntaxKind["GlobalKeyword"] = 144] = "GlobalKeyword"; + SyntaxKind[SyntaxKind["OfKeyword"] = 145] = "OfKeyword"; // Parse tree nodes // Names - SyntaxKind[SyntaxKind["QualifiedName"] = 145] = "QualifiedName"; - SyntaxKind[SyntaxKind["ComputedPropertyName"] = 146] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["QualifiedName"] = 146] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 147] = "ComputedPropertyName"; // Signature elements - SyntaxKind[SyntaxKind["TypeParameter"] = 147] = "TypeParameter"; - SyntaxKind[SyntaxKind["Parameter"] = 148] = "Parameter"; - SyntaxKind[SyntaxKind["Decorator"] = 149] = "Decorator"; + SyntaxKind[SyntaxKind["TypeParameter"] = 148] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 149] = "Parameter"; + SyntaxKind[SyntaxKind["Decorator"] = 150] = "Decorator"; // TypeMember - SyntaxKind[SyntaxKind["PropertySignature"] = 150] = "PropertySignature"; - SyntaxKind[SyntaxKind["PropertyDeclaration"] = 151] = "PropertyDeclaration"; - SyntaxKind[SyntaxKind["MethodSignature"] = 152] = "MethodSignature"; - SyntaxKind[SyntaxKind["MethodDeclaration"] = 153] = "MethodDeclaration"; - SyntaxKind[SyntaxKind["Constructor"] = 154] = "Constructor"; - SyntaxKind[SyntaxKind["GetAccessor"] = 155] = "GetAccessor"; - SyntaxKind[SyntaxKind["SetAccessor"] = 156] = "SetAccessor"; - SyntaxKind[SyntaxKind["CallSignature"] = 157] = "CallSignature"; - SyntaxKind[SyntaxKind["ConstructSignature"] = 158] = "ConstructSignature"; - SyntaxKind[SyntaxKind["IndexSignature"] = 159] = "IndexSignature"; + SyntaxKind[SyntaxKind["PropertySignature"] = 151] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 152] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 153] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 154] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 155] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 156] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 157] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 158] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 159] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 160] = "IndexSignature"; // Type - SyntaxKind[SyntaxKind["TypePredicate"] = 160] = "TypePredicate"; - SyntaxKind[SyntaxKind["TypeReference"] = 161] = "TypeReference"; - SyntaxKind[SyntaxKind["FunctionType"] = 162] = "FunctionType"; - SyntaxKind[SyntaxKind["ConstructorType"] = 163] = "ConstructorType"; - SyntaxKind[SyntaxKind["TypeQuery"] = 164] = "TypeQuery"; - SyntaxKind[SyntaxKind["TypeLiteral"] = 165] = "TypeLiteral"; - SyntaxKind[SyntaxKind["ArrayType"] = 166] = "ArrayType"; - SyntaxKind[SyntaxKind["TupleType"] = 167] = "TupleType"; - SyntaxKind[SyntaxKind["UnionType"] = 168] = "UnionType"; - SyntaxKind[SyntaxKind["IntersectionType"] = 169] = "IntersectionType"; - SyntaxKind[SyntaxKind["ConditionalType"] = 170] = "ConditionalType"; - SyntaxKind[SyntaxKind["InferType"] = 171] = "InferType"; - SyntaxKind[SyntaxKind["ParenthesizedType"] = 172] = "ParenthesizedType"; - SyntaxKind[SyntaxKind["ThisType"] = 173] = "ThisType"; - SyntaxKind[SyntaxKind["TypeOperator"] = 174] = "TypeOperator"; - SyntaxKind[SyntaxKind["IndexedAccessType"] = 175] = "IndexedAccessType"; - SyntaxKind[SyntaxKind["MappedType"] = 176] = "MappedType"; - SyntaxKind[SyntaxKind["LiteralType"] = 177] = "LiteralType"; + SyntaxKind[SyntaxKind["TypePredicate"] = 161] = "TypePredicate"; + SyntaxKind[SyntaxKind["TypeReference"] = 162] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 163] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 164] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 165] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 166] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 167] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 168] = "TupleType"; + SyntaxKind[SyntaxKind["OptionalType"] = 169] = "OptionalType"; + SyntaxKind[SyntaxKind["RestType"] = 170] = "RestType"; + SyntaxKind[SyntaxKind["UnionType"] = 171] = "UnionType"; + SyntaxKind[SyntaxKind["IntersectionType"] = 172] = "IntersectionType"; + SyntaxKind[SyntaxKind["ConditionalType"] = 173] = "ConditionalType"; + SyntaxKind[SyntaxKind["InferType"] = 174] = "InferType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 175] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ThisType"] = 176] = "ThisType"; + SyntaxKind[SyntaxKind["TypeOperator"] = 177] = "TypeOperator"; + SyntaxKind[SyntaxKind["IndexedAccessType"] = 178] = "IndexedAccessType"; + SyntaxKind[SyntaxKind["MappedType"] = 179] = "MappedType"; + SyntaxKind[SyntaxKind["LiteralType"] = 180] = "LiteralType"; + SyntaxKind[SyntaxKind["ImportType"] = 181] = "ImportType"; // Binding patterns - SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 178] = "ObjectBindingPattern"; - SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 179] = "ArrayBindingPattern"; - SyntaxKind[SyntaxKind["BindingElement"] = 180] = "BindingElement"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 182] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 183] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 184] = "BindingElement"; // Expression - SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 181] = "ArrayLiteralExpression"; - SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 182] = "ObjectLiteralExpression"; - SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 183] = "PropertyAccessExpression"; - SyntaxKind[SyntaxKind["ElementAccessExpression"] = 184] = "ElementAccessExpression"; - SyntaxKind[SyntaxKind["CallExpression"] = 185] = "CallExpression"; - SyntaxKind[SyntaxKind["NewExpression"] = 186] = "NewExpression"; - SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 187] = "TaggedTemplateExpression"; - SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 188] = "TypeAssertionExpression"; - SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 189] = "ParenthesizedExpression"; - SyntaxKind[SyntaxKind["FunctionExpression"] = 190] = "FunctionExpression"; - SyntaxKind[SyntaxKind["ArrowFunction"] = 191] = "ArrowFunction"; - SyntaxKind[SyntaxKind["DeleteExpression"] = 192] = "DeleteExpression"; - SyntaxKind[SyntaxKind["TypeOfExpression"] = 193] = "TypeOfExpression"; - SyntaxKind[SyntaxKind["VoidExpression"] = 194] = "VoidExpression"; - SyntaxKind[SyntaxKind["AwaitExpression"] = 195] = "AwaitExpression"; - SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 196] = "PrefixUnaryExpression"; - SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 197] = "PostfixUnaryExpression"; - SyntaxKind[SyntaxKind["BinaryExpression"] = 198] = "BinaryExpression"; - SyntaxKind[SyntaxKind["ConditionalExpression"] = 199] = "ConditionalExpression"; - SyntaxKind[SyntaxKind["TemplateExpression"] = 200] = "TemplateExpression"; - SyntaxKind[SyntaxKind["YieldExpression"] = 201] = "YieldExpression"; - SyntaxKind[SyntaxKind["SpreadElement"] = 202] = "SpreadElement"; - SyntaxKind[SyntaxKind["ClassExpression"] = 203] = "ClassExpression"; - SyntaxKind[SyntaxKind["OmittedExpression"] = 204] = "OmittedExpression"; - SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 205] = "ExpressionWithTypeArguments"; - SyntaxKind[SyntaxKind["AsExpression"] = 206] = "AsExpression"; - SyntaxKind[SyntaxKind["NonNullExpression"] = 207] = "NonNullExpression"; - SyntaxKind[SyntaxKind["MetaProperty"] = 208] = "MetaProperty"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 185] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 186] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 187] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 188] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 189] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 190] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 191] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 192] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 193] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 194] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 195] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 196] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 197] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 198] = "VoidExpression"; + SyntaxKind[SyntaxKind["AwaitExpression"] = 199] = "AwaitExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 200] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 201] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 202] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 203] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 204] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 205] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElement"] = 206] = "SpreadElement"; + SyntaxKind[SyntaxKind["ClassExpression"] = 207] = "ClassExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 208] = "OmittedExpression"; + SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 209] = "ExpressionWithTypeArguments"; + SyntaxKind[SyntaxKind["AsExpression"] = 210] = "AsExpression"; + SyntaxKind[SyntaxKind["NonNullExpression"] = 211] = "NonNullExpression"; + SyntaxKind[SyntaxKind["MetaProperty"] = 212] = "MetaProperty"; + SyntaxKind[SyntaxKind["SyntheticExpression"] = 213] = "SyntheticExpression"; // Misc - SyntaxKind[SyntaxKind["TemplateSpan"] = 209] = "TemplateSpan"; - SyntaxKind[SyntaxKind["SemicolonClassElement"] = 210] = "SemicolonClassElement"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 214] = "TemplateSpan"; + SyntaxKind[SyntaxKind["SemicolonClassElement"] = 215] = "SemicolonClassElement"; // Element - SyntaxKind[SyntaxKind["Block"] = 211] = "Block"; - SyntaxKind[SyntaxKind["VariableStatement"] = 212] = "VariableStatement"; - SyntaxKind[SyntaxKind["EmptyStatement"] = 213] = "EmptyStatement"; - SyntaxKind[SyntaxKind["ExpressionStatement"] = 214] = "ExpressionStatement"; - SyntaxKind[SyntaxKind["IfStatement"] = 215] = "IfStatement"; - SyntaxKind[SyntaxKind["DoStatement"] = 216] = "DoStatement"; - SyntaxKind[SyntaxKind["WhileStatement"] = 217] = "WhileStatement"; - SyntaxKind[SyntaxKind["ForStatement"] = 218] = "ForStatement"; - SyntaxKind[SyntaxKind["ForInStatement"] = 219] = "ForInStatement"; - SyntaxKind[SyntaxKind["ForOfStatement"] = 220] = "ForOfStatement"; - SyntaxKind[SyntaxKind["ContinueStatement"] = 221] = "ContinueStatement"; - SyntaxKind[SyntaxKind["BreakStatement"] = 222] = "BreakStatement"; - SyntaxKind[SyntaxKind["ReturnStatement"] = 223] = "ReturnStatement"; - SyntaxKind[SyntaxKind["WithStatement"] = 224] = "WithStatement"; - SyntaxKind[SyntaxKind["SwitchStatement"] = 225] = "SwitchStatement"; - SyntaxKind[SyntaxKind["LabeledStatement"] = 226] = "LabeledStatement"; - SyntaxKind[SyntaxKind["ThrowStatement"] = 227] = "ThrowStatement"; - SyntaxKind[SyntaxKind["TryStatement"] = 228] = "TryStatement"; - SyntaxKind[SyntaxKind["DebuggerStatement"] = 229] = "DebuggerStatement"; - SyntaxKind[SyntaxKind["VariableDeclaration"] = 230] = "VariableDeclaration"; - SyntaxKind[SyntaxKind["VariableDeclarationList"] = 231] = "VariableDeclarationList"; - SyntaxKind[SyntaxKind["FunctionDeclaration"] = 232] = "FunctionDeclaration"; - SyntaxKind[SyntaxKind["ClassDeclaration"] = 233] = "ClassDeclaration"; - SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 234] = "InterfaceDeclaration"; - SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 235] = "TypeAliasDeclaration"; - SyntaxKind[SyntaxKind["EnumDeclaration"] = 236] = "EnumDeclaration"; - SyntaxKind[SyntaxKind["ModuleDeclaration"] = 237] = "ModuleDeclaration"; - SyntaxKind[SyntaxKind["ModuleBlock"] = 238] = "ModuleBlock"; - SyntaxKind[SyntaxKind["CaseBlock"] = 239] = "CaseBlock"; - SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 240] = "NamespaceExportDeclaration"; - SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 241] = "ImportEqualsDeclaration"; - SyntaxKind[SyntaxKind["ImportDeclaration"] = 242] = "ImportDeclaration"; - SyntaxKind[SyntaxKind["ImportClause"] = 243] = "ImportClause"; - SyntaxKind[SyntaxKind["NamespaceImport"] = 244] = "NamespaceImport"; - SyntaxKind[SyntaxKind["NamedImports"] = 245] = "NamedImports"; - SyntaxKind[SyntaxKind["ImportSpecifier"] = 246] = "ImportSpecifier"; - SyntaxKind[SyntaxKind["ExportAssignment"] = 247] = "ExportAssignment"; - SyntaxKind[SyntaxKind["ExportDeclaration"] = 248] = "ExportDeclaration"; - SyntaxKind[SyntaxKind["NamedExports"] = 249] = "NamedExports"; - SyntaxKind[SyntaxKind["ExportSpecifier"] = 250] = "ExportSpecifier"; - SyntaxKind[SyntaxKind["MissingDeclaration"] = 251] = "MissingDeclaration"; + SyntaxKind[SyntaxKind["Block"] = 216] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 217] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 218] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 219] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 220] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 221] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 222] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 223] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 224] = "ForInStatement"; + SyntaxKind[SyntaxKind["ForOfStatement"] = 225] = "ForOfStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 226] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 227] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 228] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 229] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 230] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 231] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 232] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 233] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 234] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 235] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 236] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 237] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 238] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 239] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 240] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 241] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 242] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 243] = "ModuleBlock"; + SyntaxKind[SyntaxKind["CaseBlock"] = 244] = "CaseBlock"; + SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 245] = "NamespaceExportDeclaration"; + SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 246] = "ImportEqualsDeclaration"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 247] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ImportClause"] = 248] = "ImportClause"; + SyntaxKind[SyntaxKind["NamespaceImport"] = 249] = "NamespaceImport"; + SyntaxKind[SyntaxKind["NamedImports"] = 250] = "NamedImports"; + SyntaxKind[SyntaxKind["ImportSpecifier"] = 251] = "ImportSpecifier"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 252] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExportDeclaration"] = 253] = "ExportDeclaration"; + SyntaxKind[SyntaxKind["NamedExports"] = 254] = "NamedExports"; + SyntaxKind[SyntaxKind["ExportSpecifier"] = 255] = "ExportSpecifier"; + SyntaxKind[SyntaxKind["MissingDeclaration"] = 256] = "MissingDeclaration"; // Module references - SyntaxKind[SyntaxKind["ExternalModuleReference"] = 252] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 257] = "ExternalModuleReference"; // JSX - SyntaxKind[SyntaxKind["JsxElement"] = 253] = "JsxElement"; - SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 254] = "JsxSelfClosingElement"; - SyntaxKind[SyntaxKind["JsxOpeningElement"] = 255] = "JsxOpeningElement"; - SyntaxKind[SyntaxKind["JsxClosingElement"] = 256] = "JsxClosingElement"; - SyntaxKind[SyntaxKind["JsxFragment"] = 257] = "JsxFragment"; - SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 258] = "JsxOpeningFragment"; - SyntaxKind[SyntaxKind["JsxClosingFragment"] = 259] = "JsxClosingFragment"; - SyntaxKind[SyntaxKind["JsxAttribute"] = 260] = "JsxAttribute"; - SyntaxKind[SyntaxKind["JsxAttributes"] = 261] = "JsxAttributes"; - SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 262] = "JsxSpreadAttribute"; - SyntaxKind[SyntaxKind["JsxExpression"] = 263] = "JsxExpression"; + SyntaxKind[SyntaxKind["JsxElement"] = 258] = "JsxElement"; + SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 259] = "JsxSelfClosingElement"; + SyntaxKind[SyntaxKind["JsxOpeningElement"] = 260] = "JsxOpeningElement"; + SyntaxKind[SyntaxKind["JsxClosingElement"] = 261] = "JsxClosingElement"; + SyntaxKind[SyntaxKind["JsxFragment"] = 262] = "JsxFragment"; + SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 263] = "JsxOpeningFragment"; + SyntaxKind[SyntaxKind["JsxClosingFragment"] = 264] = "JsxClosingFragment"; + SyntaxKind[SyntaxKind["JsxAttribute"] = 265] = "JsxAttribute"; + SyntaxKind[SyntaxKind["JsxAttributes"] = 266] = "JsxAttributes"; + SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 267] = "JsxSpreadAttribute"; + SyntaxKind[SyntaxKind["JsxExpression"] = 268] = "JsxExpression"; // Clauses - SyntaxKind[SyntaxKind["CaseClause"] = 264] = "CaseClause"; - SyntaxKind[SyntaxKind["DefaultClause"] = 265] = "DefaultClause"; - SyntaxKind[SyntaxKind["HeritageClause"] = 266] = "HeritageClause"; - SyntaxKind[SyntaxKind["CatchClause"] = 267] = "CatchClause"; + SyntaxKind[SyntaxKind["CaseClause"] = 269] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 270] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 271] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 272] = "CatchClause"; // Property assignments - SyntaxKind[SyntaxKind["PropertyAssignment"] = 268] = "PropertyAssignment"; - SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 269] = "ShorthandPropertyAssignment"; - SyntaxKind[SyntaxKind["SpreadAssignment"] = 270] = "SpreadAssignment"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 273] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 274] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["SpreadAssignment"] = 275] = "SpreadAssignment"; // Enum - SyntaxKind[SyntaxKind["EnumMember"] = 271] = "EnumMember"; + SyntaxKind[SyntaxKind["EnumMember"] = 276] = "EnumMember"; // Top-level nodes - SyntaxKind[SyntaxKind["SourceFile"] = 272] = "SourceFile"; - SyntaxKind[SyntaxKind["Bundle"] = 273] = "Bundle"; + SyntaxKind[SyntaxKind["SourceFile"] = 277] = "SourceFile"; + SyntaxKind[SyntaxKind["Bundle"] = 278] = "Bundle"; + SyntaxKind[SyntaxKind["UnparsedSource"] = 279] = "UnparsedSource"; + SyntaxKind[SyntaxKind["InputFiles"] = 280] = "InputFiles"; // JSDoc nodes - SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 274] = "JSDocTypeExpression"; + SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 281] = "JSDocTypeExpression"; // The * type - SyntaxKind[SyntaxKind["JSDocAllType"] = 275] = "JSDocAllType"; + SyntaxKind[SyntaxKind["JSDocAllType"] = 282] = "JSDocAllType"; // The ? type - SyntaxKind[SyntaxKind["JSDocUnknownType"] = 276] = "JSDocUnknownType"; - SyntaxKind[SyntaxKind["JSDocNullableType"] = 277] = "JSDocNullableType"; - SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 278] = "JSDocNonNullableType"; - SyntaxKind[SyntaxKind["JSDocOptionalType"] = 279] = "JSDocOptionalType"; - SyntaxKind[SyntaxKind["JSDocFunctionType"] = 280] = "JSDocFunctionType"; - SyntaxKind[SyntaxKind["JSDocVariadicType"] = 281] = "JSDocVariadicType"; - SyntaxKind[SyntaxKind["JSDocComment"] = 282] = "JSDocComment"; - SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 283] = "JSDocTypeLiteral"; - SyntaxKind[SyntaxKind["JSDocTag"] = 284] = "JSDocTag"; - SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 285] = "JSDocAugmentsTag"; - SyntaxKind[SyntaxKind["JSDocClassTag"] = 286] = "JSDocClassTag"; - SyntaxKind[SyntaxKind["JSDocParameterTag"] = 287] = "JSDocParameterTag"; - SyntaxKind[SyntaxKind["JSDocReturnTag"] = 288] = "JSDocReturnTag"; - SyntaxKind[SyntaxKind["JSDocTypeTag"] = 289] = "JSDocTypeTag"; - SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 290] = "JSDocTemplateTag"; - SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 291] = "JSDocTypedefTag"; - SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 292] = "JSDocPropertyTag"; + SyntaxKind[SyntaxKind["JSDocUnknownType"] = 283] = "JSDocUnknownType"; + SyntaxKind[SyntaxKind["JSDocNullableType"] = 284] = "JSDocNullableType"; + SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 285] = "JSDocNonNullableType"; + SyntaxKind[SyntaxKind["JSDocOptionalType"] = 286] = "JSDocOptionalType"; + SyntaxKind[SyntaxKind["JSDocFunctionType"] = 287] = "JSDocFunctionType"; + SyntaxKind[SyntaxKind["JSDocVariadicType"] = 288] = "JSDocVariadicType"; + SyntaxKind[SyntaxKind["JSDocComment"] = 289] = "JSDocComment"; + SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 290] = "JSDocTypeLiteral"; + SyntaxKind[SyntaxKind["JSDocSignature"] = 291] = "JSDocSignature"; + SyntaxKind[SyntaxKind["JSDocTag"] = 292] = "JSDocTag"; + SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 293] = "JSDocAugmentsTag"; + SyntaxKind[SyntaxKind["JSDocClassTag"] = 294] = "JSDocClassTag"; + SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 295] = "JSDocCallbackTag"; + SyntaxKind[SyntaxKind["JSDocParameterTag"] = 296] = "JSDocParameterTag"; + SyntaxKind[SyntaxKind["JSDocReturnTag"] = 297] = "JSDocReturnTag"; + SyntaxKind[SyntaxKind["JSDocThisTag"] = 298] = "JSDocThisTag"; + SyntaxKind[SyntaxKind["JSDocTypeTag"] = 299] = "JSDocTypeTag"; + SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 300] = "JSDocTemplateTag"; + SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 301] = "JSDocTypedefTag"; + SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 302] = "JSDocPropertyTag"; // Synthesized list - SyntaxKind[SyntaxKind["SyntaxList"] = 293] = "SyntaxList"; + SyntaxKind[SyntaxKind["SyntaxList"] = 303] = "SyntaxList"; // Transformation nodes - SyntaxKind[SyntaxKind["NotEmittedStatement"] = 294] = "NotEmittedStatement"; - SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 295] = "PartiallyEmittedExpression"; - SyntaxKind[SyntaxKind["CommaListExpression"] = 296] = "CommaListExpression"; - SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 297] = "MergeDeclarationMarker"; - SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 298] = "EndOfDeclarationMarker"; + SyntaxKind[SyntaxKind["NotEmittedStatement"] = 304] = "NotEmittedStatement"; + SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 305] = "PartiallyEmittedExpression"; + SyntaxKind[SyntaxKind["CommaListExpression"] = 306] = "CommaListExpression"; + SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 307] = "MergeDeclarationMarker"; + SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 308] = "EndOfDeclarationMarker"; // Enum value count - SyntaxKind[SyntaxKind["Count"] = 299] = "Count"; + SyntaxKind[SyntaxKind["Count"] = 309] = "Count"; // Markers SyntaxKind[SyntaxKind["FirstAssignment"] = 58] = "FirstAssignment"; SyntaxKind[SyntaxKind["LastAssignment"] = 70] = "LastAssignment"; @@ -385,15 +2385,15 @@ var ts; SyntaxKind[SyntaxKind["FirstReservedWord"] = 72] = "FirstReservedWord"; SyntaxKind[SyntaxKind["LastReservedWord"] = 107] = "LastReservedWord"; SyntaxKind[SyntaxKind["FirstKeyword"] = 72] = "FirstKeyword"; - SyntaxKind[SyntaxKind["LastKeyword"] = 144] = "LastKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 145] = "LastKeyword"; SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 108] = "FirstFutureReservedWord"; SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 116] = "LastFutureReservedWord"; - SyntaxKind[SyntaxKind["FirstTypeNode"] = 160] = "FirstTypeNode"; - SyntaxKind[SyntaxKind["LastTypeNode"] = 177] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 161] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 181] = "LastTypeNode"; SyntaxKind[SyntaxKind["FirstPunctuation"] = 17] = "FirstPunctuation"; SyntaxKind[SyntaxKind["LastPunctuation"] = 70] = "LastPunctuation"; SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; - SyntaxKind[SyntaxKind["LastToken"] = 144] = "LastToken"; + SyntaxKind[SyntaxKind["LastToken"] = 145] = "LastToken"; SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken"; SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken"; @@ -402,13 +2402,13 @@ var ts; SyntaxKind[SyntaxKind["LastTemplateToken"] = 16] = "LastTemplateToken"; SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 27] = "FirstBinaryOperator"; SyntaxKind[SyntaxKind["LastBinaryOperator"] = 70] = "LastBinaryOperator"; - SyntaxKind[SyntaxKind["FirstNode"] = 145] = "FirstNode"; - SyntaxKind[SyntaxKind["FirstJSDocNode"] = 274] = "FirstJSDocNode"; - SyntaxKind[SyntaxKind["LastJSDocNode"] = 292] = "LastJSDocNode"; - SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 284] = "FirstJSDocTagNode"; - SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 292] = "LastJSDocTagNode"; + SyntaxKind[SyntaxKind["FirstNode"] = 146] = "FirstNode"; + SyntaxKind[SyntaxKind["FirstJSDocNode"] = 281] = "FirstJSDocNode"; + SyntaxKind[SyntaxKind["LastJSDocNode"] = 302] = "LastJSDocNode"; + SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 292] = "FirstJSDocTagNode"; + SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 302] = "LastJSDocTagNode"; /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 117] = "FirstContextualKeyword"; - /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 144] = "LastContextualKeyword"; + /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 145] = "LastContextualKeyword"; })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {})); var NodeFlags; (function (NodeFlags) { @@ -432,26 +2432,32 @@ var ts; NodeFlags[NodeFlags["JavaScriptFile"] = 65536] = "JavaScriptFile"; NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 131072] = "ThisNodeOrAnySubNodesHasError"; NodeFlags[NodeFlags["HasAggregatedChildData"] = 262144] = "HasAggregatedChildData"; - // This flag will be set when the parser encounters a dynamic import expression so that module resolution - // will not have to walk the tree if the flag is not set. However, this flag is just a approximation because - // once it is set, the flag never gets cleared (hence why it's named "PossiblyContainsDynamicImport"). - // During editing, if dynamic import is removed, incremental parsing will *NOT* update this flag. This means that the tree will always be traversed - // during module resolution. However, the removal operation should not occur often and in the case of the + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation + // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared. + // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag. + // This means that the tree will always be traversed during module resolution, or when looking for external module indicators. + // However, the removal operation should not occur often and in the case of the // removal, it is likely that users will add the import anyway. // The advantage of this approach is its simplicity. For the case of batch compilation, // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. - /* @internal */ - NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; - NodeFlags[NodeFlags["JSDoc"] = 1048576] = "JSDoc"; - /* @internal */ NodeFlags[NodeFlags["Ambient"] = 2097152] = "Ambient"; - /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 4194304] = "InWithStatement"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 524288] = "PossiblyContainsDynamicImport"; + /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 1048576] = "PossiblyContainsImportMeta"; + NodeFlags[NodeFlags["JSDoc"] = 2097152] = "JSDoc"; + /* @internal */ NodeFlags[NodeFlags["Ambient"] = 4194304] = "Ambient"; + /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 8388608] = "InWithStatement"; + NodeFlags[NodeFlags["JsonFile"] = 16777216] = "JsonFile"; NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped"; NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 384] = "ReachabilityCheckFlags"; NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 1408] = "ReachabilityAndEmitFlags"; // Parsing context flags - NodeFlags[NodeFlags["ContextFlags"] = 6387712] = "ContextFlags"; + NodeFlags[NodeFlags["ContextFlags"] = 12679168] = "ContextFlags"; // Exclude these flags when parsing a Type NodeFlags[NodeFlags["TypeExcludesFlags"] = 20480] = "TypeExcludesFlags"; + // Represents all flags that are potentially set once and + // never cleared on SourceFiles which get re-used in between incremental parses. + // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. + /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 1572864] = "PermanentlySetIncrementalFlags"; })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {})); var ModifierFlags; (function (ModifierFlags) { @@ -474,6 +2480,7 @@ var ts; ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier"; ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier"; ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault"; + ModifierFlags[ModifierFlags["All"] = 3071] = "All"; })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {})); var JsxFlags; (function (JsxFlags) { @@ -502,8 +2509,9 @@ var ts; GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node"; GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask"; // Flags - GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; - GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel"; })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; @@ -572,15 +2580,16 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams"; NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; - // empty space + NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences"; NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing"; @@ -758,8 +2767,6 @@ var ts; 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"; @@ -791,6 +2798,8 @@ var ts; CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; CheckFlags[CheckFlags["Late"] = 1024] = "Late"; CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; @@ -840,74 +2849,93 @@ var ts; 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["UniqueESSymbol"] = 1024] = "UniqueESSymbol"; - TypeFlags[TypeFlags["Void"] = 2048] = "Void"; - TypeFlags[TypeFlags["Undefined"] = 4096] = "Undefined"; - TypeFlags[TypeFlags["Null"] = 8192] = "Null"; - TypeFlags[TypeFlags["Never"] = 16384] = "Never"; - TypeFlags[TypeFlags["TypeParameter"] = 32768] = "TypeParameter"; - TypeFlags[TypeFlags["Object"] = 65536] = "Object"; - TypeFlags[TypeFlags["Union"] = 131072] = "Union"; - TypeFlags[TypeFlags["Intersection"] = 262144] = "Intersection"; - TypeFlags[TypeFlags["Index"] = 524288] = "Index"; - TypeFlags[TypeFlags["IndexedAccess"] = 1048576] = "IndexedAccess"; - TypeFlags[TypeFlags["Conditional"] = 2097152] = "Conditional"; - TypeFlags[TypeFlags["Substitution"] = 4194304] = "Substitution"; + TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown"; + TypeFlags[TypeFlags["String"] = 4] = "String"; + TypeFlags[TypeFlags["Number"] = 8] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean"; + TypeFlags[TypeFlags["Enum"] = 32] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 64] = "StringLiteral"; + TypeFlags[TypeFlags["NumberLiteral"] = 128] = "NumberLiteral"; + TypeFlags[TypeFlags["BooleanLiteral"] = 256] = "BooleanLiteral"; + TypeFlags[TypeFlags["EnumLiteral"] = 512] = "EnumLiteral"; + TypeFlags[TypeFlags["ESSymbol"] = 1024] = "ESSymbol"; + TypeFlags[TypeFlags["UniqueESSymbol"] = 2048] = "UniqueESSymbol"; + TypeFlags[TypeFlags["Void"] = 4096] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 8192] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 16384] = "Null"; + TypeFlags[TypeFlags["Never"] = 32768] = "Never"; + TypeFlags[TypeFlags["TypeParameter"] = 65536] = "TypeParameter"; + TypeFlags[TypeFlags["Object"] = 131072] = "Object"; + TypeFlags[TypeFlags["Union"] = 262144] = "Union"; + TypeFlags[TypeFlags["Intersection"] = 524288] = "Intersection"; + TypeFlags[TypeFlags["Index"] = 1048576] = "Index"; + TypeFlags[TypeFlags["IndexedAccess"] = 2097152] = "IndexedAccess"; + TypeFlags[TypeFlags["Conditional"] = 4194304] = "Conditional"; + TypeFlags[TypeFlags["Substitution"] = 8388608] = "Substitution"; + TypeFlags[TypeFlags["NonPrimitive"] = 16777216] = "NonPrimitive"; /* @internal */ - TypeFlags[TypeFlags["FreshLiteral"] = 8388608] = "FreshLiteral"; + TypeFlags[TypeFlags["FreshLiteral"] = 33554432] = "FreshLiteral"; /* @internal */ - TypeFlags[TypeFlags["ContainsWideningType"] = 16777216] = "ContainsWideningType"; + TypeFlags[TypeFlags["UnionOfUnitTypes"] = 67108864] = "UnionOfUnitTypes"; /* @internal */ - TypeFlags[TypeFlags["ContainsObjectLiteral"] = 33554432] = "ContainsObjectLiteral"; + TypeFlags[TypeFlags["ContainsWideningType"] = 134217728] = "ContainsWideningType"; /* @internal */ - TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 67108864] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["NonPrimitive"] = 134217728] = "NonPrimitive"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 268435456] = "ContainsObjectLiteral"; /* @internal */ - TypeFlags[TypeFlags["GenericMappedType"] = 536870912] = "GenericMappedType"; + TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 536870912] = "ContainsAnyFunctionType"; /* @internal */ - TypeFlags[TypeFlags["Nullable"] = 12288] = "Nullable"; - TypeFlags[TypeFlags["Literal"] = 224] = "Literal"; - TypeFlags[TypeFlags["Unit"] = 13536] = "Unit"; - TypeFlags[TypeFlags["StringOrNumberLiteral"] = 96] = "StringOrNumberLiteral"; + TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown"; /* @internal */ - TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 1120] = "StringOrNumberLiteralOrUnique"; + TypeFlags[TypeFlags["Nullable"] = 24576] = "Nullable"; + TypeFlags[TypeFlags["Literal"] = 448] = "Literal"; + TypeFlags[TypeFlags["Unit"] = 27072] = "Unit"; + TypeFlags[TypeFlags["StringOrNumberLiteral"] = 192] = "StringOrNumberLiteral"; /* @internal */ - TypeFlags[TypeFlags["DefinitelyFalsy"] = 14560] = "DefinitelyFalsy"; - TypeFlags[TypeFlags["PossiblyFalsy"] = 14574] = "PossiblyFalsy"; + TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 2240] = "StringOrNumberLiteralOrUnique"; /* @internal */ - TypeFlags[TypeFlags["Intrinsic"] = 134249103] = "Intrinsic"; + TypeFlags[TypeFlags["DefinitelyFalsy"] = 29120] = "DefinitelyFalsy"; + TypeFlags[TypeFlags["PossiblyFalsy"] = 29148] = "PossiblyFalsy"; /* @internal */ - TypeFlags[TypeFlags["Primitive"] = 16382] = "Primitive"; - TypeFlags[TypeFlags["StringLike"] = 524322] = "StringLike"; - TypeFlags[TypeFlags["NumberLike"] = 84] = "NumberLike"; - TypeFlags[TypeFlags["BooleanLike"] = 136] = "BooleanLike"; - TypeFlags[TypeFlags["EnumLike"] = 272] = "EnumLike"; - TypeFlags[TypeFlags["ESSymbolLike"] = 1536] = "ESSymbolLike"; - TypeFlags[TypeFlags["UnionOrIntersection"] = 393216] = "UnionOrIntersection"; - TypeFlags[TypeFlags["StructuredType"] = 458752] = "StructuredType"; - TypeFlags[TypeFlags["TypeVariable"] = 1081344] = "TypeVariable"; - TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 7372800] = "InstantiableNonPrimitive"; - TypeFlags[TypeFlags["InstantiablePrimitive"] = 524288] = "InstantiablePrimitive"; - TypeFlags[TypeFlags["Instantiable"] = 7897088] = "Instantiable"; - TypeFlags[TypeFlags["StructuredOrInstantiable"] = 8355840] = "StructuredOrInstantiable"; + TypeFlags[TypeFlags["Intrinsic"] = 16839967] = "Intrinsic"; + /* @internal */ + TypeFlags[TypeFlags["Primitive"] = 32764] = "Primitive"; + TypeFlags[TypeFlags["StringLike"] = 68] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 168] = "NumberLike"; + TypeFlags[TypeFlags["BooleanLike"] = 272] = "BooleanLike"; + TypeFlags[TypeFlags["EnumLike"] = 544] = "EnumLike"; + TypeFlags[TypeFlags["ESSymbolLike"] = 3072] = "ESSymbolLike"; + TypeFlags[TypeFlags["VoidLike"] = 12288] = "VoidLike"; + /* @internal */ + TypeFlags[TypeFlags["DisjointDomains"] = 16809468] = "DisjointDomains"; + TypeFlags[TypeFlags["UnionOrIntersection"] = 786432] = "UnionOrIntersection"; + TypeFlags[TypeFlags["StructuredType"] = 917504] = "StructuredType"; + TypeFlags[TypeFlags["TypeVariable"] = 2162688] = "TypeVariable"; + TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 14745600] = "InstantiableNonPrimitive"; + TypeFlags[TypeFlags["InstantiablePrimitive"] = 1048576] = "InstantiablePrimitive"; + TypeFlags[TypeFlags["Instantiable"] = 15794176] = "Instantiable"; + TypeFlags[TypeFlags["StructuredOrInstantiable"] = 16711680] = "StructuredOrInstantiable"; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - TypeFlags[TypeFlags["Narrowable"] = 142575359] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 134283777] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["Narrowable"] = 33492479] = "Narrowable"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 16909315] = "NotUnionOrUnit"; /* @internal */ - TypeFlags[TypeFlags["RequiresWidening"] = 50331648] = "RequiresWidening"; + TypeFlags[TypeFlags["NotUnit"] = 16749629] = "NotUnit"; /* @internal */ - TypeFlags[TypeFlags["PropagatingFlags"] = 117440512] = "PropagatingFlags"; + TypeFlags[TypeFlags["RequiresWidening"] = 402653184] = "RequiresWidening"; /* @internal */ + TypeFlags[TypeFlags["PropagatingFlags"] = 939524096] = "PropagatingFlags"; + // The following flags are used for different purposes during union and intersection type construction + /* @internal */ + TypeFlags[TypeFlags["NonWideningType"] = 134217728] = "NonWideningType"; + /* @internal */ + TypeFlags[TypeFlags["Wildcard"] = 268435456] = "Wildcard"; + /* @internal */ + TypeFlags[TypeFlags["EmptyObject"] = 536870912] = "EmptyObject"; + /* @internal */ + TypeFlags[TypeFlags["ConstructionFlags"] = 939524096] = "ConstructionFlags"; + // The following flag is used for different purposes by maybeTypeOfKind + /* @internal */ + TypeFlags[TypeFlags["GenericMappedType"] = 134217728] = "GenericMappedType"; })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {})); var ObjectFlags; (function (ObjectFlags) { @@ -1048,6 +3076,11 @@ var ts; ScriptKind[ScriptKind["TSX"] = 4] = "TSX"; ScriptKind[ScriptKind["External"] = 5] = "External"; ScriptKind[ScriptKind["JSON"] = 6] = "JSON"; + /** + * Used on extensions that doesn't define the ScriptKind but the content defines it. + * Deferred extensions are going to be included in all project contexts. + */ + ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred"; })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {})); var ScriptTarget; (function (ScriptTarget) { @@ -1058,6 +3091,7 @@ var ts; ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017"; ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018"; ScriptTarget[ScriptTarget["ESNext"] = 6] = "ESNext"; + ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 6] = "Latest"; })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {})); var LanguageVariant; @@ -1065,12 +3099,6 @@ var ts; LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard"; LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX"; })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {})); - /* @internal */ - 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"; @@ -1293,6 +3321,7 @@ var ts; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { + EmitFlags[EmitFlags["None"] = 0] = "None"; EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine"; EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode"; EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution"; @@ -1406,9 +3435,9 @@ var ts; // Precomputed Formats 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["SingleLineTypeLiteralMembers"] = 384] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 16449] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 272] = "TupleTypeElements"; ListFormat[ListFormat["UnionTypeConstituents"] = 260] = "UnionTypeConstituents"; ListFormat[ListFormat["IntersectionTypeConstituents"] = 264] = "IntersectionTypeConstituents"; ListFormat[ListFormat["ObjectBindingPatternElements"] = 262576] = "ObjectBindingPatternElements"; @@ -1424,12 +3453,12 @@ var ts; ListFormat[ListFormat["VariableDeclarationList"] = 272] = "VariableDeclarationList"; ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 384] = "SingleLineFunctionBodyStatements"; ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements"; - ListFormat[ListFormat["ClassHeritageClauses"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "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["NamedImportsOrExportsElements"] = 262576] = "NamedImportsOrExportsElements"; ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 131072] = "JsxElementOrFragmentChildren"; ListFormat[ListFormat["JsxElementAttributes"] = 131328] = "JsxElementAttributes"; ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 81985] = "CaseOrDefaultClauseStatements"; @@ -1479,6 +3508,7 @@ var ts; "reference": { args: [ { name: "types", optional: true, captureSpan: true }, + { name: "lib", optional: true, captureSpan: true }, { name: "path", optional: true, captureSpan: true }, { name: "no-default-lib", optional: true } ], @@ -1504,3004 +3534,6 @@ var ts; }, }); })(ts || (ts = {})); -/*@internal*/ -var ts; -(function (ts) { - /** Gets a timestamp with (at least) ms resolution */ - ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; -})(ts || (ts = {})); -/*@internal*/ -/** Performance measurements for the compiler. */ -(function (ts) { - var performance; - (function (performance) { - // NOTE: cannot use ts.noop as core.ts loads after this - var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { }; - var enabled = false; - var profilerStart = 0; - var counts; - var marks; - var measures; - /** - * Marks a performance event. - * - * @param markName The name of the mark. - */ - function mark(markName) { - if (enabled) { - marks.set(markName, ts.timestamp()); - counts.set(markName, (counts.get(markName) || 0) + 1); - profilerEvent(markName); - } - } - performance.mark = mark; - /** - * Adds a performance measurement with the specified name. - * - * @param measureName The name of the performance measurement. - * @param startMarkName The name of the starting mark. If not supplied, the point at which the - * profiler was enabled is used. - * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is - * used. - */ - function measure(measureName, startMarkName, endMarkName) { - if (enabled) { - var end = endMarkName && marks.get(endMarkName) || ts.timestamp(); - var start = startMarkName && marks.get(startMarkName) || profilerStart; - measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); - } - } - performance.measure = measure; - /** - * Gets the number of times a marker was encountered. - * - * @param markName The name of the mark. - */ - function getCount(markName) { - return counts && counts.get(markName) || 0; - } - performance.getCount = getCount; - /** - * Gets the total duration of all measurements with the supplied name. - * - * @param measureName The name of the measure whose durations should be accumulated. - */ - function getDuration(measureName) { - return measures && measures.get(measureName) || 0; - } - performance.getDuration = getDuration; - /** - * Iterate over each measure, performing some action - * - * @param cb The action to perform for each measure - */ - function forEachMeasure(cb) { - measures.forEach(function (measure, key) { - cb(key, measure); - }); - } - performance.forEachMeasure = forEachMeasure; - /** Enables (and resets) performance measurements for the compiler. */ - function enable() { - counts = ts.createMap(); - marks = ts.createMap(); - measures = ts.createMap(); - enabled = true; - profilerStart = ts.timestamp(); - } - performance.enable = enable; - /** Disables performance measurements for the compiler. */ - function disable() { - enabled = false; - } - performance.disable = disable; - })(performance = ts.performance || (ts.performance = {})); -})(ts || (ts = {})); -/// -/// -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.8"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".1"; -})(ts || (ts = {})); -(function (ts) { - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. - return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; - function sortAndDeduplicateDiagnostics(diagnostics) { - return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); - } - ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - function closeFileWatcher(watcher) { - watcher.close(); - } - ts.closeFileWatcher = closeFileWatcher; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new MapCtr(); - } - ts.createMap = createMap; - /** Create a new escaped identifier map. */ - function createUnderscoreEscapedMap() { - return new MapCtr(); - } - ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - function createSymbolTable(symbols) { - var result = createMap(); - if (symbols) { - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; - result.set(symbol.escapedName, symbol); - } - } - return result; - } - ts.createSymbolTable = createSymbolTable; - function createMapFromTemplate(template) { - var map = new MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // tslint:disable-next-line no-in-operator variable-name - 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 = /** @class */ (function () { - function MapIterator(data, selector) { - this.index = 0; - this.data = data; - this.selector = selector; - this.keys = Object.keys(data); - } - MapIterator.prototype.next = function () { - var index = this.index; - if (index < this.keys.length) { - this.index++; - return { value: this.selector(this.data, this.keys[index]), done: false }; - } - return { value: undefined, done: true }; - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - } - class_1.prototype.get = function (key) { - return this.data[key]; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - } - this.data[key] = value; - return this; - }; - class_1.prototype.has = function (key) { - // tslint:disable-next-line:no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - delete this.data[key]; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.data, function (_data, key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.data, function (data, key) { return data[key]; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.data, function (data, key) { return [key, data[key]]; }); - }; - class_1.prototype.forEach = function (action) { - for (var key in this.data) { - action(this.data[key], key); - } - }; - return class_1; - }()); - } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = isRootedDiskPath(fileName) - ? normalizePath(fileName) - : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; - function length(array) { - return array ? array.length : 0; - } - ts.length = length; - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEach(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - return undefined; - } - ts.forEach = forEach; - /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ - function firstDefined(array, callback) { - if (array === undefined) { - return undefined; - } - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result !== undefined) { - return result; - } - } - return undefined; - } - ts.firstDefined = firstDefined; - function firstDefinedIterator(iter, callback) { - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) { - return undefined; - } - var result = callback(value); - if (result !== undefined) { - return result; - } - } - } - ts.firstDefinedIterator = firstDefinedIterator; - function findAncestor(node, callback) { - while (node) { - var result = callback(node); - if (result === "quit") { - return undefined; - } - else if (result) { - return node; - } - node = node.parent; - } - return undefined; - } - ts.findAncestor = findAncestor; - function zipWith(arrayA, arrayB, callback) { - var result = []; - Debug.assertEqual(arrayA.length, arrayB.length); - for (var i = 0; i < arrayA.length; i++) { - result.push(callback(arrayA[i], arrayB[i], i)); - } - return result; - } - ts.zipWith = zipWith; - function zipToIterator(arrayA, arrayB) { - Debug.assertEqual(arrayA.length, arrayB.length); - var i = 0; - return { - next: function () { - if (i === arrayA.length) { - return { value: undefined, done: true }; - } - i++; - return { value: [arrayA[i - 1], arrayB[i - 1]], done: false }; - } - }; - } - ts.zipToIterator = zipToIterator; - function zipToMap(keys, values) { - Debug.assert(keys.length === values.length); - var map = createMap(); - for (var i = 0; i < keys.length; ++i) { - map.set(keys[i], values[i]); - } - return map; - } - ts.zipToMap = zipToMap; - /** - * Iterates through `array` by index and performs the callback on each element of array until the callback - * returns a falsey value, then returns false. - * If no such value is found, the callback is applied to each element of array and `true` is returned. - */ - function every(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!callback(array[i], i)) { - return false; - } - } - } - return true; - } - ts.every = every; - function find(array, predicate) { - for (var i = 0; i < array.length; i++) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.find = find; - function findLast(array, predicate) { - for (var i = array.length - 1; i >= 0; i--) { - var value = array[i]; - if (predicate(value, i)) { - return value; - } - } - return undefined; - } - ts.findLast = findLast; - /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ - function findIndex(array, predicate) { - for (var i = 0; i < array.length; i++) { - if (predicate(array[i], i)) { - return i; - } - } - return -1; - } - ts.findIndex = findIndex; - /** - * Returns the first truthy result of `callback`, or else fails. - * This is like `forEach`, but never returns undefined. - */ - function findMap(array, callback) { - for (var i = 0; i < array.length; i++) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - Debug.fail(); - } - ts.findMap = findMap; - function contains(array, value, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (array) { - for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { - var v = array_1[_i]; - if (equalityComparer(v, value)) { - return true; - } - } - } - return false; - } - ts.contains = contains; - function arraysEqual(a, b, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); }); - } - ts.arraysEqual = arraysEqual; - function indexOfAnyCharCode(text, charCodes, start) { - for (var i = start || 0; i < text.length; i++) { - if (contains(charCodes, text.charCodeAt(i))) { - return i; - } - } - return -1; - } - ts.indexOfAnyCharCode = indexOfAnyCharCode; - function countWhere(array, predicate) { - var count = 0; - if (array) { - for (var i = 0; i < array.length; i++) { - var v = array[i]; - if (predicate(v, i)) { - count++; - } - } - } - return count; - } - ts.countWhere = countWhere; - function filter(array, f) { - if (array) { - var len = array.length; - var i = 0; - while (i < len && f(array[i])) - i++; - if (i < len) { - var result = array.slice(0, i); - i++; - while (i < len) { - var item = array[i]; - if (f(item)) { - result.push(item); - } - i++; - } - return result; - } - } - return array; - } - ts.filter = filter; - function filterMutate(array, f) { - var outIndex = 0; - for (var i = 0; i < array.length; i++) { - if (f(array[i], i, array)) { - array[outIndex] = array[i]; - outIndex++; - } - } - array.length = outIndex; - } - ts.filterMutate = filterMutate; - function clear(array) { - array.length = 0; - } - ts.clear = clear; - function map(array, f) { - var result; - if (array) { - result = []; - for (var i = 0; i < array.length; i++) { - result.push(f(array[i], i)); - } - } - return result; - } - ts.map = map; - function mapIterator(iter, mapFn) { - return { - next: function () { - var iterRes = iter.next(); - return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false }; - } - }; - } - ts.mapIterator = mapIterator; - function sameMap(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = f(item, i); - if (item !== mapped) { - var result = array.slice(0, i); - result.push(mapped); - for (i++; i < array.length; i++) { - result.push(f(array[i], i)); - } - return result; - } - } - } - return array; - } - ts.sameMap = sameMap; - /** - * Flattens an array containing a mix of array or non-array elements. - * - * @param array The array to flatten. - */ - function flatten(array) { - var result; - if (array) { - result = []; - for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { - var v = array_2[_i]; - if (v) { - if (isArray(v)) { - addRange(result, v); - } - else { - result.push(v); - } - } - } - } - return result; - } - ts.flatten = flatten; - /** - * Maps an array. If the mapped value is an array, it is spread into the result. - * - * @param array The array to map. - * @param mapfn The callback used to map the result into one or more values. - */ - function flatMap(array, mapfn) { - var result; - if (array) { - result = []; - for (var i = 0; i < array.length; i++) { - var v = mapfn(array[i], i); - if (v) { - if (isArray(v)) { - addRange(result, v); - } - else { - result.push(v); - } - } - } - } - return result; - } - ts.flatMap = flatMap; - function flatMapIterator(iter, mapfn) { - var first = iter.next(); - if (first.done) { - return ts.emptyIterator; - } - var currentIter = getIterator(first.value); - return { - next: function () { - while (true) { - var currentRes = currentIter.next(); - if (!currentRes.done) { - return currentRes; - } - var iterRes = iter.next(); - if (iterRes.done) { - return iterRes; - } - currentIter = getIterator(iterRes.value); - } - }, - }; - function getIterator(x) { - var res = mapfn(x); - return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res; - } - } - ts.flatMapIterator = flatMapIterator; - function sameFlatMap(array, mapfn) { - var result; - if (array) { - for (var i = 0; i < array.length; i++) { - var item = array[i]; - var mapped = mapfn(item, i); - if (result || item !== mapped || isArray(mapped)) { - if (!result) { - result = array.slice(0, i); - } - if (isArray(mapped)) { - addRange(result, mapped); - } - else { - result.push(mapped); - } - } - } - } - return result || array; - } - ts.sameFlatMap = sameFlatMap; - function mapAllOrFail(array, mapFn) { - var result = []; - for (var i = 0; i < array.length; i++) { - var mapped = mapFn(array[i], i); - if (mapped === undefined) { - return undefined; - } - result.push(mapped); - } - return result; - } - ts.mapAllOrFail = mapAllOrFail; - function mapDefined(array, mapFn) { - var result = []; - if (array) { - for (var i = 0; i < array.length; i++) { - var mapped = mapFn(array[i], i); - if (mapped !== undefined) { - result.push(mapped); - } - } - } - return result; - } - ts.mapDefined = mapDefined; - function mapDefinedIterator(iter, mapFn) { - return { - next: function () { - while (true) { - var res = iter.next(); - if (res.done) { - return res; - } - var value = mapFn(res.value); - if (value !== undefined) { - return { value: value, done: false }; - } - } - } - }; - } - ts.mapDefinedIterator = mapDefinedIterator; - ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } }; - function singleIterator(value) { - var done = false; - return { - next: function () { - var wasDone = done; - done = true; - return wasDone ? { value: undefined, done: true } : { value: value, done: false }; - } - }; - } - ts.singleIterator = singleIterator; - /** - * Computes the first matching span of elements and returns a tuple of the first span - * and the remaining elements. - */ - function span(array, f) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (!f(array[i], i)) { - return [array.slice(0, i), array.slice(i)]; - } - } - return [array.slice(0), []]; - } - return undefined; - } - ts.span = span; - /** - * Maps contiguous spans of values with the same key. - * - * @param array The array to map. - * @param keyfn A callback used to select the key for an element. - * @param mapfn A callback used to map a contiguous chunk of values to a single value. - */ - function spanMap(array, keyfn, mapfn) { - var result; - if (array) { - result = []; - var len = array.length; - var previousKey = void 0; - var key = void 0; - var start = 0; - var pos = 0; - while (start < len) { - while (pos < len) { - var value = array[pos]; - key = keyfn(value, pos); - if (pos === 0) { - previousKey = key; - } - else if (key !== previousKey) { - break; - } - pos++; - } - if (start < pos) { - var v = mapfn(array.slice(start, pos), previousKey, start, pos); - if (v) { - result.push(v); - } - start = pos; - } - previousKey = key; - pos++; - } - } - return result; - } - ts.spanMap = spanMap; - function mapEntries(map, f) { - if (!map) { - return undefined; - } - var result = createMap(); - map.forEach(function (value, key) { - var _a = f(key, value), newKey = _a[0], newValue = _a[1]; - result.set(newKey, newValue); - }); - return result; - } - ts.mapEntries = mapEntries; - function some(array, predicate) { - if (array) { - if (predicate) { - for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { - var v = array_3[_i]; - if (predicate(v)) { - return true; - } - } - } - else { - return array.length > 0; - } - } - return false; - } - ts.some = some; - function concatenate(array1, array2) { - if (!some(array2)) - return array1; - if (!some(array1)) - return array2; - return array1.concat(array2); - } - ts.concatenate = concatenate; - function deduplicateRelational(array, equalityComparer, comparer) { - // Perform a stable sort of the array. This ensures the first entry in a list of - // duplicates remains the first entry in the result. - var indices = array.map(function (_, i) { return i; }); - stableSortIndices(array, indices, comparer); - var last = array[indices[0]]; - var deduplicated = [indices[0]]; - for (var i = 1; i < indices.length; i++) { - var index = indices[i]; - var item = array[index]; - if (!equalityComparer(last, item)) { - deduplicated.push(index); - last = item; - } - } - // restore original order - deduplicated.sort(); - return deduplicated.map(function (i) { return array[i]; }); - } - function deduplicateEquality(array, equalityComparer) { - var result = []; - for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { - var item = array_4[_i]; - pushIfUnique(result, item, equalityComparer); - } - return result; - } - /** - * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. - * @param comparer An optional `Comparer` used to sort entries before comparison, though the - * result will remain in the original order in `array`. - */ - function deduplicate(array, equalityComparer, comparer) { - return !array ? undefined : - array.length === 0 ? [] : - array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : - deduplicateEquality(array, equalityComparer); - } - ts.deduplicate = deduplicate; - /** - * Deduplicates an array that has already been sorted. - */ - function deduplicateSorted(array, comparer) { - if (!array) - return undefined; - if (array.length === 0) - return []; - var last = array[0]; - var deduplicated = [last]; - for (var i = 1; i < array.length; i++) { - var next = array[i]; - switch (comparer(next, last)) { - // equality comparison - case true: - // relational comparison - case 0 /* EqualTo */: - continue; - case -1 /* LessThan */: - // If `array` is sorted, `next` should **never** be less than `last`. - return Debug.fail("Array is unsorted."); - } - deduplicated.push(last = next); - } - return deduplicated; - } - function insertSorted(array, insert, compare) { - if (array.length === 0) { - array.push(insert); - return; - } - var insertIndex = binarySearch(array, insert, identity, compare); - if (insertIndex < 0) { - array.splice(~insertIndex, 0, insert); - } - } - ts.insertSorted = insertSorted; - function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer); - } - ts.sortAndDeduplicate = sortAndDeduplicate; - function arrayIsEqualTo(array1, array2, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (!array1 || !array2) { - return array1 === array2; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; i++) { - if (!equalityComparer(array1[i], array2[i])) { - return false; - } - } - return true; - } - ts.arrayIsEqualTo = arrayIsEqualTo; - function changesAffectModuleResolution(oldOptions, newOptions) { - return !oldOptions || - (oldOptions.module !== newOptions.module) || - (oldOptions.moduleResolution !== newOptions.moduleResolution) || - (oldOptions.noResolve !== newOptions.noResolve) || - (oldOptions.target !== newOptions.target) || - (oldOptions.noLib !== newOptions.noLib) || - (oldOptions.jsx !== newOptions.jsx) || - (oldOptions.allowJs !== newOptions.allowJs) || - (oldOptions.rootDir !== newOptions.rootDir) || - (oldOptions.configFilePath !== newOptions.configFilePath) || - (oldOptions.baseUrl !== newOptions.baseUrl) || - (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || - !arrayIsEqualTo(oldOptions.lib, newOptions.lib) || - !arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || - !arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || - !equalOwnProperties(oldOptions.paths, newOptions.paths); - } - ts.changesAffectModuleResolution = changesAffectModuleResolution; - function compact(array) { - var result; - if (array) { - for (var i = 0; i < array.length; i++) { - var v = array[i]; - if (result || !v) { - if (!result) { - result = array.slice(0, i); - } - if (v) { - result.push(v); - } - } - } - } - return result || array; - } - ts.compact = compact; - /** - * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that - * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted - * based on the provided comparer. - */ - function relativeComplement(arrayA, arrayB, comparer) { - if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) - return arrayB; - var result = []; - loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { - if (offsetB > 0) { - // Ensure `arrayB` is properly sorted. - Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */); - } - loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) { - if (offsetA > startA) { - // Ensure `arrayA` is properly sorted. We only need to perform this check if - // `offsetA` has changed since we entered the loop. - Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */); - } - switch (comparer(arrayB[offsetB], arrayA[offsetA])) { - case -1 /* LessThan */: - // If B is less than A, B does not exist in arrayA. Add B to the result and - // move to the next element in arrayB without changing the current position - // in arrayA. - result.push(arrayB[offsetB]); - continue loopB; - case 0 /* EqualTo */: - // If B is equal to A, B exists in arrayA. Move to the next element in - // arrayB without adding B to the result or changing the current position - // in arrayA. - continue loopB; - case 1 /* GreaterThan */: - // If B is greater than A, we need to keep looking for B in arrayA. Move to - // the next element in arrayA and recheck. - continue loopA; - } - } - } - return result; - } - ts.relativeComplement = relativeComplement; - function sum(array, prop) { - var result = 0; - for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { - var v = array_5[_i]; - // TODO: Remove the following type assertion once the fix for #17069 is merged - result += v[prop]; - } - return result; - } - ts.sum = sum; - /** - * Appends a value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param value The value to append to the array. If `value` is `undefined`, nothing is - * appended. - */ - function append(to, value) { - if (value === undefined) - return to; - if (to === undefined) - return [value]; - to.push(value); - return to; - } - ts.append = append; - /** - * Gets the actual offset into an array for a relative offset. Negative offsets indicate a - * position offset from the end of the array. - */ - function toOffset(array, offset) { - return offset < 0 ? array.length + offset : offset; - } - /** - * Appends a range of value to an array, returning the array. - * - * @param to The array to which `value` is to be appended. If `to` is `undefined`, a new array - * is created if `value` was appended. - * @param from The values to append to the array. If `from` is `undefined`, nothing is - * appended. If an element of `from` is `undefined`, that element is not appended. - * @param start The offset in `from` at which to start copying values. - * @param end The offset in `from` at which to stop copying values (non-inclusive). - */ - function addRange(to, from, start, end) { - if (from === undefined || from.length === 0) - return to; - if (to === undefined) - return from.slice(start, end); - start = start === undefined ? 0 : toOffset(from, start); - end = end === undefined ? from.length : toOffset(from, end); - for (var i = start; i < end && i < from.length; i++) { - if (from[i] !== undefined) { - to.push(from[i]); - } - } - return to; - } - ts.addRange = addRange; - /** - * @return Whether the value was added. - */ - function pushIfUnique(array, toAdd, equalityComparer) { - if (contains(array, toAdd, equalityComparer)) { - return false; - } - else { - array.push(toAdd); - return true; - } - } - ts.pushIfUnique = pushIfUnique; - /** - * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. - */ - function appendIfUnique(array, toAdd, equalityComparer) { - if (array) { - pushIfUnique(array, toAdd, equalityComparer); - return array; - } - else { - return [toAdd]; - } - } - ts.appendIfUnique = appendIfUnique; - function stableSortIndices(array, indices, comparer) { - // sort indices by value then position - indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); }); - } - /** - * Returns a new sorted array. - */ - function sort(array, comparer) { - return array.slice().sort(comparer); - } - ts.sort = sort; - function best(iter, isBetter) { - var x = iter.next(); - if (x.done) { - return undefined; - } - var best = x.value; - while (true) { - var _a = iter.next(), value = _a.value, done = _a.done; - if (done) { - return best; - } - if (isBetter(value, best)) { - best = value; - } - } - } - ts.best = best; - function arrayIterator(array) { - var i = 0; - return { next: function () { - if (i === array.length) { - return { value: undefined, done: true }; - } - else { - i++; - return { value: array[i - 1], done: false }; - } - } }; - } - ts.arrayIterator = arrayIterator; - /** - * Stable sort of an array. Elements equal to each other maintain their relative position in the array. - */ - function stableSort(array, comparer) { - var indices = array.map(function (_, i) { return i; }); - stableSortIndices(array, indices, comparer); - return indices.map(function (i) { return array[i]; }); - } - ts.stableSort = stableSort; - function rangeEquals(array1, array2, pos, end) { - while (pos < end) { - if (array1[pos] !== array2[pos]) { - return false; - } - pos++; - } - return true; - } - ts.rangeEquals = rangeEquals; - /** - * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. - * A negative offset indicates the element should be retrieved from the end of the array. - */ - function elementAt(array, offset) { - if (array) { - offset = toOffset(array, offset); - if (offset < array.length) { - return array[offset]; - } - } - return undefined; - } - ts.elementAt = elementAt; - /** - * Returns the first element of an array if non-empty, `undefined` otherwise. - */ - function firstOrUndefined(array) { - return elementAt(array, 0); - } - ts.firstOrUndefined = firstOrUndefined; - function first(array) { - Debug.assert(array.length !== 0); - return array[0]; - } - ts.first = first; - /** - * Returns the last element of an array if non-empty, `undefined` otherwise. - */ - function lastOrUndefined(array) { - return elementAt(array, -1); - } - ts.lastOrUndefined = lastOrUndefined; - function last(array) { - Debug.assert(array.length !== 0); - return array[array.length - 1]; - } - ts.last = last; - /** - * Returns the only element of an array if it contains only one element, `undefined` otherwise. - */ - function singleOrUndefined(array) { - return array && array.length === 1 - ? array[0] - : undefined; - } - ts.singleOrUndefined = singleOrUndefined; - function singleOrMany(array) { - return array && array.length === 1 - ? array[0] - : array; - } - ts.singleOrMany = singleOrMany; - function replaceElement(array, index, value) { - var result = array.slice(0); - result[index] = value; - return result; - } - ts.replaceElement = replaceElement; - /** - * Performs a binary search, finding the index at which `value` occurs in `array`. - * If no such index is found, returns the 2's-complement of first index at which - * `array[index]` exceeds `value`. - * @param array A sorted array whose first element must be no larger than number - * @param value The value to be searched for in the array. - * @param keySelector A callback used to select the search key from `value` and each element of - * `array`. - * @param keyComparer A callback used to compare two keys in a sorted array. - * @param offset An offset into `array` at which to start the search. - */ - function binarySearch(array, value, keySelector, keyComparer, offset) { - if (!array || array.length === 0) { - return -1; - } - var low = offset || 0; - var high = array.length - 1; - var key = keySelector(value); - while (low <= high) { - var middle = low + ((high - low) >> 1); - var midKey = keySelector(array[middle]); - switch (keyComparer(midKey, key)) { - case -1 /* LessThan */: - low = middle + 1; - break; - case 0 /* EqualTo */: - return middle; - case 1 /* GreaterThan */: - high = middle - 1; - break; - } - } - return ~low; - } - ts.binarySearch = binarySearch; - function reduceLeft(array, f, initial, start, count) { - if (array && array.length > 0) { - var size = array.length; - if (size > 0) { - var pos = start === undefined || start < 0 ? 0 : start; - var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count; - var result = void 0; - if (arguments.length <= 2) { - result = array[pos]; - pos++; - } - else { - result = initial; - } - while (pos <= end) { - result = f(result, array[pos], pos); - pos++; - } - return result; - } - } - return initial; - } - ts.reduceLeft = reduceLeft; - var hasOwnProperty = Object.prototype.hasOwnProperty; - /** - * Indicates whether a map-like contains an own property with the specified key. - * - * @param map A map-like. - * @param key A property key. - */ - function hasProperty(map, key) { - return hasOwnProperty.call(map, key); - } - ts.hasProperty = hasProperty; - /** - * Gets the value of an owned property in a map-like. - * - * @param map A map-like. - * @param key A property key. - */ - function getProperty(map, key) { - return hasOwnProperty.call(map, key) ? map[key] : undefined; - } - ts.getProperty = getProperty; - /** - * Gets the owned, enumerable property keys of a map-like. - */ - function getOwnKeys(map) { - var keys = []; - for (var key in map) { - if (hasOwnProperty.call(map, key)) { - keys.push(key); - } - } - return keys; - } - ts.getOwnKeys = getOwnKeys; - function getOwnValues(sparseArray) { - var values = []; - for (var key in sparseArray) { - if (hasOwnProperty.call(sparseArray, key)) { - values.push(sparseArray[key]); - } - } - return values; - } - ts.getOwnValues = getOwnValues; - function arrayFrom(iterator, map) { - var result = []; - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - result.push(map ? map(value) : value); - } - return result; - var _b; - } - ts.arrayFrom = arrayFrom; - function forEachEntry(map, callback) { - var iterator = map.entries(); - for (var _a = iterator.next(), pair = _a.value, done = _a.done; !done; _b = iterator.next(), pair = _b.value, done = _b.done, _b) { - var key = pair[0], value = pair[1]; - var result = callback(value, key); - if (result) { - return result; - } - } - return undefined; - var _b; - } - ts.forEachEntry = forEachEntry; - function forEachKey(map, callback) { - var iterator = map.keys(); - for (var _a = iterator.next(), key = _a.value, done = _a.done; !done; _b = iterator.next(), key = _b.value, done = _b.done, _b) { - var result = callback(key); - if (result) { - return result; - } - } - return undefined; - var _b; - } - ts.forEachKey = forEachKey; - function copyEntries(source, target) { - source.forEach(function (value, key) { - target.set(key, value); - }); - } - ts.copyEntries = copyEntries; - function assign(t) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { - var arg = args_1[_a]; - for (var p in arg) { - if (hasProperty(arg, p)) { - t[p] = arg[p]; - } - } - } - return t; - } - ts.assign = assign; - /** - * Performs a shallow equality comparison of the contents of two map-likes. - * - * @param left A map-like whose properties should be compared. - * @param right A map-like whose properties should be compared. - */ - function equalOwnProperties(left, right, equalityComparer) { - if (equalityComparer === void 0) { equalityComparer = equateValues; } - if (left === right) - return true; - if (!left || !right) - return false; - for (var key in left) { - if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key) === undefined) - return false; - if (!equalityComparer(left[key], right[key])) - return false; - } - } - for (var key in right) { - if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; - } - } - return true; - } - ts.equalOwnProperties = equalOwnProperties; - function arrayToMap(array, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = createMap(); - for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { - var value = array_6[_i]; - result.set(makeKey(value), makeValue(value)); - } - return result; - } - ts.arrayToMap = arrayToMap; - function arrayToNumericMap(array, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = []; - for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { - var value = array_7[_i]; - result[makeKey(value)] = makeValue(value); - } - return result; - } - ts.arrayToNumericMap = arrayToNumericMap; - function arrayToSet(array, makeKey) { - return arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); - } - ts.arrayToSet = arrayToSet; - function arrayToMultiMap(values, makeKey, makeValue) { - if (makeValue === void 0) { makeValue = identity; } - var result = createMultiMap(); - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var value = values_1[_i]; - result.add(makeKey(value), makeValue(value)); - } - return result; - } - ts.arrayToMultiMap = arrayToMultiMap; - function group(values, getGroupId) { - return arrayFrom(arrayToMultiMap(values, getGroupId).values()); - } - ts.group = group; - function cloneMap(map) { - var clone = createMap(); - copyEntries(map, clone); - return clone; - } - ts.cloneMap = cloneMap; - function clone(object) { - var result = {}; - for (var id in object) { - if (hasOwnProperty.call(object, id)) { - result[id] = object[id]; - } - } - return result; - } - ts.clone = clone; - function extend(first, second) { - var result = {}; - for (var id in second) { - if (hasOwnProperty.call(second, id)) { - result[id] = second[id]; - } - } - for (var id in first) { - if (hasOwnProperty.call(first, id)) { - result[id] = first[id]; - } - } - return result; - } - ts.extend = extend; - function createMultiMap() { - var map = createMap(); - map.add = multiMapAdd; - map.remove = multiMapRemove; - return map; - } - ts.createMultiMap = createMultiMap; - function multiMapAdd(key, value) { - var values = this.get(key); - if (values) { - values.push(value); - } - else { - this.set(key, values = [value]); - } - return values; - } - function multiMapRemove(key, value) { - var values = this.get(key); - if (values) { - unorderedRemoveItem(values, value); - if (!values.length) { - this.delete(key); - } - } - } - /** - * Tests whether a value is an array. - */ - function isArray(value) { - return Array.isArray ? Array.isArray(value) : value instanceof Array; - } - ts.isArray = isArray; - function toArray(value) { - return isArray(value) ? value : [value]; - } - ts.toArray = toArray; - /** - * Tests whether a value is string - */ - function isString(text) { - return typeof text === "string"; - } - ts.isString = isString; - function tryCast(value, test) { - return value !== undefined && test(value) ? value : undefined; - } - ts.tryCast = tryCast; - function cast(value, test) { - if (value !== undefined && test(value)) - return value; - if (value && typeof value.kind === "number") { - Debug.fail("Invalid cast. The supplied " + Debug.showSyntaxKind(value) + " did not pass the test '" + Debug.getFunctionName(test) + "'."); - } - else { - Debug.fail("Invalid cast. The supplied value did not pass the test '" + Debug.getFunctionName(test) + "'."); - } - } - ts.cast = cast; - /** Does nothing. */ - function noop(_) { } // tslint:disable-line no-empty - ts.noop = noop; - /** Do nothing and return false */ - function returnFalse() { return false; } - ts.returnFalse = returnFalse; - /** Do nothing and return true */ - function returnTrue() { return true; } - ts.returnTrue = returnTrue; - /** Returns its argument. */ - function identity(x) { return x; } - ts.identity = identity; - /** Returns lower case string */ - function toLowerCase(x) { return x.toLowerCase(); } - ts.toLowerCase = toLowerCase; - /** Throws an error because a function is not implemented. */ - function notImplemented() { - throw new Error("Not implemented"); - } - ts.notImplemented = notImplemented; - function memoize(callback) { - var value; - return function () { - if (callback) { - value = callback(); - callback = undefined; - } - return value; - }; - } - ts.memoize = memoize; - function chain(a, b, c, d, e) { - if (e) { - var args_2 = []; - for (var i = 0; i < arguments.length; i++) { - args_2[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (_) { return function (u) { return u; }; }; - } - } - ts.chain = chain; - function compose(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } - ts.compose = compose; - function formatStringFromArgs(text, args, baseIndex) { - baseIndex = baseIndex || 0; - return text.replace(/{(\d+)}/g, function (_match, index) { return args[+index + baseIndex]; }); - } - ts.formatStringFromArgs = formatStringFromArgs; - function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; - } - ts.getLocaleSpecificMessage = getLocaleSpecificMessage; - function createFileDiagnostic(file, start, length, message) { - Debug.assertGreaterThanOrEqual(start, 0); - Debug.assertGreaterThanOrEqual(length, 0); - if (file) { - Debug.assertLessThanOrEqual(start, file.text.length); - Debug.assertLessThanOrEqual(start + length, file.text.length); - } - var text = getLocaleSpecificMessage(message); - if (arguments.length > 4) { - text = formatStringFromArgs(text, arguments, 4); - } - return { - file: file, - start: start, - length: length, - messageText: text, - category: message.category, - code: message.code, - }; - } - ts.createFileDiagnostic = createFileDiagnostic; - /* internal */ - function formatMessage(_dummy, message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); - } - return text; - } - ts.formatMessage = formatMessage; - function createCompilerDiagnostic(message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 1) { - text = formatStringFromArgs(text, arguments, 1); - } - return { - file: undefined, - start: undefined, - length: undefined, - messageText: text, - category: message.category, - code: message.code - }; - } - ts.createCompilerDiagnostic = createCompilerDiagnostic; - function createCompilerDiagnosticFromMessageChain(chain) { - return { - file: undefined, - start: undefined, - length: undefined, - code: chain.code, - category: chain.category, - messageText: chain.next ? chain : chain.messageText - }; - } - ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; - function chainDiagnosticMessages(details, message) { - var text = getLocaleSpecificMessage(message); - if (arguments.length > 2) { - text = formatStringFromArgs(text, arguments, 2); - } - return { - messageText: text, - category: message.category, - code: message.code, - next: details - }; - } - ts.chainDiagnosticMessages = chainDiagnosticMessages; - function concatenateDiagnosticMessageChains(headChain, tailChain) { - var lastChain = headChain; - while (lastChain.next) { - lastChain = lastChain.next; - } - lastChain.next = tailChain; - return headChain; - } - ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; - function equateValues(a, b) { - return a === b; - } - ts.equateValues = equateValues; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function equateStringsCaseInsensitive(a, b) { - return a === b - || a !== undefined - && b !== undefined - && a.toUpperCase() === b.toUpperCase(); - } - ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive; - /** - * Compare the equality of two strings using a case-sensitive ordinal comparison. - * - * Case-sensitive comparisons compare both strings one code-point at a time using the - * integer value of each code-point. - */ - function equateStringsCaseSensitive(a, b) { - return equateValues(a, b); - } - ts.equateStringsCaseSensitive = equateStringsCaseSensitive; - function compareComparableValues(a, b) { - return a === b ? 0 /* EqualTo */ : - a === undefined ? -1 /* LessThan */ : - b === undefined ? 1 /* GreaterThan */ : - a < b ? -1 /* LessThan */ : - 1 /* GreaterThan */; - } - /** - * Compare two numeric values for their order relative to each other. - * To compare strings, use any of the `compareStrings` functions. - */ - function compareValues(a, b) { - return compareComparableValues(a, b); - } - ts.compareValues = compareValues; - /** - * Compare two strings using a case-insensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-insensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point after applying `toUpperCase` to each string. We always map both - * strings to their upper-case form as some unicode characters do not properly round-trip to - * lowercase (such as `ẞ` (German sharp capital s)). - */ - function compareStringsCaseInsensitive(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - a = a.toUpperCase(); - b = b.toUpperCase(); - return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive; - /** - * Compare two strings using a case-sensitive ordinal comparison. - * - * Ordinal comparisons are based on the difference between the unicode code points of both - * strings. Characters with multiple unicode representations are considered unequal. Ordinal - * comparisons provide predictable ordering, but place "a" after "B". - * - * Case-sensitive comparisons compare both strings one code-point at a time using the integer - * value of each code-point. - */ - function compareStringsCaseSensitive(a, b) { - return compareComparableValues(a, b); - } - ts.compareStringsCaseSensitive = compareStringsCaseSensitive; - /** - * Creates a string comparer for use with string collation in the UI. - */ - var createUIStringComparer = (function () { - var defaultComparer; - var enUSComparer; - var stringComparerFactory = getStringComparerFactory(); - return createStringComparer; - function compareWithCallback(a, b, comparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - var value = comparer(a, b); - return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - function createIntlCollatorStringComparer(locale) { - // Intl.Collator.prototype.compare is bound to the collator. See NOTE in - // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare - var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare; - return function (a, b) { return compareWithCallback(a, b, comparer); }; - } - function createLocaleCompareStringComparer(locale) { - // if the locale is not the default locale (`undefined`), use the fallback comparer. - if (locale !== undefined) - return createFallbackStringComparer(); - return function (a, b) { return compareWithCallback(a, b, compareStrings); }; - function compareStrings(a, b) { - return a.localeCompare(b); - } - } - function createFallbackStringComparer() { - // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b". - // We first sort case insensitively. So "Aaa" will come before "baa". - // Then we sort case sensitively, so "aaa" will come before "Aaa". - // - // For case insensitive comparisons we always map both strings to their - // upper-case form as some unicode characters do not properly round-trip to - // lowercase (such as `ẞ` (German sharp capital s)). - return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); }; - function compareDictionaryOrder(a, b) { - return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b); - } - function compareStrings(a, b) { - return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; - } - } - function getStringComparerFactory() { - // If the host supports Intl, we use it for comparisons using the default locale. - if (typeof Intl === "object" && typeof Intl.Collator === "function") { - return createIntlCollatorStringComparer; - } - // If the host does not support Intl, we fall back to localeCompare. - // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it. - if (typeof String.prototype.localeCompare === "function" && - typeof String.prototype.toLocaleUpperCase === "function" && - "a".localeCompare("B") < 0) { - return createLocaleCompareStringComparer; - } - // Otherwise, fall back to ordinal comparison: - return createFallbackStringComparer; - } - function createStringComparer(locale) { - // Hold onto common string comparers. This avoids constantly reallocating comparers during - // tests. - if (locale === undefined) { - return defaultComparer || (defaultComparer = stringComparerFactory(locale)); - } - else if (locale === "en-US") { - return enUSComparer || (enUSComparer = stringComparerFactory(locale)); - } - else { - return stringComparerFactory(locale); - } - } - })(); - var uiComparerCaseSensitive; - var uiLocale; - function getUILocale() { - return uiLocale; - } - ts.getUILocale = getUILocale; - function setUILocale(value) { - if (uiLocale !== value) { - uiLocale = value; - uiComparerCaseSensitive = undefined; - } - } - ts.setUILocale = setUILocale; - /** - * Compare two strings in a using the case-sensitive sort behavior of the UI locale. - * - * Ordering is not predictable between different host locales, but is best for displaying - * ordered data for UI presentation. Characters with multiple unicode representations may - * be considered equal. - * - * Case-sensitive comparisons compare strings that differ in base characters, or - * accents/diacritic marks, or case as unequal. - */ - function compareStringsCaseSensitiveUI(a, b) { - var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); - return comparer(a, b); - } - ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI; - function compareProperties(a, b, key, comparer) { - return a === b ? 0 /* EqualTo */ : - a === undefined ? -1 /* LessThan */ : - b === undefined ? 1 /* GreaterThan */ : - comparer(a[key], b[key]); - } - ts.compareProperties = compareProperties; - function getDiagnosticFileName(diagnostic) { - return diagnostic.file ? diagnostic.file.fileName : undefined; - } - function compareDiagnostics(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFileName(d1), getDiagnosticFileName(d2)) || - compareValues(d1.start, d2.start) || - compareValues(d1.length, d2.length) || - compareValues(d1.code, d2.code) || - compareMessageText(d1.messageText, d2.messageText) || - 0 /* EqualTo */; - } - ts.compareDiagnostics = compareDiagnostics; - /** True is greater than false. */ - function compareBooleans(a, b) { - return compareValues(a ? 1 : 0, b ? 1 : 0); - } - ts.compareBooleans = compareBooleans; - function compareMessageText(text1, text2) { - while (text1 && text2) { - // We still have both chains. - var string1 = isString(text1) ? text1 : text1.messageText; - var string2 = isString(text2) ? text2 : text2.messageText; - var res = compareStringsCaseSensitive(string1, string2); - if (res) { - return res; - } - text1 = isString(text1) ? undefined : text1.next; - text2 = isString(text2) ? undefined : text2.next; - } - if (!text1 && !text2) { - // if the chains are done, then these messages are the same. - return 0 /* EqualTo */; - } - // We still have one chain remaining. The shorter chain should come first. - return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; - } - function normalizeSlashes(path) { - return path.replace(/\\/g, "/"); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") - */ - function getRootLength(path) { - if (path.charCodeAt(0) === 47 /* slash */) { - if (path.charCodeAt(1) !== 47 /* slash */) - return 1; - var p1 = path.indexOf("/", 2); - if (p1 < 0) - return 2; - var p2 = path.indexOf("/", p1 + 1); - if (p2 < 0) - return p1 + 1; - return p2 + 1; - } - if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) - return 3; - } - // Per RFC 1738 'file' URI schema has the shape file:/// - // if is omitted then it is assumed that host value is 'localhost', - // however slash after the omitted is not removed. - // file:///folder1/file1 - this is a correct URI - // file://folder2/file2 - this is an incorrect URI - if (path.lastIndexOf("file:///", 0) === 0) { - return "file:///".length; - } - var idx = path.indexOf("://"); - if (idx !== -1) { - return idx + "://".length; - } - return 0; - } - ts.getRootLength = getRootLength; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var directorySeparatorCharCode = 47 /* slash */; - function getNormalizedParts(normalizedSlashedPath, rootLength) { - var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); - var normalized = []; - for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { - var part = parts_1[_i]; - if (part !== ".") { - if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { - normalized.pop(); - } - else { - // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, - // e.g. "path//file.ts". Drop these before re-joining the parts. - if (part) { - normalized.push(part); - } - } - } - } - 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 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 { path: root, parts: parts }; - } - } - 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; - } - ts.pathEndsWithDirectorySeparator = pathEndsWithDirectorySeparator; - function getDirectoryPath(path) { - return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function isUrl(path) { - return path && !isRootedDiskPath(path) && stringContains(path, "://"); - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; - function getEmitModuleResolutionKind(compilerOptions) { - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - } - return moduleResolution; - } - ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; - function getAllowSyntheticDefaultImports(compilerOptions) { - var moduleKind = getEmitModuleKind(compilerOptions); - return compilerOptions.allowSyntheticDefaultImports !== undefined - ? compilerOptions.allowSyntheticDefaultImports - : compilerOptions.esModuleInterop - ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 - : moduleKind === ts.ModuleKind.System; - } - ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; - function getStrictOptionValue(compilerOptions, flag) { - return compilerOptions[flag] === undefined ? compilerOptions.strict : compilerOptions[flag]; - } - ts.getStrictOptionValue = getStrictOptionValue; - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function isRootedDiskPath(path) { - return path && getRootLength(path) !== 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function normalizedPathComponents(path, rootLength) { - var normalizedParts = getNormalizedParts(path, rootLength); - return [path.substr(0, rootLength)].concat(normalizedParts); - } - function getNormalizedPathComponents(path, currentDirectory) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - if (rootLength === 0) { - // If the path is not rooted it is relative to current directory - path = combinePaths(normalizeSlashes(currentDirectory), path); - rootLength = getRootLength(path); - } - return normalizedPathComponents(path, rootLength); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getNormalizedPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getNormalizedPathFromPathComponents(pathComponents) { - if (pathComponents && pathComponents.length) { - return pathComponents[0] + pathComponents.slice(1).join(ts.directorySeparator); - } - } - ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; - function getNormalizedPathComponentsOfUrl(url) { - // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ - // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - var urlLength = url.length; - // Initial root length is http:// part - var rootLength = url.indexOf("://") + "://".length; - while (rootLength < urlLength) { - // Consume all immediate slashes in the protocol - // eg.initial rootlength is just file:// but it needs to consume another "/" in file:/// - if (url.charCodeAt(rootLength) === 47 /* slash */) { - rootLength++; - } - else { - // non slash character means we continue proceeding to next component of root search - break; - } - } - // there are no parts after http:// just return current string as the pathComponent - if (rootLength === urlLength) { - return [url]; - } - // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - var indexOfNextSlash = url.indexOf(ts.directorySeparator, rootLength); - if (indexOfNextSlash !== -1) { - // Found the "/" after the website.com so the root is length of http://www.website.com/ - // and get components after the root normally like any other folder components - rootLength = indexOfNextSlash + 1; - return normalizedPathComponents(url, rootLength); - } - else { - // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" - // eg. if url passed in was http://website.com we want to use root as [http://website.com/] - // so that other path manipulations will be correct and it can be merged with relative paths correctly - return [url + ts.directorySeparator]; - } - } - function getNormalizedPathOrUrlComponents(pathOrUrl, currentDirectory) { - if (isUrl(pathOrUrl)) { - return getNormalizedPathComponentsOfUrl(pathOrUrl); - } - else { - return getNormalizedPathComponents(pathOrUrl, currentDirectory); - } - } - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { - // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] - directoryComponents.pop(); - } - // Find the component that differs - var joinStartIndex; - for (joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (getCanonicalFileName(directoryComponents[joinStartIndex]) !== getCanonicalFileName(pathComponents[joinStartIndex])) { - break; - } - } - // Get the relative path - if (joinStartIndex) { - var relativePath = ""; - var relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); - for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { - if (directoryComponents[joinStartIndex] !== "") { - relativePath = relativePath + ".." + ts.directorySeparator; - } - } - return relativePath + relativePathComponents.join(ts.directorySeparator); - } - // Cant find the relative path, get the absolute path - var absolutePath = getNormalizedPathFromPathComponents(pathComponents); - if (isAbsolutePathAnUrl && isRootedDiskPath(absolutePath)) { - absolutePath = "file:///" + absolutePath; - } - return absolutePath; - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function getBaseFileName(path) { - if (path === undefined) { - return undefined; - } - var i = path.lastIndexOf(ts.directorySeparator); - return i < 0 ? path : path.substring(i + 1); - } - ts.getBaseFileName = getBaseFileName; - function combinePaths(path1, path2) { - if (!(path1 && path1.length)) - return path2; - if (!(path2 && path2.length)) - return path1; - if (getRootLength(path2) !== 0) - return path2; - if (path1.charAt(path1.length - 1) === ts.directorySeparator) - return path1 + path2; - return path1 + ts.directorySeparator + path2; - } - ts.combinePaths = combinePaths; - function removeTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) === ts.directorySeparator) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - /** - * Adds a trailing directory separator to a path, if it does not already have one. - * @param path The path. - */ - function ensureTrailingDirectorySeparator(path) { - if (path.charAt(path.length - 1) !== ts.directorySeparator) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - a = removeTrailingDirectorySeparator(a); - b = removeTrailingDirectorySeparator(b); - var aComponents = getNormalizedPathComponents(a, currentDirectory); - var bComponents = getNormalizedPathComponents(b, currentDirectory); - var sharedLength = Math.min(aComponents.length, bComponents.length); - var comparer = ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; - for (var i = 0; i < sharedLength; i++) { - var result = comparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; - } - } - return compareValues(aComponents.length, bComponents.length); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - parent = removeTrailingDirectorySeparator(parent); - child = removeTrailingDirectorySeparator(child); - if (parent === child) - return true; - var parentComponents = getNormalizedPathComponents(parent, currentDirectory); - var childComponents = getNormalizedPathComponents(child, currentDirectory); - if (childComponents.length < parentComponents.length) { - return false; - } - var equalityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function startsWith(str, prefix) { - return str.lastIndexOf(prefix, 0) === 0; - } - ts.startsWith = startsWith; - function removePrefix(str, prefix) { - return startsWith(str, prefix) ? str.substr(prefix.length) : str; - } - ts.removePrefix = removePrefix; - function endsWith(str, suffix) { - var expectedPos = str.length - suffix.length; - return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; - } - ts.endsWith = endsWith; - function removeSuffix(str, suffix) { - return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; - } - ts.removeSuffix = removeSuffix; - function stringContains(str, substring) { - return str.indexOf(substring) !== -1; - } - ts.stringContains = stringContains; - function hasExtension(fileName) { - return stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; - // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. - // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future - // proof. - var reservedCharacterPattern = /[^\w\s\/]/g; - var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - 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) { - return undefined; - } - var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); - // If excluding, match "foo/bar/baz...", but if including, only allow "foo". - var terminator = usage === "exclude" ? "($|/)" : "$"; - return "^(" + pattern + ")" + terminator; - } - ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; - function getRegularExpressionsForWildcards(specs, basePath, usage) { - if (specs === undefined || specs.length === 0) { - return undefined; - } - return flatMap(specs, function (spec) { - return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); - }); - } - /** - * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, - * and does not contain any glob characters itself. - */ - function isImplicitGlob(lastPathComponent) { - return !/[.*?]/.test(lastPathComponent); - } - ts.isImplicitGlob = isImplicitGlob; - function getSubPatternFromSpec(spec, basePath, usage, _a) { - var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; - var subpattern = ""; - var hasWrittenComponent = false; - var components = getNormalizedPathComponents(spec, basePath); - var lastComponent = lastOrUndefined(components); - if (usage !== "exclude" && lastComponent === "**") { - return undefined; - } - // getNormalizedPathComponents includes the separator for the root component. - // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); - if (isImplicitGlob(lastComponent)) { - components.push("**", "*"); - } - var optionalCount = 0; - for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { - var component = components_1[_i]; - if (component === "**") { - subpattern += doubleAsteriskRegexFragment; - } - else { - if (usage === "directories") { - subpattern += "("; - optionalCount++; - } - if (hasWrittenComponent) { - 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 */) { - componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; - component = component.substr(1); - } - else if (component.charCodeAt(0) === 63 /* question */) { - 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); - } - } - hasWrittenComponent = true; - } - while (optionalCount > 0) { - subpattern += ")?"; - optionalCount--; - } - return subpattern; - } - function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { - return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; - } - function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); - return { - includeFilePatterns: map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), - includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), - includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), - excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), - basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) - }; - } - ts.getFileMatcherPatterns = getFileMatcherPatterns; - function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { - path = normalizePath(path); - currentDirectory = normalizePath(currentDirectory); - var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); - var regexFlag = useCaseSensitiveFileNames ? "" : "i"; - var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return new RegExp(pattern, regexFlag); }); - var includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag); - var excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag); - // Associate an array of results with each include regex. This keeps results in order of the "include" order. - // If there are no "includes", then just put everything in results[0]. - var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; - for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { - var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); - } - return flatten(results); - function visitDirectory(path, absolutePath, depth) { - var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; - var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name, extensions)) - return "continue"; - if (excludeRegex && excludeRegex.test(absoluteName)) - return "continue"; - if (!includeFileRegexes) { - results[0].push(name); - } - else { - var includeIndex = findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); - if (includeIndex !== -1) { - results[includeIndex].push(name); - } - } - }; - for (var _i = 0, _b = sort(files, compareStringsCaseSensitive); _i < _b.length; _i++) { - var current = _b[_i]; - _loop_1(current); - } - if (depth !== undefined) { - depth--; - if (depth === 0) { - return; - } - } - for (var _c = 0, _d = sort(directories, compareStringsCaseSensitive); _c < _d.length; _c++) { - var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); - if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && - (!excludeRegex || !excludeRegex.test(absoluteName))) { - visitDirectory(name, absoluteName, depth); - } - } - } - } - ts.matchFiles = matchFiles; - /** - * Computes the unique non-wildcard base paths amongst the provided include patterns. - */ - function getBasePaths(path, includes, useCaseSensitiveFileNames) { - // Storage for our results in the form of literal paths (e.g. the paths as written by the user). - var basePaths = [path]; - if (includes) { - // Storage for literal base paths amongst the include patterns. - var includeBasePaths = []; - for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { - var include = includes_1[_i]; - // We also need to check the relative paths by converting them to absolute and normalizing - // in case they escape the base path (e.g "..\somedirectory") - var absolute = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)); - // Append the literal and canonical candidate base paths. - includeBasePaths.push(getIncludeBasePath(absolute)); - } - // Sort the offsets array using either the literal or canonical path representations. - includeBasePaths.sort(useCaseSensitiveFileNames ? compareStringsCaseSensitive : compareStringsCaseInsensitive); - var _loop_2 = function (includeBasePath) { - if (every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { - basePaths.push(includeBasePath); - } - }; - // Iterate over each include base path and include unique base paths that are not a - // subpath of an existing base path - for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { - var includeBasePath = includeBasePaths_1[_a]; - _loop_2(includeBasePath); - } - } - return basePaths; - } - function getIncludeBasePath(absolute) { - var wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes); - if (wildcardOffset < 0) { - // No "*" or "?" in the path - return !hasExtension(absolute) - ? absolute - : removeTrailingDirectorySeparator(getDirectoryPath(absolute)); - } - return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); - } - function ensureScriptKind(fileName, scriptKind) { - // Using scriptKind as a condition handles both: - // - 'scriptKind' is unspecified and thus it is `undefined` - // - 'scriptKind' is set and it is `Unknown` (0) - // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt - // to get the ScriptKind from the file name. If it cannot be resolved - // from the file name then the default 'TS' script kind is returned. - return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; - } - ts.ensureScriptKind = ensureScriptKind; - function getScriptKindFromFileName(fileName) { - var ext = fileName.substr(fileName.lastIndexOf(".")); - switch (ext.toLowerCase()) { - case ".js" /* Js */: - return 1 /* JS */; - case ".jsx" /* Jsx */: - return 2 /* JSX */; - case ".ts" /* Ts */: - return 3 /* TS */; - case ".tsx" /* Tsx */: - return 4 /* TSX */; - case ".json" /* Json */: - return 6 /* JSON */; - default: - return 0 /* Unknown */; - } - } - ts.getScriptKindFromFileName = getScriptKindFromFileName; - /** - * List of supported extensions in order of file resolution precedence. - */ - ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; - /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; - ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; - var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); - function getSupportedExtensions(options, extraFileExtensions) { - var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { - return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; - } - return deduplicate(allSupportedExtensions.concat(extraFileExtensions.map(function (e) { return e.extension; })), equateStringsCaseSensitive, compareStringsCaseSensitive); - } - ts.getSupportedExtensions = getSupportedExtensions; - function hasJavaScriptFileExtension(fileName) { - return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; - function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { - if (!fileName) { - return false; - } - for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { - var extension = _a[_i]; - if (fileExtensionIs(fileName, extension)) { - return true; - } - } - return false; - } - ts.isSupportedSourceFileName = isSupportedSourceFileName; - /** - * Extension boundaries by priority. Lower numbers indicate higher priorities, and are - * aligned to the offset of the highest priority extension in the - * allSupportedExtensions array. - */ - 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])) { - return adjustExtensionPriority(i, supportedExtensions); - } - } - // If its not in the list of supported extensions, this is likely a - // TypeScript file with a non-ts extension - return 0 /* Highest */; - } - ts.getExtensionPriority = getExtensionPriority; - /** - * Adjusts an extension priority to be the highest priority within the same range. - */ - function adjustExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { - return 0 /* TypeScriptFiles */; - } - else if (extensionPriority < supportedExtensions.length) { - return 2 /* DeclarationAndJavaScriptFiles */; - } - else { - return supportedExtensions.length; - } - } - ts.adjustExtensionPriority = adjustExtensionPriority; - /** - * Gets the next lowest extension priority for a given priority. - */ - function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { - if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { - return 2 /* DeclarationAndJavaScriptFiles */; - } - else { - return supportedExtensions.length; - } - } - ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; - var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */]; - function removeFileExtension(path) { - for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { - var ext = extensionsToRemove_1[_i]; - var extensionless = tryRemoveExtension(path, ext); - if (extensionless !== undefined) { - return extensionless; - } - } - return path; - } - ts.removeFileExtension = removeFileExtension; - function tryRemoveExtension(path, extension) { - return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; - } - ts.tryRemoveExtension = tryRemoveExtension; - function removeExtension(path, extension) { - return path.substring(0, path.length - extension.length); - } - ts.removeExtension = removeExtension; - function changeExtension(path, newExtension) { - return (removeFileExtension(path) + newExtension); - } - ts.changeExtension = changeExtension; - /** - * Takes a string like "jquery-min.4.2.3" and returns "jquery" - */ - function removeMinAndVersionNumbers(fileName) { - // Match a "." or "-" followed by a version number or 'min' at the end of the name - var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; - // The "min" or version may both be present, in either order, so try applying the above twice. - return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); - } - ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers; - function Symbol(flags, name) { - this.flags = flags; - this.escapedName = name; - this.declarations = undefined; - this.valueDeclaration = undefined; - this.id = undefined; - this.mergeId = undefined; - this.parent = undefined; - } - function Type(checker, flags) { - this.flags = flags; - if (Debug.isDebugging) { - this.checker = checker; - } - } - function Signature() { } // tslint:disable-line no-empty - function Node(kind, pos, end) { - this.pos = pos; - this.end = end; - this.kind = kind; - this.id = 0; - this.flags = 0 /* None */; - this.modifierFlagsCache = 0 /* None */; - this.transformFlags = 0 /* None */; - this.parent = undefined; - this.original = undefined; - } - function SourceMapSource(fileName, text, skipTrivia) { - this.fileName = fileName; - this.text = text; - this.skipTrivia = skipTrivia || (function (pos) { return pos; }); - } - ts.objectAllocator = { - getNodeConstructor: function () { return Node; }, - getTokenConstructor: function () { return Node; }, - getIdentifierConstructor: function () { return Node; }, - getSourceFileConstructor: function () { return Node; }, - getSymbolConstructor: function () { return Symbol; }, - getTypeConstructor: function () { return Type; }, - 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 /* None */; - Debug.isDebugging = false; - function shouldAssert(level) { - return Debug.currentAssertionLevel >= level; - } - Debug.shouldAssert = shouldAssert; - function assert(expression, message, verboseDebugInfo, stackCrawlMark) { - if (!expression) { - if (verboseDebugInfo) { - message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo()); - } - fail(message ? "False expression: " + message : "False expression.", stackCrawlMark || assert); - } - } - 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."); - if (Error.captureStackTrace) { - Error.captureStackTrace(e, stackCrawlMark || fail); - } - throw e; - } - Debug.fail = fail; - function assertDefined(value, message) { - assert(value !== undefined && value !== null, message); - return value; - } - Debug.assertDefined = assertDefined; - function assertEachDefined(value, message) { - for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { - var v = value_1[_i]; - assertDefined(v, message); - } - return value; - } - Debug.assertEachDefined = assertEachDefined; - function assertNever(member, message, stackCrawlMark) { - return fail(message || "Illegal value: " + member, stackCrawlMark || assertNever); - } - Debug.assertNever = assertNever; - function getFunctionName(func) { - if (typeof func !== "function") { - return ""; - } - else if (func.hasOwnProperty("name")) { - return func.name; - } - else { - var text = Function.prototype.toString.call(func); - var match = /^function\s+([\w\$]+)\s*\(/.exec(text); - return match ? match[1] : ""; - } - } - Debug.getFunctionName = getFunctionName; - function showSymbol(symbol) { - var symbolFlags = ts.SymbolFlags; - return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + map(symbol.declarations, showSyntaxKind) + " }"; - } - Debug.showSymbol = showSymbol; - function showFlags(flags, flagsEnum) { - var out = []; - for (var pow = 0; pow <= 30; pow++) { - var n = 1 << pow; - if (flags & n) { - out.push(flagsEnum[n]); - } - } - return out.join("|"); - } - function showSyntaxKind(node) { - var syntaxKind = ts.SyntaxKind; - return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); - } - Debug.showSyntaxKind = showSyntaxKind; - })(Debug = ts.Debug || (ts.Debug = {})); - /** Remove an item from an array, moving everything to its right one space left. */ - function orderedRemoveItem(array, item) { - for (var i = 0; i < array.length; i++) { - if (array[i] === item) { - orderedRemoveItemAt(array, i); - return true; - } - } - return false; - } - ts.orderedRemoveItem = orderedRemoveItem; - /** Remove an item by index from an array, moving everything to its right one space left. */ - function orderedRemoveItemAt(array, index) { - // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. - for (var i = index; i < array.length - 1; i++) { - array[i] = array[i + 1]; - } - array.pop(); - } - ts.orderedRemoveItemAt = orderedRemoveItemAt; - function unorderedRemoveItemAt(array, index) { - // Fill in the "hole" left at `index`. - array[index] = array[array.length - 1]; - array.pop(); - } - ts.unorderedRemoveItemAt = unorderedRemoveItemAt; - /** Remove the *first* occurrence of `item` from the array. */ - function unorderedRemoveItem(array, item) { - unorderedRemoveFirstItemWhere(array, function (element) { return element === item; }); - } - ts.unorderedRemoveItem = unorderedRemoveItem; - /** Remove the *first* element satisfying `predicate`. */ - function unorderedRemoveFirstItemWhere(array, predicate) { - for (var i = 0; i < array.length; i++) { - if (predicate(array[i])) { - unorderedRemoveItemAt(array, i); - break; - } - } - } - function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames ? identity : toLowerCase; - } - ts.createGetCanonicalFileName = createGetCanonicalFileName; - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - ts.matchPatternOrExact = matchPatternOrExact; - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - ts.patternText = patternText; - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - ts.matchedText = matchedText; - /** Return the object corresponding to the best pattern to match `candidate`. */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_2 = values; _i < values_2.length; _i++) { - var v = values_2[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - startsWith(candidate, prefix) && - endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; - /** True if an extension is one of the supported TypeScript extensions. */ - function extensionIsTypeScript(ext) { - return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; - } - ts.extensionIsTypeScript = extensionIsTypeScript; - /** - * Gets the extension from a path. - * Path must have a valid extension. - */ - function extensionFromPath(path) { - var ext = tryGetExtensionFromPath(path); - if (ext !== undefined) { - return ext; - } - 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); }); - } - ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - function getAnyExtensionFromPath(path) { - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; - function isCheckJsEnabledForFile(sourceFile, compilerOptions) { - return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; - } - ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; - function and(f, g) { - return function (arg) { return f(arg) && g(arg); }; - } - ts.and = and; - function or(f, g) { - return function (arg) { return f(arg) || g(arg); }; - } - ts.or = or; - function assertTypeIsNever(_) { } // tslint:disable-line no-empty - ts.assertTypeIsNever = assertTypeIsNever; - ts.emptyFileSystemEntries = { - files: ts.emptyArray, - directories: ts.emptyArray - }; - function singleElementArray(t) { - return t === undefined ? undefined : [t]; - } - ts.singleElementArray = singleElementArray; - function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { - unchanged = unchanged || noop; - 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 = comparer(newItem, oldItem); - if (compareResult === -1 /* LessThan */) { - inserted(newItem); - newIndex++; - } - else if (compareResult === 1 /* GreaterThan */) { - deleted(oldItem); - oldIndex++; - } - else { - unchanged(oldItem, newItem); - newIndex++; - oldIndex++; - } - } - while (newIndex < newLen) { - inserted(newItems[newIndex++]); - } - while (oldIndex < oldLen) { - deleted(oldItems[oldIndex++]); - } - } - ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; -})(ts || (ts = {})); -/// var ts; (function (ts) { /** @@ -4546,12 +3578,12 @@ var ts; /* @internal */ ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time function createPollingIntervalBasedLevels(levels) { + var _a; return _a = {}, _a[PollingInterval.Low] = levels.Low, _a[PollingInterval.Medium] = levels.Medium, _a[PollingInterval.High] = levels.High, _a; - var _a; } var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 }; var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels); @@ -4778,47 +3810,80 @@ var ts; */ /*@internal*/ function createRecursiveDirectoryWatcher(host) { + var cache = ts.createMap(); + var callbackCache = ts.createMultiMap(); + var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames); + var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); return createDirectoryWatcher; /** * Create the directory watcher for the dirPath. */ function createDirectoryWatcher(dirName, callback) { - var watcher = host.watchDirectory(dirName, function (fileName) { - // Call the actual callback - callback(fileName); - // Iterate through existing children and update the watches if needed - updateChildWatches(result, callback); - }); - var result = { - close: function () { - watcher.close(); - result.childWatches.forEach(ts.closeFileWatcher); - result = undefined; - }, + var dirPath = toCanonicalFilePath(dirName); + var directoryWatcher = cache.get(dirPath); + if (directoryWatcher) { + directoryWatcher.refCount++; + } + else { + directoryWatcher = { + watcher: host.watchDirectory(dirName, function (fileName) { + // Call the actual callback + callbackCache.forEach(function (callbacks, rootDirName) { + if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) { + callbacks.forEach(function (callback) { return callback(fileName); }); + } + }); + // Iterate through existing children and update the watches if needed + updateChildWatches(dirName, dirPath); + }), + refCount: 1, + childWatches: ts.emptyArray + }; + cache.set(dirPath, directoryWatcher); + updateChildWatches(dirName, dirPath); + } + if (callback) { + callbackCache.add(dirPath, callback); + } + return { dirName: dirName, - childWatches: ts.emptyArray + close: function () { + var directoryWatcher = ts.Debug.assertDefined(cache.get(dirPath)); + if (callback) + callbackCache.remove(dirPath, callback); + directoryWatcher.refCount--; + if (directoryWatcher.refCount) + return; + cache.delete(dirPath); + ts.closeFileWatcherOf(directoryWatcher); + directoryWatcher.childWatches.forEach(ts.closeFileWatcher); + } }; - updateChildWatches(result, callback); - return result; } - function updateChildWatches(watcher, callback) { + function updateChildWatches(dirName, dirPath) { // Iterate through existing children and update the watches if needed - if (watcher) { - watcher.childWatches = watchChildDirectories(watcher.dirName, watcher.childWatches, callback); + var parentWatcher = cache.get(dirPath); + if (parentWatcher) { + parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches); } } /** * Watch the directories in the parentDir */ - function watchChildDirectories(parentDir, existingChildWatches, callback) { + function watchChildDirectories(parentDir, existingChildWatches) { var newChildWatches; - ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? host.getAccessileSortedChildDirectories(parentDir) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return host.filePathComparer(ts.getNormalizedAbsolutePath(child, parentDir), childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); + ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) { + var childFullName = ts.getNormalizedAbsolutePath(child, parentDir); + // Filter our the symbolic link directories since those arent included in recursive watch + // which is same behaviour when recursive: true is passed to fs.watch + return filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined; + }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher); return newChildWatches || ts.emptyArray; /** * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list */ function createAndAddChildDirectoryWatcher(childName) { - var result = createDirectoryWatcher(ts.getNormalizedAbsolutePath(childName, parentDir), callback); + var result = createDirectoryWatcher(childName); addChildDirectoryWatcher(result); } /** @@ -4845,6 +3910,7 @@ var ts; return parseInt(version.substring(1, dot)); } ts.getNodeMajorVersion = getNodeMajorVersion; + // TODO: GH#18217 this is used as if it's certainly defined in many places. // MONACOCHANGE ts.sys = undefined; // END MONACOCHANGE @@ -4859,13 +3925,12 @@ var ts; } })(ts || (ts = {})); // -// generated from './diagnosticInformationMap.generated.ts' by '../../scripts/processDiagnosticMessages.js' -/// +// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ var ts; (function (ts) { - function diag(code, category, key, message) { - return { code: code, category: category, key: key, message: message }; + function diag(code, category, key, message, reportsUnnecessary) { + return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary }; } // tslint:disable-next-line variable-name ts.Diagnostics = { @@ -4875,7 +3940,9 @@ var ts; A_file_cannot_have_a_reference_to_itself: diag(1006, ts.DiagnosticCategory.Error, "A_file_cannot_have_a_reference_to_itself_1006", "A file cannot have a reference to itself."), Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."), Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."), + An_element_access_expression_should_take_an_argument: diag(1011, ts.DiagnosticCategory.Error, "An_element_access_expression_should_take_an_argument_1011", "An element access expression should take an argument."), Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."), + A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma: diag(1013, ts.DiagnosticCategory.Error, "A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma_1013", "A rest parameter or binding pattern may not have a trailing comma."), A_rest_parameter_must_be_last_in_a_parameter_list: diag(1014, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_last_in_a_parameter_list_1014", "A rest parameter must be last in a parameter list."), Parameter_cannot_have_question_mark_and_initializer: diag(1015, ts.DiagnosticCategory.Error, "Parameter_cannot_have_question_mark_and_initializer_1015", "Parameter cannot have question mark and initializer."), A_required_parameter_cannot_follow_an_optional_parameter: diag(1016, ts.DiagnosticCategory.Error, "A_required_parameter_cannot_follow_an_optional_parameter_1016", "A required parameter cannot follow an optional parameter."), @@ -4922,6 +3989,7 @@ var ts; The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise type."), In_ambient_enum_declarations_member_initializer_must_be_constant_expression: diag(1066, ts.DiagnosticCategory.Error, "In_ambient_enum_declarations_member_initializer_must_be_constant_expression_1066", "In ambient enum declarations member initializer must be constant expression."), Unexpected_token_A_constructor_method_accessor_or_property_was_expected: diag(1068, ts.DiagnosticCategory.Error, "Unexpected_token_A_constructor_method_accessor_or_property_was_expected_1068", "Unexpected token. A constructor, method, accessor, or property was expected."), + Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces: diag(1069, ts.DiagnosticCategory.Error, "Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces_1069", "Unexpected token. A type parameter name was expected without curly braces."), _0_modifier_cannot_appear_on_a_type_member: diag(1070, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_type_member_1070", "'{0}' modifier cannot appear on a type member."), _0_modifier_cannot_appear_on_an_index_signature: diag(1071, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_an_index_signature_1071", "'{0}' modifier cannot appear on an index signature."), A_0_modifier_cannot_be_used_with_an_import_declaration: diag(1079, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_import_declaration_1079", "A '{0}' modifier cannot be used with an import declaration."), @@ -4958,7 +4026,6 @@ var ts; An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), Octal_literals_are_not_allowed_in_strict_mode: diag(1121, ts.DiagnosticCategory.Error, "Octal_literals_are_not_allowed_in_strict_mode_1121", "Octal literals are not allowed in strict mode."), - A_tuple_type_element_list_cannot_be_empty: diag(1122, ts.DiagnosticCategory.Error, "A_tuple_type_element_list_cannot_be_empty_1122", "A tuple type element list cannot be empty."), Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."), Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."), Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."), @@ -5078,6 +4145,8 @@ var ts; _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."), A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal: diag(1254, ts.DiagnosticCategory.Error, "A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_1254", "A 'const' initializer in an ambient context must be a string or numeric literal."), A_definite_assignment_assertion_is_not_permitted_in_this_context: diag(1255, ts.DiagnosticCategory.Error, "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255", "A definite assignment assertion '!' is not permitted in this context."), + A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."), + A_required_element_cannot_follow_an_optional_element: diag(1257, ts.DiagnosticCategory.Error, "A_required_element_cannot_follow_an_optional_element_1257", "A required element cannot follow an optional element."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), @@ -5091,7 +4160,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules_1323", "Dynamic import cannot be used when targeting ECMAScript 2015 modules."), + Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5107,6 +4176,10 @@ var ts; An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type: diag(1338, ts.DiagnosticCategory.Error, "infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type_1338", "'infer' declarations are only permitted in the 'extends' clause of a conditional type."), + Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here: diag(1339, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339", "Module '{0}' does not refer to a value, but is used as a value here."), + Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0: diag(1340, ts.DiagnosticCategory.Error, "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0_1340", "Module '{0}' does not refer to a type, but is used as a type here. Did you mean 'typeof import('{0}')'?"), + Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."), + The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_option_1343", "The 'import.meta' meta-property is only allowed using 'ESNext' for the 'target' and 'module' compiler options."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5174,6 +4247,7 @@ var ts; The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access: diag(2364, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access_2364", "The left-hand side of an assignment expression must be a variable or a property access."), Operator_0_cannot_be_applied_to_types_1_and_2: diag(2365, ts.DiagnosticCategory.Error, "Operator_0_cannot_be_applied_to_types_1_and_2_2365", "Operator '{0}' cannot be applied to types '{1}' and '{2}'."), Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined: diag(2366, ts.DiagnosticCategory.Error, "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366", "Function lacks ending return statement and return type does not include 'undefined'."), + This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap: diag(2367, ts.DiagnosticCategory.Error, "This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap_2367", "This condition will always return '{0}' since the types '{1}' and '{2}' have no overlap."), Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."), A_parameter_property_is_only_allowed_in_a_constructor_implementation: diag(2369, ts.DiagnosticCategory.Error, "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369", "A parameter property is only allowed in a constructor implementation."), A_rest_parameter_must_be_of_an_array_type: diag(2370, ts.DiagnosticCategory.Error, "A_rest_parameter_must_be_of_an_array_type_2370", "A rest parameter must be of an array type."), @@ -5212,7 +4286,7 @@ var ts; The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any: diag(2405, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any_2405", "The left-hand side of a 'for...in' statement must be of type 'string' or 'any'."), The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access: diag(2406, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access_2406", "The left-hand side of a 'for...in' statement must be a variable or a property access."), - The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter."), + The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0: diag(2407, ts.DiagnosticCategory.Error, "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_2407", "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type '{0}'."), Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."), Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: diag(2409, ts.DiagnosticCategory.Error, "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", "Return type of constructor signature must be assignable to the instance type of the class."), The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: diag(2410, ts.DiagnosticCategory.Error, "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'."), @@ -5223,6 +4297,7 @@ var ts; Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), + Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1: diag(2418, ts.DiagnosticCategory.Error, "Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1_2418", "Type of computed property's value is '{0}', which is not assignable to type '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), @@ -5286,7 +4361,7 @@ var ts; The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation: diag(2483, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation_2483", "The left-hand side of a 'for...of' statement cannot use a type annotation."), Export_declaration_conflicts_with_exported_declaration_of_0: diag(2484, ts.DiagnosticCategory.Error, "Export_declaration_conflicts_with_exported_declaration_of_0_2484", "Export declaration conflicts with exported declaration of '{0}'."), The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access: diag(2487, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access_2487", "The left-hand side of a 'for...of' statement must be a variable or a property access."), - Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type must have a '[Symbol.iterator]()' method that returns an iterator."), + Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator: diag(2488, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator_2488", "Type '{0}' must have a '[Symbol.iterator]()' method that returns an iterator."), An_iterator_must_have_a_next_method: diag(2489, ts.DiagnosticCategory.Error, "An_iterator_must_have_a_next_method_2489", "An iterator must have a 'next()' method."), The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), @@ -5302,7 +4377,7 @@ var ts; A_rest_element_cannot_contain_a_binding_pattern: diag(2501, ts.DiagnosticCategory.Error, "A_rest_element_cannot_contain_a_binding_pattern_2501", "A rest element cannot contain a binding pattern."), _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: diag(2502, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502", "'{0}' is referenced directly or indirectly in its own type annotation."), Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."), - Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), + Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator: diag(2504, ts.DiagnosticCategory.Error, "Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator_2504", "Type '{0}' must have a '[Symbol.asyncIterator]()' method that returns an async iterator."), A_generator_cannot_have_a_void_type_annotation: diag(2505, ts.DiagnosticCategory.Error, "A_generator_cannot_have_a_void_type_annotation_2505", "A generator cannot have a 'void' type annotation."), _0_is_referenced_directly_or_indirectly_in_its_own_base_expression: diag(2506, ts.DiagnosticCategory.Error, "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506", "'{0}' is referenced directly or indirectly in its own base expression."), Type_0_is_not_a_constructor_function_type: diag(2507, ts.DiagnosticCategory.Error, "Type_0_is_not_a_constructor_function_type_2507", "Type '{0}' is not a constructor function type."), @@ -5366,6 +4441,14 @@ var ts; Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations: diag(2567, ts.DiagnosticCategory.Error, "Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations_2567", "Enum declarations can only merge with namespace or other enum declarations."), + Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2568, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators_2568", "Type '{0}' is not an array type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators: diag(2569, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterati_2569", "Type '{0}' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators."), + Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await: diag(2570, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await_2570", "Property '{0}' does not exist on type '{1}'. Did you forget to use 'await'?"), + Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."), + Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."), + Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."), + A_rest_element_type_must_be_an_array_type: diag(2574, ts.DiagnosticCategory.Error, "A_rest_element_type_must_be_an_array_type_2574", "A rest element type must be an array type."), + No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments: diag(2575, ts.DiagnosticCategory.Error, "No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments_2575", "No overload expects {0} arguments, but overloads do exist that expect either {1} or {2} arguments."), 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."), @@ -5419,7 +4502,7 @@ var ts; _0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible: diag(2692, ts.DiagnosticCategory.Error, "_0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible_2692", "'{0}' is a primitive, but '{1}' is a wrapper object. Prefer using '{0}' when possible."), _0_only_refers_to_a_type_but_is_being_used_as_a_value_here: diag(2693, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693", "'{0}' only refers to a type, but is being used as a value here."), Namespace_0_has_no_exported_member_1: diag(2694, ts.DiagnosticCategory.Error, "Namespace_0_has_no_exported_member_1_2694", "Namespace '{0}' has no exported member '{1}'."), - Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects."), + Left_side_of_comma_operator_is_unused_and_has_no_side_effects: diag(2695, ts.DiagnosticCategory.Error, "Left_side_of_comma_operator_is_unused_and_has_no_side_effects_2695", "Left side of comma operator is unused and has no side effects.", /*reportsUnnecessary*/ true), The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead: diag(2696, ts.DiagnosticCategory.Error, "The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead_2696", "The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?"), An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option: diag(2697, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_in_2697", "An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option."), Spread_types_may_only_be_created_from_object_types: diag(2698, ts.DiagnosticCategory.Error, "Spread_types_may_only_be_created_from_object_types_2698", "Spread types may only be created from object types."), @@ -5449,6 +4532,11 @@ var ts; Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"), + Class_name_cannot_be_Object_when_targeting_ES5_with_module_0: diag(2725, ts.DiagnosticCategory.Error, "Class_name_cannot_be_Object_when_targeting_ES5_with_module_0_2725", "Class name cannot be 'Object' when targeting ES5 with module {0}."), + Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."), + Cannot_find_lib_definition_for_0_Did_you_mean_1: diag(2727, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_Did_you_mean_1_2727", "Cannot find lib definition for '{0}'. Did you mean '{1}'?"), + _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."), + Property_0_is_used_before_its_initialization: diag(2729, ts.DiagnosticCategory.Error, "Property_0_is_used_before_its_initialization_2729", "Property '{0}' is used before its initialization."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5560,6 +4648,10 @@ var ts; Substitutions_for_pattern_0_shouldn_t_be_an_empty_array: diag(5066, ts.DiagnosticCategory.Error, "Substitutions_for_pattern_0_shouldn_t_be_an_empty_array_5066", "Substitutions for pattern '{0}' shouldn't be an empty array."), Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(5067, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name_5067", "Invalid value for 'jsxFactory'. '{0}' is not a valid identifier or qualified-name."), Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig: diag(5068, ts.DiagnosticCategory.Error, "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068", "Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig."), + Option_0_cannot_be_specified_without_specifying_option_1_or_option_2: diag(5069, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_without_specifying_option_1_or_option_2_5069", "Option '{0}' cannot be specified without specifying option '{1}' or option '{2}'."), + Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy: diag(5070, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy_5070", "Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy."), + Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs: diag(5071, ts.DiagnosticCategory.Error, "Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_5071", "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'."), + Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6000, ts.DiagnosticCategory.Message, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, ts.DiagnosticCategory.Message, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."), @@ -5595,7 +4687,6 @@ var ts; DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), - Compilation_complete_Watching_for_file_changes: diag(6042, ts.DiagnosticCategory.Message, "Compilation_complete_Watching_for_file_changes_6042", "Compilation complete. Watching for file changes."), Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), @@ -5680,12 +4771,12 @@ var ts; Resolving_real_path_for_0_result_1: diag(6130, ts.DiagnosticCategory.Message, "Resolving_real_path_for_0_result_1_6130", "Resolving real path for '{0}', result '{1}'."), Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system: diag(6131, ts.DiagnosticCategory.Error, "Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system_6131", "Cannot compile modules using option '{0}' unless the '--module' flag is 'amd' or 'system'."), File_name_0_has_a_1_extension_stripping_it: diag(6132, ts.DiagnosticCategory.Message, "File_name_0_has_a_1_extension_stripping_it_6132", "File name '{0}' has a '{1}' extension - stripping it."), - _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read."), + _0_is_declared_but_its_value_is_never_read: diag(6133, ts.DiagnosticCategory.Error, "_0_is_declared_but_its_value_is_never_read_6133", "'{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."), Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."), The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: diag(6136, ts.DiagnosticCategory.Message, "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", "The maximum dependency depth to search under node_modules and load JavaScript files."), Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1: diag(6137, ts.DiagnosticCategory.Error, "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137", "Cannot import type declaration files. Consider importing '{0}' instead of '{1}'."), - Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read."), + Property_0_is_declared_but_its_value_is_never_read: diag(6138, ts.DiagnosticCategory.Error, "Property_0_is_declared_but_its_value_is_never_read_6138", "Property '{0}' is declared but its value is never read.", /*reportsUnnecessary*/ true), Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."), Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: diag(6140, ts.DiagnosticCategory.Error, "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'."), Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, ts.DiagnosticCategory.Message, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", "Parse in strict mode and emit \"use strict\" for each source file."), @@ -5738,7 +4829,51 @@ var ts; Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen: diag(6191, ts.DiagnosticCategory.Message, "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191", "Whether to keep outdated console output in watch mode instead of clearing the screen."), - All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused."), + All_imports_in_import_declaration_are_unused: diag(6192, ts.DiagnosticCategory.Error, "All_imports_in_import_declaration_are_unused_6192", "All imports in import declaration are unused.", /*reportsUnnecessary*/ true), + Found_1_error_Watching_for_file_changes: diag(6193, ts.DiagnosticCategory.Message, "Found_1_error_Watching_for_file_changes_6193", "Found 1 error. Watching for file changes."), + Found_0_errors_Watching_for_file_changes: diag(6194, ts.DiagnosticCategory.Message, "Found_0_errors_Watching_for_file_changes_6194", "Found {0} errors. Watching for file changes."), + Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols: diag(6195, ts.DiagnosticCategory.Message, "Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols_6195", "Resolve 'keyof' to string valued property names only (no numbers or symbols)."), + _0_is_declared_but_never_used: diag(6196, ts.DiagnosticCategory.Error, "_0_is_declared_but_never_used_6196", "'{0}' is declared but never used.", /*reportsUnnecessary*/ true), + Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"), + All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true), + All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true), + Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0: diag(6200, ts.DiagnosticCategory.Error, "Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0_6200", "Definitions of the following identifiers conflict with those in another file: {0}"), + Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."), + _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."), + and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."), + Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"), + Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"), + Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0: diag(6202, ts.DiagnosticCategory.Error, "Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0_6202", "Project references may not form a circular graph. Cycle detected: {0}"), + Composite_projects_may_not_disable_declaration_emit: diag(6304, ts.DiagnosticCategory.Error, "Composite_projects_may_not_disable_declaration_emit_6304", "Composite projects may not disable declaration emit."), + Output_file_0_has_not_been_built_from_source_file_1: diag(6305, ts.DiagnosticCategory.Error, "Output_file_0_has_not_been_built_from_source_file_1_6305", "Output file '{0}' has not been built from source file '{1}'."), + Referenced_project_0_must_have_setting_composite_Colon_true: diag(6306, ts.DiagnosticCategory.Error, "Referenced_project_0_must_have_setting_composite_Colon_true_6306", "Referenced project '{0}' must have setting \"composite\": true."), + File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern: diag(6307, ts.DiagnosticCategory.Error, "File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern_6307", "File '{0}' is not in project file list. Projects must list all files or use an 'include' pattern."), + Cannot_prepend_project_0_because_it_does_not_have_outFile_set: diag(6308, ts.DiagnosticCategory.Error, "Cannot_prepend_project_0_because_it_does_not_have_outFile_set_6308", "Cannot prepend project '{0}' because it does not have 'outFile' set"), + Output_file_0_from_project_1_does_not_exist: diag(6309, ts.DiagnosticCategory.Error, "Output_file_0_from_project_1_does_not_exist_6309", "Output file '{0}' from project '{1}' does not exist"), + Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2: diag(6350, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2_6350", "Project '{0}' is out of date because oldest output '{1}' is older than newest input '{2}'"), + Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2: diag(6351, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2_6351", "Project '{0}' is up to date because newest input '{1}' is older than oldest output '{2}'"), + Project_0_is_out_of_date_because_output_file_1_does_not_exist: diag(6352, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_output_file_1_does_not_exist_6352", "Project '{0}' is out of date because output file '{1}' does not exist"), + Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date: diag(6353, ts.DiagnosticCategory.Message, "Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date_6353", "Project '{0}' is out of date because its dependency '{1}' is out of date"), + Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies: diag(6354, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies_6354", "Project '{0}' is up to date with .d.ts files from its dependencies"), + Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"), + A_non_dry_build_would_delete_the_following_files_Colon_0: diag(6356, ts.DiagnosticCategory.Message, "A_non_dry_build_would_delete_the_following_files_Colon_0_6356", "A non-dry build would delete the following files: {0}"), + A_non_dry_build_would_build_project_0: diag(6357, ts.DiagnosticCategory.Message, "A_non_dry_build_would_build_project_0_6357", "A non-dry build would build project '{0}'"), + Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."), + Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."), + delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"), + Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"), + Skipping_build_of_project_0_because_its_dependency_1_has_errors: diag(6362, ts.DiagnosticCategory.Message, "Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362", "Skipping build of project '{0}' because its dependency '{1}' has errors"), + Project_0_can_t_be_built_because_its_dependency_1_has_errors: diag(6363, ts.DiagnosticCategory.Message, "Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363", "Project '{0}' can't be built because its dependency '{1}' has errors"), + Build_one_or_more_projects_and_their_dependencies_if_out_of_date: diag(6364, ts.DiagnosticCategory.Message, "Build_one_or_more_projects_and_their_dependencies_if_out_of_date_6364", "Build one or more projects and their dependencies, if out of date"), + Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"), + Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"), + Show_what_would_be_built_or_deleted_if_specified_with_clean: diag(6367, ts.DiagnosticCategory.Message, "Show_what_would_be_built_or_deleted_if_specified_with_clean_6367", "Show what would be built (or deleted, if specified with '--clean')"), + Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), + Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), + Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Skipping_clean_because_not_all_projects_could_be_located: diag(6371, ts.DiagnosticCategory.Error, "Skipping_clean_because_not_all_projects_could_be_located_6371", "Skipping clean because not all projects could be located"), + The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), + The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), Variable_0_implicitly_has_an_1_type: diag(7005, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_an_1_type_7005", "Variable '{0}' implicitly has an '{1}' type."), Parameter_0_implicitly_has_an_1_type: diag(7006, ts.DiagnosticCategory.Error, "Parameter_0_implicitly_has_an_1_type_7006", "Parameter '{0}' implicitly has an '{1}' type."), Member_0_implicitly_has_an_1_type: diag(7008, ts.DiagnosticCategory.Error, "Member_0_implicitly_has_an_1_type_7008", "Member '{0}' implicitly has an '{1}' type."), @@ -5757,8 +4892,8 @@ var ts; 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: diag(7024, ts.DiagnosticCategory.Error, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "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."), Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: diag(7025, ts.DiagnosticCategory.Error, "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), - Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected."), - Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label."), + Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true), + Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true), Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."), Not_all_code_paths_return_a_value: diag(7030, ts.DiagnosticCategory.Error, "Not_all_code_paths_return_a_value_7030", "Not all code paths return a value."), Binding_element_0_implicitly_has_an_1_type: diag(7031, ts.DiagnosticCategory.Error, "Binding_element_0_implicitly_has_an_1_type_7031", "Binding element '{0}' implicitly has an '{1}' type."), @@ -5768,8 +4903,9 @@ var ts; Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), - A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), + Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead: diag(7038, ts.DiagnosticCategory.Message, "Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cau_7038", "Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead."), Mapped_object_type_implicitly_has_an_any_template_type: diag(7039, ts.DiagnosticCategory.Error, "Mapped_object_type_implicitly_has_an_any_template_type_7039", "Mapped object type implicitly has an 'any' template type."), + If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0: diag(7040, ts.DiagnosticCategory.Error, "If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_S_7040", "If the '{0}' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/{0}`"), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5799,6 +4935,7 @@ var ts; Expected_0_1_type_arguments_provide_these_with_an_extends_tag: diag(8027, ts.DiagnosticCategory.Error, "Expected_0_1_type_arguments_provide_these_with_an_extends_tag_8027", "Expected {0}-{1} type arguments; provide these with an '@extends' tag."), JSDoc_may_only_appear_in_the_last_parameter_of_a_signature: diag(8028, ts.DiagnosticCategory.Error, "JSDoc_may_only_appear_in_the_last_parameter_of_a_signature_8028", "JSDoc '...' may only appear in the last parameter of a signature."), JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), + The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -5828,6 +4965,7 @@ var ts; This_constructor_function_may_be_converted_to_a_class_declaration: diag(80002, ts.DiagnosticCategory.Suggestion, "This_constructor_function_may_be_converted_to_a_class_declaration_80002", "This constructor function may be converted to a class declaration."), Import_may_be_converted_to_a_default_import: diag(80003, ts.DiagnosticCategory.Suggestion, "Import_may_be_converted_to_a_default_import_80003", "Import may be converted to a default import."), JSDoc_types_may_be_moved_to_TypeScript_types: diag(80004, ts.DiagnosticCategory.Suggestion, "JSDoc_types_may_be_moved_to_TypeScript_types_80004", "JSDoc types may be moved to TypeScript types."), + require_call_may_be_converted_to_an_import: diag(80005, ts.DiagnosticCategory.Suggestion, "require_call_may_be_converted_to_an_import_80005", "'require' call may be converted to an import."), Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), @@ -5835,7 +4973,9 @@ var ts; Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), - Add_this_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_this_to_unresolved_variable_90008", "Add 'this.' to unresolved variable"), + Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"), + Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"), + Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), @@ -5872,10 +5012,51 @@ var ts; Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"), Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"), Add_definite_assignment_assertion_to_property_0: diag(95020, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertion_to_property_0_95020", "Add definite assignment assertion to property '{0}'"), + Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"), + Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"), + Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"), + Prefix_all_unused_declarations_with_where_possible: diag(95025, ts.DiagnosticCategory.Message, "Prefix_all_unused_declarations_with_where_possible_95025", "Prefix all unused declarations with '_' where possible"), + Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"), + Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"), + Add_definite_assignment_assertions_to_all_uninitialized_properties: diag(95028, ts.DiagnosticCategory.Message, "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028", "Add definite assignment assertions to all uninitialized properties"), + Add_undefined_type_to_all_uninitialized_properties: diag(95029, ts.DiagnosticCategory.Message, "Add_undefined_type_to_all_uninitialized_properties_95029", "Add undefined type to all uninitialized properties"), + Change_all_jsdoc_style_types_to_TypeScript: diag(95030, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_95030", "Change all jsdoc-style types to TypeScript"), + Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types: diag(95031, ts.DiagnosticCategory.Message, "Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types_95031", "Change all jsdoc-style types to TypeScript (and add '| undefined' to nullable types)"), + Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"), + Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"), + Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"), + Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"), + Make_all_super_calls_the_first_statement_in_their_constructor: diag(95036, ts.DiagnosticCategory.Message, "Make_all_super_calls_the_first_statement_in_their_constructor_95036", "Make all 'super()' calls the first statement in their constructor"), + Add_qualifier_to_all_unresolved_variables_matching_a_member_name: diag(95037, ts.DiagnosticCategory.Message, "Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037", "Add qualifier to all unresolved variables matching a member name"), + Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"), + Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"), + Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"), + Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"), + Add_ts_ignore_to_all_error_messages: diag(95042, ts.DiagnosticCategory.Message, "Add_ts_ignore_to_all_error_messages_95042", "Add '@ts-ignore' to all error messages"), + Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"), + Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"), + Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"), + Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"), + Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"), + Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"), + Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"), + Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"), + Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"), + Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"), + Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"), + Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"), + Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"), + Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"), + Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"), + Add_or_remove_braces_in_an_arrow_function: diag(95058, ts.DiagnosticCategory.Message, "Add_or_remove_braces_in_an_arrow_function_95058", "Add or remove braces in an arrow function"), + Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"), + Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"), + Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"), + Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"), + Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"), + Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"), }; })(ts || (ts = {})); -/// -/// var ts; (function (ts) { /* @internal */ @@ -5912,7 +5093,7 @@ var ts; "false": 86 /* FalseKeyword */, "finally": 87 /* FinallyKeyword */, "for": 88 /* ForKeyword */, - "from": 142 /* FromKeyword */, + "from": 143 /* FromKeyword */, "function": 89 /* FunctionKeyword */, "get": 125 /* GetKeyword */, "if": 90 /* IfKeyword */, @@ -5938,7 +5119,7 @@ var ts; "public": 114 /* PublicKeyword */, "readonly": 132 /* ReadonlyKeyword */, "require": 133 /* RequireKeyword */, - "global": 143 /* GlobalKeyword */, + "global": 144 /* GlobalKeyword */, "return": 96 /* ReturnKeyword */, "set": 136 /* SetKeyword */, "static": 115 /* StaticKeyword */, @@ -5954,6 +5135,7 @@ var ts; "typeof": 103 /* TypeOfKeyword */, "undefined": 140 /* UndefinedKeyword */, "unique": 141 /* UniqueKeyword */, + "unknown": 142 /* UnknownKeyword */, "var": 104 /* VarKeyword */, "void": 105 /* VoidKeyword */, "while": 106 /* WhileKeyword */, @@ -5961,7 +5143,7 @@ var ts; "yield": 116 /* YieldKeyword */, "async": 120 /* AsyncKeyword */, "await": 121 /* AwaitKeyword */, - "of": 144 /* OfKeyword */, + "of": 145 /* OfKeyword */, "{": 17 /* OpenBraceToken */, "}": 18 /* CloseBraceToken */, "(": 19 /* OpenParenToken */, @@ -6489,7 +5671,6 @@ var ts; // If we are not reducing and we have a truthy result, return it. return accumulator; } - hasPendingCommentRange = false; } pendingPos = startPos; pendingEnd = pos; @@ -6581,8 +5762,9 @@ var ts; } ts.isIdentifierText = isIdentifierText; // Creates a scanner over a (possibly unspecified) range of a piece of text. - function createScanner(languageVersion, skipTrivia, languageVariant, text, onError, start, length) { + function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) { if (languageVariant === void 0) { languageVariant = 0 /* Standard */; } + var text = textInitial; // Current position (end position of text of current token) var pos; // end of text @@ -7038,7 +6220,7 @@ var ts; var isPreviousTokenSeparator = false; while (true) { var ch = text.charCodeAt(pos); - // Numeric seperators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator + // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -7625,11 +6807,10 @@ var ts; } } function scanJSDocToken() { + startPos = tokenPos = pos; if (pos >= end) { return token = 1 /* EndOfFileToken */; } - startPos = pos; - tokenPos = pos; var ch = text.charCodeAt(pos); pos++; switch (ch) { @@ -7664,6 +6845,13 @@ var ts; return token = 26 /* CommaToken */; case 46 /* dot */: return token = 23 /* DotToken */; + case 96 /* backtick */: + while (pos < end && text.charCodeAt(pos) !== 96 /* backtick */) { + pos++; + } + tokenValue = text.substring(tokenPos + 1, pos); + pos++; + return token = 13 /* NoSubstitutionTemplateLiteral */; } if (isIdentifierStart(ch, 6 /* Latest */)) { while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { @@ -7750,14 +6938,29 @@ var ts; } ts.createScanner = createScanner; })(ts || (ts = {})); -/// -/* @internal */ +/** Non-internal stuff goes here */ var ts; (function (ts) { + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + // Update: We also consider a path like `C:\foo.ts` "relative" because we do not search for it in `node_modules` or treat it as an ambient module. + return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function sortAndDeduplicateDiagnostics(diagnostics) { + return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics); + } + ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; ts.externalHelpersModuleNameText = "tslib"; + ts.defaultMaximumTruncationLength = 160; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { @@ -7771,6 +6974,26 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; + /** Create a new escaped identifier map. */ + function createUnderscoreEscapedMap() { + return new ts.MapCtr(); + } + ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; + function hasEntries(map) { + return !!map && !!map.size; + } + ts.hasEntries = hasEntries; + function createSymbolTable(symbols) { + var result = ts.createMap(); + if (symbols) { + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; + result.set(symbol.escapedName, symbol); + } + } + return result; + } + ts.createSymbolTable = createSymbolTable; var stringWriter = createSingleLineStringWriter(); function createSingleLineStringWriter() { var str = ""; @@ -7806,6 +7029,87 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) + ? ts.normalizePath(fileName) + : ts.getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function changesAffectModuleResolution(oldOptions, newOptions) { + return !oldOptions || + (oldOptions.module !== newOptions.module) || + (oldOptions.moduleResolution !== newOptions.moduleResolution) || + (oldOptions.noResolve !== newOptions.noResolve) || + (oldOptions.target !== newOptions.target) || + (oldOptions.noLib !== newOptions.noLib) || + (oldOptions.jsx !== newOptions.jsx) || + (oldOptions.allowJs !== newOptions.allowJs) || + (oldOptions.rootDir !== newOptions.rootDir) || + (oldOptions.configFilePath !== newOptions.configFilePath) || + (oldOptions.baseUrl !== newOptions.baseUrl) || + (oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, newOptions.lib) || + !ts.arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) || + !ts.arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths); + } + ts.changesAffectModuleResolution = changesAffectModuleResolution; + function findAncestor(node, callback) { + while (node) { + var result = callback(node); + if (result === "quit") { + return undefined; + } + else if (result) { + return node; + } + node = node.parent; + } + return undefined; + } + ts.findAncestor = findAncestor; + function forEachEntry(map, callback) { + var _a; + var iterator = map.entries(); + for (var _b = iterator.next(), pair = _b.value, done = _b.done; !done; _a = iterator.next(), pair = _a.value, done = _a.done, _a) { + var key = pair[0], value = pair[1]; + var result = callback(value, key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachEntry = forEachEntry; + function forEachKey(map, callback) { + var _a; + var iterator = map.keys(); + for (var _b = iterator.next(), key = _b.value, done = _b.done; !done; _a = iterator.next(), key = _a.value, done = _a.done, _a) { + var result = callback(key); + if (result) { + return result; + } + } + return undefined; + } + ts.forEachKey = forEachKey; + function copyEntries(source, target) { + source.forEach(function (value, key) { + target.set(key, value); + }); + } + ts.copyEntries = copyEntries; + function arrayToSet(array, makeKey) { + return ts.arrayToMap(array, makeKey || (function (s) { return s; }), function () { return true; }); + } + ts.arrayToSet = arrayToSet; + function cloneMap(map) { + var clone = ts.createMap(); + copyEntries(map, clone); + return clone; + } + ts.cloneMap = cloneMap; function usingSingleLineStringWriter(action) { var oldString = stringWriter.getText(); try { @@ -7849,7 +7153,7 @@ var ts; } ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo; function packageIdIsEqual(a, b) { - return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; + return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } function packageIdToString(_a) { var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; @@ -7900,7 +7204,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 272 /* SourceFile */) { + while (node && node.kind !== 277 /* SourceFile */) { node = node.parent; } return node; @@ -7908,11 +7212,11 @@ var ts; ts.getSourceFileOfNode = getSourceFileOfNode; function isStatementWithLocals(node) { switch (node.kind) { - case 211 /* Block */: - case 239 /* CaseBlock */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return true; } return false; @@ -7956,6 +7260,14 @@ var ts; } } ts.getEndLinePosition = getEndLinePosition; + /** + * Returns a value indicating whether a name is unique globally or within the current file. + * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. + */ + function isFileLevelUniqueName(sourceFile, name, hasGlobalName) { + return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name); + } + ts.isFileLevelUniqueName = isFileLevelUniqueName; // Returns true if this node is missing from the actual source code. A 'missing' node is different // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes // in the tree), it is definitely missing. However, a node may be defined, but still be @@ -7979,6 +7291,23 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function addStatementsAfterPrologue(to, from) { + if (from === undefined || from.length === 0) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice.apply(to, [statementIndex, 0].concat(from)); + return to; + } + ts.addStatementsAfterPrologue = addStatementsAfterPrologue; /** * Determine if the given comment is a triple-slash * @@ -8000,9 +7329,9 @@ var ts; return false; } ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment; - function isPinnedComment(text, comment) { - return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + function isPinnedComment(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 33 /* exclamation */; } ts.isPinnedComment = isPinnedComment; function getTokenPosOfNode(node, sourceFile, includeJsDoc) { @@ -8021,7 +7350,7 @@ var ts; // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === 293 /* SyntaxList */ && node._children.length > 0) { + if (node.kind === 303 /* SyntaxList */ && node._children.length > 0) { return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); @@ -8068,7 +7397,7 @@ var ts; */ function getEmitFlags(node) { var emitNode = node.emitNode; - return emitNode && emitNode.flags; + return emitNode && emitNode.flags || 0; } ts.getEmitFlags = getEmitFlags; function getLiteralText(node, sourceFile) { @@ -8102,7 +7431,7 @@ var ts; case 12 /* RegularExpressionLiteral */: return node.text; } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); + return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); } ts.getLiteralText = getLiteralText; function getTextOfConstantValue(value) { @@ -8114,14 +7443,6 @@ var ts; return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier); } ts.escapeLeadingUnderscores = escapeLeadingUnderscores; - /** - * @deprecated Use `id.escapedText` to get the escaped text of an Identifier. - * @param identifier The identifier to escape - */ - function escapeIdentifier(identifier) { - return identifier; - } - ts.escapeIdentifier = escapeIdentifier; // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores function makeIdentifierFromModuleName(moduleName) { @@ -8135,7 +7456,7 @@ var ts; ts.isBlockOrCatchScoped = isBlockOrCatchScoped; function isCatchClauseVariableDeclarationOrBindingElement(declaration) { var node = getRootDeclaration(declaration); - return node.kind === 230 /* VariableDeclaration */ && node.parent.kind === 267 /* CatchClause */; + return node.kind === 235 /* VariableDeclaration */ && node.parent.kind === 272 /* CatchClause */; } ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement; function isAmbientModule(node) { @@ -8150,6 +7471,16 @@ var ts; return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule; + /** + * An effective module (namespace) declaration is either + * 1. An actual declaration: namespace X { ... } + * 2. A Javascript declaration, which is: + * An identifier in a nested property access expression: Y in `X.Y.Z = { ... }` + */ + function isEffectiveModuleDeclaration(node) { + return ts.isModuleDeclaration(node) || ts.isIdentifier(node); + } + ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration; /** Given a symbol for a module, checks that it is a shorthand ambient module. */ function isShorthandAmbientModuleSymbol(moduleSymbol) { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -8157,11 +7488,11 @@ var ts; ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol; function isShorthandAmbientModule(node) { // The only kind of module that can be missing a body is a shorthand ambient module. - return node && node.kind === 237 /* ModuleDeclaration */ && (!node.body); + return node && node.kind === 242 /* ModuleDeclaration */ && (!node.body); } function isBlockScopedContainerTopLevel(node) { - return node.kind === 272 /* SourceFile */ || - node.kind === 237 /* ModuleDeclaration */ || + return node.kind === 277 /* SourceFile */ || + node.kind === 242 /* ModuleDeclaration */ || ts.isFunctionLike(node); } ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel; @@ -8178,9 +7509,9 @@ var ts; // - defined in the top level scope and source file is an external module // - defined inside ambient module declaration located in the top level scope and source file not an external module switch (node.parent.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node.parent); - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent); } return false; @@ -8192,50 +7523,53 @@ var ts; ts.isEffectiveExternalModule = isEffectiveExternalModule; function isBlockScope(node, parentNode) { switch (node.kind) { - case 272 /* SourceFile */: - case 239 /* CaseBlock */: - case 267 /* CatchClause */: - case 237 /* ModuleDeclaration */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 272 /* CatchClause */: + case 242 /* ModuleDeclaration */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; - case 211 /* Block */: + case 216 /* Block */: // function block is not considered block-scope container // see comment in binder.ts: bind(...), case for SyntaxKind.Block - return parentNode && !ts.isFunctionLike(parentNode); + return !ts.isFunctionLike(parentNode); } return false; } ts.isBlockScope = isBlockScope; function isDeclarationWithTypeParameters(node) { switch (node.kind) { - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 280 /* JSDocFunctionType */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 290 /* JSDocTemplateTag */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 287 /* JSDocFunctionType */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 300 /* JSDocTemplateTag */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + case 291 /* JSDocSignature */: return true; default: ts.assertTypeIsNever(node); @@ -8245,31 +7579,46 @@ var ts; ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters; function isAnyImportSyntax(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: return true; default: return false; } } ts.isAnyImportSyntax = isAnyImportSyntax; + function isLateVisibilityPaintedStatement(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 217 /* VariableStatement */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + return true; + default: + return false; + } + } + ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement; + function isAnyImportOrReExport(node) { + return isAnyImportSyntax(node) || ts.isExportDeclaration(node); + } + ts.isAnyImportOrReExport = isAnyImportOrReExport; // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. function getEnclosingBlockScopeContainer(node) { - var current = node.parent; - while (current) { - if (isBlockScope(current, current.parent)) { - return current; - } - current = current.parent; - } + return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); }); } ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer; // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. function declarationNameToString(name) { - return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); + return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } ts.declarationNameToString = declarationNameToString; function getNameFromIndexInfo(info) { @@ -8283,8 +7632,8 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return escapeLeadingUnderscores(name.text); - case 146 /* ComputedPropertyName */: - return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; + case 147 /* ComputedPropertyName */: + return isStringOrNumericLiteral(name.expression) ? escapeLeadingUnderscores(name.expression.text) : undefined; // TODO: GH#18217 Almost all uses of this assume the result to be defined! default: ts.Debug.assertNever(name); } @@ -8294,10 +7643,12 @@ var ts; switch (name.kind) { case 71 /* Identifier */: return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name); - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return entityNameToString(name.left) + "." + entityNameToString(name.right); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return entityNameToString(name.expression) + "." + entityNameToString(name.name); + default: + throw ts.Debug.assertNever(name); } } ts.entityNameToString = entityNameToString; @@ -8316,12 +7667,7 @@ var ts; return ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile; - function createDiagnosticForNodeSpan(sourceFile, startNode, endNode, message, arg0, arg1, arg2, arg3) { - var start = ts.skipTrivia(sourceFile.text, startNode.pos); - return ts.createFileDiagnostic(sourceFile, start, endNode.end - start, message, arg0, arg1, arg2, arg3); - } - ts.createDiagnosticForNodeSpan = createDiagnosticForNodeSpan; - function createDiagnosticForNodeFromMessageChain(node, messageChain) { + function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) { var sourceFile = getSourceFileOfNode(node); var span = getErrorSpanForNode(sourceFile, node); return { @@ -8330,7 +7676,8 @@ var ts; length: span.length, code: messageChain.code, category: messageChain.category, - messageText: messageChain.next ? messageChain : messageChain.messageText + messageText: messageChain.next ? messageChain : messageChain.messageText, + relatedInformation: relatedInformation }; } ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain; @@ -8343,7 +7690,7 @@ var ts; ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition; function getErrorSpanForArrowFunction(sourceFile, node) { var pos = ts.skipTrivia(sourceFile.text, node.pos); - if (node.body && node.body.kind === 211 /* Block */) { + if (node.body && node.body.kind === 216 /* Block */) { var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line; var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line; if (startLine < endLine) { @@ -8357,7 +7704,7 @@ var ts; function getErrorSpanForNode(sourceFile, node) { var errorNode = node; switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false); if (pos_1 === sourceFile.text.length) { // file is empty - return span for the beginning of the file @@ -8366,23 +7713,25 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, pos_1); // This list is a work in progress. Add missing node kinds to improve their error // spans. - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 235 /* TypeAliasDeclaration */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 240 /* TypeAliasDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: errorNode = node.name; break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); } if (errorNode === undefined) { @@ -8410,29 +7759,36 @@ var ts; return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule; - function isConstEnumDeclaration(node) { - return node.kind === 236 /* EnumDeclaration */ && isConst(node); + function isJsonSourceFile(file) { + return file.scriptKind === 6 /* JSON */; } - ts.isConstEnumDeclaration = isConstEnumDeclaration; - function isConst(node) { - return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */) - || !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); + ts.isJsonSourceFile = isJsonSourceFile; + function isEnumConst(node) { + return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */); } - ts.isConst = isConst; + ts.isEnumConst = isEnumConst; + function isVarConst(node) { + return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */); + } + ts.isVarConst = isVarConst; function isLet(node) { return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; function isSuperCall(n) { - return n.kind === 185 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 97 /* SuperKeyword */; } ts.isSuperCall = isSuperCall; function isImportCall(n) { - return n.kind === 185 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; + return n.kind === 189 /* CallExpression */ && n.expression.kind === 91 /* ImportKeyword */; } ts.isImportCall = isImportCall; + function isLiteralImportTypeNode(n) { + return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); + } + ts.isLiteralImportTypeNode = isLiteralImportTypeNode; function isPrologueDirective(node) { - return node.kind === 214 /* ExpressionStatement */ + return node.kind === 219 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; @@ -8441,11 +7797,11 @@ var ts; } ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode; function getJSDocCommentRanges(node, text) { - var commentRanges = (node.kind === 148 /* Parameter */ || - node.kind === 147 /* TypeParameter */ || - node.kind === 190 /* FunctionExpression */ || - node.kind === 191 /* ArrowFunction */ || - node.kind === 189 /* ParenthesizedExpression */) ? + var commentRanges = (node.kind === 149 /* Parameter */ || + node.kind === 148 /* TypeParameter */ || + node.kind === 194 /* FunctionExpression */ || + node.kind === 195 /* ArrowFunction */ || + node.kind === 193 /* ParenthesizedExpression */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -8461,11 +7817,12 @@ var ts; ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; var defaultLibReferenceRegEx = /^(\/\/\/\s*/; function isPartOfTypeNode(node) { - if (160 /* FirstTypeNode */ <= node.kind && node.kind <= 177 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= node.kind && node.kind <= 181 /* LastTypeNode */) { return true; } switch (node.kind) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 134 /* NumberKeyword */: case 137 /* StringKeyword */: case 122 /* BooleanKeyword */: @@ -8474,72 +7831,76 @@ var ts; case 131 /* NeverKeyword */: return true; case 105 /* VoidKeyword */: - return node.parent.kind !== 194 /* VoidExpression */; - case 205 /* ExpressionWithTypeArguments */: + return node.parent.kind !== 198 /* VoidExpression */; + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(node); - case 147 /* TypeParameter */: - return node.parent.kind === 176 /* MappedType */ || node.parent.kind === 171 /* InferType */; + case 148 /* TypeParameter */: + return node.parent.kind === 179 /* MappedType */ || node.parent.kind === 174 /* InferType */; // Identifiers and qualified names may be type nodes, depending on their context. Climb // above them to find the lowest container case 71 /* Identifier */: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) { + if (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node) { + else if (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier - ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 145 /* QualifiedName */ || node.kind === 183 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + ts.Debug.assert(node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */ || node.kind === 187 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); // falls through - case 145 /* QualifiedName */: - case 183 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: + case 146 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 99 /* ThisKeyword */: { var parent = node.parent; - if (parent.kind === 164 /* TypeQuery */) { + if (parent.kind === 165 /* TypeQuery */) { return false; } + if (parent.kind === 181 /* ImportType */) { + return !parent.isTypeOf; + } // Do not recursively call isPartOfTypeNode on the parent. In the example: // // let a: A.B.C; // // Calling isPartOfTypeNode would consider the qualified name A.B a type node. // Only C and A.B.C are type nodes. - if (160 /* FirstTypeNode */ <= parent.kind && parent.kind <= 177 /* LastTypeNode */) { + if (161 /* FirstTypeNode */ <= parent.kind && parent.kind <= 181 /* LastTypeNode */) { return true; } switch (parent.kind) { - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return !isExpressionWithTypeArgumentsInClassExtendsClause(parent); - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return node === parent.constraint; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 148 /* Parameter */: - case 230 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 149 /* Parameter */: + case 235 /* VariableDeclaration */: return node === parent.type; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return node === parent.type; - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return node === parent.type; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return node === parent.type; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return ts.contains(parent.typeArguments, node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; } + } } return false; } @@ -8560,23 +7921,23 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitor(node); - case 239 /* CaseBlock */: - case 211 /* Block */: - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 224 /* WithStatement */: - case 225 /* SwitchStatement */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 226 /* LabeledStatement */: - case 228 /* TryStatement */: - case 267 /* CatchClause */: + case 244 /* CaseBlock */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return ts.forEachChild(node, traverse); } } @@ -8586,26 +7947,26 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: visitor(node); var operand = node.expression; if (operand) { traverse(operand); } return; - case 236 /* EnumDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // These are not allowed inside a generator now, but eventually they may be allowed // as local types. Regardless, any yield statements contained within them should be // skipped in this traversal. return; default: if (ts.isFunctionLike(node)) { - if (node.name && node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. traverse(node.name.expression); @@ -8628,10 +7989,10 @@ var ts; * @param node The type node. */ function getRestParameterElementType(node) { - if (node && node.kind === 166 /* ArrayType */) { + if (node && node.kind === 167 /* ArrayType */) { return node.elementType; } - else if (node && node.kind === 161 /* TypeReference */) { + else if (node && node.kind === 162 /* TypeReference */) { return ts.singleOrUndefined(node.typeArguments); } else { @@ -8641,12 +8002,12 @@ var ts; ts.getRestParameterElementType = getRestParameterElementType; function getMembersOfDeclaration(node) { switch (node.kind) { - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 165 /* TypeLiteral */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 166 /* TypeLiteral */: return node.members; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return node.properties; } } @@ -8654,40 +8015,44 @@ var ts; function isVariableLike(node) { if (node) { switch (node.kind) { - case 180 /* BindingElement */: - case 271 /* EnumMember */: - case 148 /* Parameter */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 269 /* ShorthandPropertyAssignment */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 276 /* EnumMember */: + case 149 /* Parameter */: + case 273 /* PropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 274 /* ShorthandPropertyAssignment */: + case 235 /* VariableDeclaration */: return true; } } return false; } ts.isVariableLike = isVariableLike; + function isVariableLikeOrAccessor(node) { + return isVariableLike(node) || ts.isAccessor(node); + } + ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor; function isVariableDeclarationInVariableStatement(node) { - return node.parent.kind === 231 /* VariableDeclarationList */ - && node.parent.parent.kind === 212 /* VariableStatement */; + return node.parent.kind === 236 /* VariableDeclarationList */ + && node.parent.parent.kind === 217 /* VariableStatement */; } ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement; function isValidESSymbolDeclaration(node) { - return ts.isVariableDeclaration(node) ? isConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : + return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) : ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) : ts.isPropertySignature(node) && hasReadonlyModifier(node); } ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration; function introducesArgumentsExoticObject(node) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return true; } return false; @@ -8698,7 +8063,7 @@ var ts; if (beforeUnwrapLabelCallback) { beforeUnwrapLabelCallback(node); } - if (node.statement.kind !== 226 /* LabeledStatement */) { + if (node.statement.kind !== 231 /* LabeledStatement */) { return node.statement; } node = node.statement; @@ -8706,17 +8071,17 @@ var ts; } ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel; function isFunctionBlock(node) { - return node && node.kind === 211 /* Block */ && ts.isFunctionLike(node.parent); + return node && node.kind === 216 /* Block */ && ts.isFunctionLike(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { - return node && node.kind === 153 /* MethodDeclaration */ && node.parent.kind === 182 /* ObjectLiteralExpression */; + return node && node.kind === 154 /* MethodDeclaration */ && node.parent.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; function isObjectLiteralOrClassExpressionMethod(node) { - return node.kind === 153 /* MethodDeclaration */ && - (node.parent.kind === 182 /* ObjectLiteralExpression */ || - node.parent.kind === 203 /* ClassExpression */); + return node.kind === 154 /* MethodDeclaration */ && + (node.parent.kind === 186 /* ObjectLiteralExpression */ || + node.parent.kind === 207 /* ClassExpression */); } ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { @@ -8728,30 +8093,52 @@ var ts; } ts.isThisTypePredicate = isThisTypePredicate; function getPropertyAssignment(objectLiteral, key, key2) { - return ts.filter(objectLiteral.properties, function (property) { - if (property.kind === 268 /* PropertyAssignment */) { + return objectLiteral.properties.filter(function (property) { + if (property.kind === 273 /* PropertyAssignment */) { var propName = getTextOfPropertyName(property.name); - return key === propName || (key2 && key2 === propName); + return key === propName || (!!key2 && key2 === propName); } + return false; }); } ts.getPropertyAssignment = getPropertyAssignment; + function getTsConfigObjectLiteralExpression(tsConfigSourceFile) { + if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { + var expression = tsConfigSourceFile.statements[0].expression; + return ts.tryCast(expression, ts.isObjectLiteralExpression); + } + } + ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression; + function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) { + return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) { + return ts.isArrayLiteralExpression(property.initializer) ? + ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) : + undefined; + }); + } + ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue; + function getTsConfigPropArray(tsConfigSourceFile, propKey) { + var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); + return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; + } + ts.getTsConfigPropArray = getTsConfigPropArray; function getContainingFunction(node) { - return ts.findAncestor(node.parent, ts.isFunctionLike); + return findAncestor(node.parent, ts.isFunctionLike); } ts.getContainingFunction = getContainingFunction; function getContainingClass(node) { - return ts.findAncestor(node.parent, ts.isClassLike); + return findAncestor(node.parent, ts.isClassLike); } ts.getContainingClass = getContainingClass; function getThisContainer(node, includeArrowFunctions) { + ts.Debug.assert(node.kind !== 277 /* SourceFile */); while (true) { node = node.parent; if (!node) { - return undefined; + return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that. } switch (node.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: // If the grandparent node is an object literal (as opposed to a class), // then the computed property is not a 'this' container. // A computed property name in a class needs to be a this container @@ -8766,9 +8153,9 @@ var ts; // the *body* of the container. node = node.parent; break; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 148 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8779,26 +8166,26 @@ var ts; node = node.parent; } break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (!includeArrowFunctions) { continue; } // falls through - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 237 /* ModuleDeclaration */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 236 /* EnumDeclaration */: - case 272 /* SourceFile */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 242 /* ModuleDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 241 /* EnumDeclaration */: + case 277 /* SourceFile */: return node; } } @@ -8808,9 +8195,9 @@ var ts; var container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { switch (container.kind) { - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return container; } } @@ -8832,27 +8219,27 @@ var ts; return node; } switch (node.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: node = node.parent; break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!stopOnFunctions) { continue; } // falls through - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return node; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are always applied outside of the body of a class or method. - if (node.parent.kind === 148 /* Parameter */ && ts.isClassElement(node.parent.parent)) { + if (node.parent.kind === 149 /* Parameter */ && ts.isClassElement(node.parent.parent)) { // If the decorator's parent is a Parameter, we resolve the this container from // the grandparent class declaration. node = node.parent.parent; @@ -8868,14 +8255,14 @@ var ts; } ts.getSuperContainer = getSuperContainer; function getImmediatelyInvokedFunctionExpression(func) { - if (func.kind === 190 /* FunctionExpression */ || func.kind === 191 /* ArrowFunction */) { + if (func.kind === 194 /* FunctionExpression */ || func.kind === 195 /* ArrowFunction */) { var prev = func; var parent = func.parent; - while (parent.kind === 189 /* ParenthesizedExpression */) { + while (parent.kind === 193 /* ParenthesizedExpression */) { prev = parent; parent = parent.parent; } - if (parent.kind === 185 /* CallExpression */ && parent.expression === prev) { + if (parent.kind === 189 /* CallExpression */ && parent.expression === prev) { return parent; } } @@ -8886,7 +8273,7 @@ var ts; */ function isSuperProperty(node) { var kind = node.kind; - return (kind === 183 /* PropertyAccessExpression */ || kind === 184 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 97 /* SuperKeyword */; } ts.isSuperProperty = isSuperProperty; @@ -8895,20 +8282,20 @@ var ts; */ function isThisProperty(node) { var kind = node.kind; - return (kind === 183 /* PropertyAccessExpression */ || kind === 184 /* ElementAccessExpression */) + return (kind === 187 /* PropertyAccessExpression */ || kind === 188 /* ElementAccessExpression */) && node.expression.kind === 99 /* ThisKeyword */; } ts.isThisProperty = isThisProperty; function getEntityNameFromTypeNode(node) { switch (node.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : undefined; case 71 /* Identifier */: - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return node; } return undefined; @@ -8916,10 +8303,10 @@ var ts; ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode; function getInvokedExpression(node) { switch (node.kind) { - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return node.tag; - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return node.tagName; default: return node.expression; @@ -8928,53 +8315,55 @@ var ts; ts.getInvokedExpression = getInvokedExpression; function nodeCanBeDecorated(node, parent, grandparent) { switch (node.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // classes are valid targets return true; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // property declarations are valid if their parent is a class declaration. - return parent.kind === 233 /* ClassDeclaration */; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: + return parent.kind === 238 /* ClassDeclaration */; + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: // if this method has a body and its parent is a class declaration, this is a valid target. return node.body !== undefined - && parent.kind === 233 /* ClassDeclaration */; - case 148 /* Parameter */: + && parent.kind === 238 /* ClassDeclaration */; + case 149 /* Parameter */: // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target; return parent.body !== undefined - && (parent.kind === 154 /* Constructor */ - || parent.kind === 153 /* MethodDeclaration */ - || parent.kind === 156 /* SetAccessor */) - && grandparent.kind === 233 /* ClassDeclaration */; + && (parent.kind === 155 /* Constructor */ + || parent.kind === 154 /* MethodDeclaration */ + || parent.kind === 157 /* SetAccessor */) + && grandparent.kind === 238 /* ClassDeclaration */; } return false; } ts.nodeCanBeDecorated = nodeCanBeDecorated; function nodeIsDecorated(node, parent, grandparent) { return node.decorators !== undefined - && nodeCanBeDecorated(node, parent, grandparent); + && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217 } ts.nodeIsDecorated = nodeIsDecorated; function nodeOrChildIsDecorated(node, parent, grandparent) { - return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); + return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217 } ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated; function childIsDecorated(node, parent) { switch (node.kind) { - case 233 /* ClassDeclaration */: - return ts.forEach(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); - case 153 /* MethodDeclaration */: - case 156 /* SetAccessor */: - return ts.forEach(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); + case 238 /* ClassDeclaration */: + return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217 + case 154 /* MethodDeclaration */: + case 157 /* SetAccessor */: + return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217 + default: + return false; } } ts.childIsDecorated = childIsDecorated; function isJSXTagName(node) { var parent = node.parent; - if (parent.kind === 255 /* JsxOpeningElement */ || - parent.kind === 254 /* JsxSelfClosingElement */ || - parent.kind === 256 /* JsxClosingElement */) { + if (parent.kind === 260 /* JsxOpeningElement */ || + parent.kind === 259 /* JsxSelfClosingElement */ || + parent.kind === 261 /* JsxClosingElement */) { return parent.tagName === node; } return false; @@ -8987,45 +8376,45 @@ var ts; case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 12 /* RegularExpressionLiteral */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 187 /* TaggedTemplateExpression */: - case 206 /* AsExpression */: - case 188 /* TypeAssertionExpression */: - case 207 /* NonNullExpression */: - case 189 /* ParenthesizedExpression */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: - case 191 /* ArrowFunction */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: - case 198 /* BinaryExpression */: - case 199 /* ConditionalExpression */: - case 202 /* SpreadElement */: - case 200 /* TemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: + case 210 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 211 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 206 /* SpreadElement */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: - case 204 /* OmittedExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 201 /* YieldExpression */: - case 195 /* AwaitExpression */: - case 208 /* MetaProperty */: + case 208 /* OmittedExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 205 /* YieldExpression */: + case 199 /* AwaitExpression */: + case 212 /* MetaProperty */: return true; - case 145 /* QualifiedName */: - while (node.parent.kind === 145 /* QualifiedName */) { + case 146 /* QualifiedName */: + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } - return node.parent.kind === 164 /* TypeQuery */ || isJSXTagName(node); + return node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node); case 71 /* Identifier */: - if (node.parent.kind === 164 /* TypeQuery */ || isJSXTagName(node)) { + if (node.parent.kind === 165 /* TypeQuery */ || isJSXTagName(node)) { return true; } // falls through @@ -9041,47 +8430,47 @@ var ts; function isInExpressionContext(node) { var parent = node.parent; switch (parent.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 271 /* EnumMember */: - case 268 /* PropertyAssignment */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 184 /* BindingElement */: return parent.initializer === node; - case 214 /* ExpressionStatement */: - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 223 /* ReturnStatement */: - case 224 /* WithStatement */: - case 225 /* SwitchStatement */: - case 264 /* CaseClause */: - case 227 /* ThrowStatement */: + case 219 /* ExpressionStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 228 /* ReturnStatement */: + case 229 /* WithStatement */: + case 230 /* SwitchStatement */: + case 269 /* CaseClause */: + case 232 /* ThrowStatement */: return parent.expression === node; - case 218 /* ForStatement */: + case 223 /* ForStatement */: var forStatement = parent; - return (forStatement.initializer === node && forStatement.initializer.kind !== 231 /* VariableDeclarationList */) || + return (forStatement.initializer === node && forStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.incrementor === node; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var forInStatement = parent; - return (forInStatement.initializer === node && forInStatement.initializer.kind !== 231 /* VariableDeclarationList */) || + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 236 /* VariableDeclarationList */) || forInStatement.expression === node; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return node === parent.expression; - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return node === parent.expression; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return node === parent.expression; - case 149 /* Decorator */: - case 263 /* JsxExpression */: - case 262 /* JsxSpreadAttribute */: - case 270 /* SpreadAssignment */: + case 150 /* Decorator */: + case 268 /* JsxExpression */: + case 267 /* JsxSpreadAttribute */: + case 275 /* SpreadAssignment */: return true; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent); default: return isExpressionNode(parent); @@ -9089,7 +8478,7 @@ var ts; } ts.isInExpressionContext = isInExpressionContext; function isExternalModuleImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 252 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration; function getExternalModuleImportEqualsDeclarationExpression(node) { @@ -9098,19 +8487,27 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function isInternalModuleImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 252 /* ExternalModuleReference */; + return node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 257 /* ExternalModuleReference */; } ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration; function isSourceFileJavaScript(file) { return isInJavaScriptFile(file); } ts.isSourceFileJavaScript = isSourceFileJavaScript; + function isSourceFileNotJavaScript(file) { + return !isInJavaScriptFile(file); + } + ts.isSourceFileNotJavaScript = isSourceFileNotJavaScript; function isInJavaScriptFile(node) { - return node && !!(node.flags & 65536 /* JavaScriptFile */); + return !!node && !!(node.flags & 65536 /* JavaScriptFile */); } ts.isInJavaScriptFile = isInJavaScriptFile; + function isInJsonFile(node) { + return !!node && !!(node.flags & 16777216 /* JsonFile */); + } + ts.isInJsonFile = isInJsonFile; function isInJSDoc(node) { - return node && !!(node.flags & 1048576 /* JSDoc */); + return !!node && !!(node.flags & 2097152 /* JSDoc */); } ts.isInJSDoc = isInJSDoc; function isJSDocIndexSignature(node) { @@ -9121,8 +8518,8 @@ var ts; (node.typeArguments[0].kind === 137 /* StringKeyword */ || node.typeArguments[0].kind === 134 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteral) { - if (callExpression.kind !== 185 /* CallExpression */) { + function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + if (callExpression.kind !== 189 /* CallExpression */) { return false; } var _a = callExpression, expression = _a.expression, args = _a.arguments; @@ -9133,7 +8530,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteral || arg.kind === 9 /* StringLiteral */ || arg.kind === 13 /* NoSubstitutionTemplateLiteral */; + return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -9144,28 +8541,53 @@ var ts; return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */; } ts.isStringDoubleQuoted = isStringDoubleQuoted; - /** - * Given the symbol of a declaration, find the symbol of its Javascript container-like initializer, - * if it has one. Otherwise just return the original symbol. - * - * Container-like initializer behave like namespaces, so the binder needs to add contained symbols - * to their exports. An example is a function with assignments to `this` inside. - */ - function getJSInitializerSymbol(symbol) { - if (!symbol || !symbol.valueDeclaration) { - return symbol; + function getDeclarationOfJSInitializer(node) { + if (!isInJavaScriptFile(node) || !node.parent) { + return undefined; } - var declaration = symbol.valueDeclaration; - var e = getDeclaredJavascriptInitializer(declaration) || getAssignedJavascriptInitializer(declaration); - return e && e.symbol ? e.symbol : symbol; + var name; + var decl; + if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) { + name = node.parent.name; + decl = node.parent; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.right === node) { + name = node.parent.left; + decl = name; + } + else if (ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 54 /* BarBarToken */) { + if (ts.isVariableDeclaration(node.parent.parent) && node.parent.parent.initializer === node.parent) { + name = node.parent.parent.name; + decl = node.parent.parent; + } + else if (ts.isBinaryExpression(node.parent.parent) && node.parent.parent.operatorToken.kind === 58 /* EqualsToken */ && node.parent.parent.right === node.parent) { + name = node.parent.parent.left; + decl = name; + } + if (!name || !isEntityNameExpression(name) || !isSameEntityName(name, node.parent.left)) { + return undefined; + } + } + if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + return undefined; + } + return decl; } - ts.getJSInitializerSymbol = getJSInitializerSymbol; - /** Get the declaration initializer, when the initializer is container-like (See getJavascriptInitializer) */ - function getDeclaredJavascriptInitializer(node) { - if (node && ts.isVariableDeclaration(node) && node.initializer) { - return getJavascriptInitializer(node.initializer, /*isPrototypeAssignment*/ false) || - ts.isIdentifier(node.name) && getDefaultedJavascriptInitializer(node.name, node.initializer, /*isPrototypeAssignment*/ false); + ts.getDeclarationOfJSInitializer = getDeclarationOfJSInitializer; + /** Get the initializer, taking into account defaulted Javascript initializers */ + function getEffectiveInitializer(node) { + if (isInJavaScriptFile(node) && node.initializer && + ts.isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === 54 /* BarBarToken */ && + node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { + return node.initializer.right; } + return node.initializer; + } + ts.getEffectiveInitializer = getEffectiveInitializer; + /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ + function getDeclaredJavascriptInitializer(node) { + var init = getEffectiveInitializer(node); + return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); } ts.getDeclaredJavascriptInitializer = getDeclaredJavascriptInitializer; /** @@ -9174,7 +8596,7 @@ var ts; */ function getAssignedJavascriptInitializer(node) { if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */) { - var isPrototypeAssignment = ts.isPropertyAccessExpression(node.parent.left) && node.parent.left.name.escapedText === "prototype"; + var isPrototypeAssignment = isPrototypeAccess(node.parent.left); return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || getDefaultedJavascriptInitializer(node.parent.left, node.parent.right, isPrototypeAssignment); } @@ -9193,9 +8615,11 @@ var ts; function getJavascriptInitializer(initializer, isPrototypeAssignment) { if (ts.isCallExpression(initializer)) { var e = skipParentheses(initializer.expression); - return e.kind === 190 /* FunctionExpression */ || e.kind === 191 /* ArrowFunction */ ? initializer : undefined; + return e.kind === 194 /* FunctionExpression */ || e.kind === 195 /* ArrowFunction */ ? initializer : undefined; } - if (initializer.kind === 190 /* FunctionExpression */ || initializer.kind === 203 /* ClassExpression */) { + if (initializer.kind === 194 /* FunctionExpression */ || + initializer.kind === 207 /* ClassExpression */ || + initializer.kind === 195 /* ArrowFunction */) { return initializer; } if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) { @@ -9217,6 +8641,13 @@ var ts; return e; } } + function isDefaultedJavascriptInitializer(node) { + var name = ts.isVariableDeclaration(node.parent) ? node.parent.name : + ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 58 /* EqualsToken */ ? node.parent.left : + undefined; + return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + } + ts.isDefaultedJavascriptInitializer = isDefaultedJavascriptInitializer; /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ function getOuterNameOfJsInitializer(node) { if (ts.isBinaryExpression(node.parent)) { @@ -9257,7 +8688,7 @@ var ts; return false; } function getRightMostAssignedExpression(node) { - while (isAssignmentExpression(node, /*excludeCompoundAssignements*/ true)) { + while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { node = node.right; } return node; @@ -9280,6 +8711,14 @@ var ts; return 0 /* None */; } var lhs = expr.left; + if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { + // F.prototype = { ... } + return 6 /* Prototype */; + } + return getSpecialPropertyAccessKind(lhs); + } + ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + function getSpecialPropertyAccessKind(lhs) { if (lhs.expression.kind === 99 /* ThisKeyword */) { return 4 /* ThisProperty */; } @@ -9288,11 +8727,7 @@ var ts; return 2 /* ModuleExports */; } else if (isEntityNameExpression(lhs.expression)) { - if (lhs.name.escapedText === "prototype" && ts.isObjectLiteralExpression(expr.right)) { - // F.prototype = { ... } - return 6 /* Prototype */; - } - else if (ts.isPropertyAccessExpression(lhs.expression) && lhs.expression.name.escapedText === "prototype") { + if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr return 3 /* PrototypeProperty */; } @@ -9312,38 +8747,66 @@ var ts; } return 0 /* None */; } - ts.getSpecialPropertyAssignmentKind = getSpecialPropertyAssignmentKind; + ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + function getInitializerOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.right)) { + expr = expr.right; + } + return expr.right; + } + ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression; + function isPrototypePropertyAssignment(node) { + return ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 3 /* PrototypeProperty */; + } + ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment; function isSpecialPropertyDeclaration(expr) { return isInJavaScriptFile(expr) && - expr.parent && expr.parent.kind === 214 /* ExpressionStatement */ && + expr.parent && expr.parent.kind === 219 /* ExpressionStatement */ && !!ts.getJSDocTypeTag(expr.parent); } ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration; + function importFromModuleSpecifier(node) { + return tryGetImportFromModuleSpecifier(node) || ts.Debug.fail(ts.Debug.showSyntaxKind(node.parent)); + } + ts.importFromModuleSpecifier = importFromModuleSpecifier; + function tryGetImportFromModuleSpecifier(node) { + switch (node.parent.kind) { + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + return node.parent; + case 257 /* ExternalModuleReference */: + return node.parent.parent; + case 189 /* CallExpression */: + return node.parent; + case 180 /* LiteralType */: + ts.Debug.assert(ts.isStringLiteral(node)); + return ts.tryCast(node.parent.parent, ts.isImportTypeNode); + default: + return undefined; + } + } + ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier; function getExternalModuleName(node) { - if (node.kind === 242 /* ImportDeclaration */) { - return node.moduleSpecifier; - } - if (node.kind === 241 /* ImportEqualsDeclaration */) { - var reference = node.moduleReference; - if (reference.kind === 252 /* ExternalModuleReference */) { - return reference.expression; - } - } - if (node.kind === 248 /* ExportDeclaration */) { - return node.moduleSpecifier; - } - if (isModuleWithStringLiteralName(node)) { - return node.name; + switch (node.kind) { + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + return node.moduleSpecifier; + case 246 /* ImportEqualsDeclaration */: + return node.moduleReference.kind === 257 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined; + case 181 /* ImportType */: + return isLiteralImportTypeNode(node) ? node.argument.literal : undefined; + default: + return ts.Debug.assertNever(node); } } ts.getExternalModuleName = getExternalModuleName; function getNamespaceDeclarationNode(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return undefined; default: return ts.Debug.assertNever(node); @@ -9351,19 +8814,19 @@ var ts; } ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode; function isDefaultImport(node) { - return node.kind === 242 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; + return node.kind === 247 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name; } ts.isDefaultImport = isDefaultImport; function hasQuestionToken(node) { if (node) { switch (node.kind) { - case 148 /* Parameter */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 269 /* ShorthandPropertyAssignment */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 149 /* Parameter */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 274 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return node.questionToken !== undefined; } } @@ -9371,86 +8834,104 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function isJSDocConstructSignature(node) { - return node.kind === 280 /* JSDocFunctionType */ && + return node.kind === 287 /* JSDocFunctionType */ && node.parameters.length > 0 && node.parameters[0].name && node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; + function isJSDocTypeAlias(node) { + return node.kind === 301 /* JSDocTypedefTag */ || node.kind === 295 /* JSDocCallbackTag */; + } + ts.isJSDocTypeAlias = isJSDocTypeAlias; + function isTypeAlias(node) { + return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); + } + ts.isTypeAlias = isTypeAlias; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && - node.expression.operatorToken.kind === 58 /* EqualsToken */ && - node.expression.right; + node.expression.operatorToken.kind === 58 /* EqualsToken */ + ? node.expression.right + : undefined; } function getSourceOfDefaultedAssignment(node) { return ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression) && getSpecialPropertyAssignmentKind(node.expression) !== 0 /* None */ && ts.isBinaryExpression(node.expression.right) && - node.expression.right.operatorToken.kind === 54 /* BarBarToken */ && - node.expression.right.right; + node.expression.right.operatorToken.kind === 54 /* BarBarToken */ + ? node.expression.right.right + : undefined; } function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: var v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: + return node.initializer; + case 273 /* PropertyAssignment */: return node.initializer; } } function getSingleVariableOfVariableStatement(node) { - return ts.isVariableStatement(node) && - node.declarationList.declarations.length > 0 && - node.declarationList.declarations[0]; + return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } function getNestedModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ && + return ts.isModuleDeclaration(node) && node.body && - node.body.kind === 237 /* ModuleDeclaration */ && - node.body; + node.body.kind === 242 /* ModuleDeclaration */ + ? node.body + : undefined; } - function getJSDocCommentsAndTags(node) { + function getJSDocCommentsAndTags(hostNode) { var result; - getJSDocCommentsAndTagsWorker(node); - return result || ts.emptyArray; - function getJSDocCommentsAndTagsWorker(node) { - var parent = node.parent; - if (parent && (parent.kind === 268 /* PropertyAssignment */ || parent.kind === 151 /* PropertyDeclaration */ || getNestedModuleDeclaration(parent))) { - getJSDocCommentsAndTagsWorker(parent); - } - // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. - // /** - // * @param {number} name - // * @returns {number} - // */ - // var x = function(name) { return name.length; } - if (parent && parent.parent && - (getSingleVariableOfVariableStatement(parent.parent) === node || getSourceOfAssignment(parent.parent))) { - getJSDocCommentsAndTagsWorker(parent.parent); - } - if (parent && parent.parent && parent.parent.parent && - (getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || getSourceOfDefaultedAssignment(parent.parent.parent))) { - getJSDocCommentsAndTagsWorker(parent.parent.parent); - } - if (ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) !== 0 /* None */ || - node.kind === 183 /* PropertyAccessExpression */ && node.parent && node.parent.kind === 214 /* ExpressionStatement */) { - getJSDocCommentsAndTagsWorker(parent); - } - // Pull parameter comments from declaring function as well - if (node.kind === 148 /* Parameter */) { - result = ts.addRange(result, ts.getJSDocParameterTags(node)); - } - if (isVariableLike(node) && ts.hasInitializer(node) && ts.hasJSDocNodes(node.initializer)) { - result = ts.addRange(result, node.initializer.jsDoc); - } + // Pull parameter comments from declaring function as well + if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) { + result = ts.addRange(result, hostNode.initializer.jsDoc); + } + var node = hostNode; + while (node && node.parent) { if (ts.hasJSDocNodes(node)) { result = ts.addRange(result, node.jsDoc); } + if (node.kind === 149 /* Parameter */) { + result = ts.addRange(result, ts.getJSDocParameterTags(node)); + break; + } + node = getNextJSDocCommentLocation(node); } + return result || ts.emptyArray; } ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags; + function getNextJSDocCommentLocation(node) { + var parent = node.parent; + if (parent.kind === 273 /* PropertyAssignment */ || + parent.kind === 152 /* PropertyDeclaration */ || + parent.kind === 219 /* ExpressionStatement */ && node.kind === 187 /* PropertyAccessExpression */ || + getNestedModuleDeclaration(parent) || + ts.isBinaryExpression(node) && node.operatorToken.kind === 58 /* EqualsToken */) { + return parent; + } + // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement. + // /** + // * @param {number} name + // * @returns {number} + // */ + // var x = function(name) { return name.length; } + else if (parent.parent && + (getSingleVariableOfVariableStatement(parent.parent) === node || + ts.isBinaryExpression(parent) && parent.operatorToken.kind === 58 /* EqualsToken */)) { + return parent.parent; + } + else if (parent.parent && parent.parent.parent && + (getSingleVariableOfVariableStatement(parent.parent.parent) || + getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node || + getSourceOfDefaultedAssignment(parent.parent.parent))) { + return parent.parent.parent; + } + } /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ function getParameterSymbolFromJSDoc(node) { if (node.symbol) { @@ -9469,7 +8950,10 @@ var ts; } ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc; function getHostSignatureFromJSDoc(node) { - var host = getJSDocHost(node); + return getHostSignatureFromJSDocHost(getJSDocHost(node)); + } + ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + function getHostSignatureFromJSDocHost(host) { var decl = getSourceOfDefaultedAssignment(host) || getSourceOfAssignment(host) || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) || @@ -9478,10 +8962,9 @@ var ts; host; return decl && ts.isFunctionLike(decl) ? decl : undefined; } - ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc; + ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost; function getJSDocHost(node) { - ts.Debug.assert(node.parent.kind === 282 /* JSDocComment */); - return node.parent.parent; + return ts.Debug.assertDefined(findAncestor(node.parent, ts.isJSDoc)).parent; } ts.getJSDocHost = getJSDocHost; function getTypeParameterFromJsDoc(node) { @@ -9492,11 +8975,12 @@ var ts; ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc; function hasRestParameter(s) { var last = ts.lastOrUndefined(s.parameters); - return last && isRestParameter(last); + return !!last && isRestParameter(last); } ts.hasRestParameter = hasRestParameter; function isRestParameter(node) { - return node.dotDotDotToken !== undefined; + var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; + return node.dotDotDotToken !== undefined || !!type && type.kind === 288 /* JSDocVariadicType */; } ts.isRestParameter = isRestParameter; var AssignmentKind; @@ -9509,31 +8993,31 @@ var ts; var parent = node.parent; while (true) { switch (parent.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var binaryOperator = parent.operatorToken.kind; return isAssignmentOperator(binaryOperator) && parent.left === node ? binaryOperator === 58 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ : 0 /* None */; - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: var unaryOperator = parent.operator; return unaryOperator === 43 /* PlusPlusToken */ || unaryOperator === 44 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return parent.initializer === node ? 1 /* Definite */ : 0 /* None */; - case 189 /* ParenthesizedExpression */: - case 181 /* ArrayLiteralExpression */: - case 202 /* SpreadElement */: - case 207 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 185 /* ArrayLiteralExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: node = parent; break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: if (parent.name !== node) { return 0 /* None */; } node = parent.parent; break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (parent.name === node) { return 0 /* None */; } @@ -9560,27 +9044,31 @@ var ts; */ function isNodeWithPossibleHoistedDeclaration(node) { switch (node.kind) { - case 211 /* Block */: - case 212 /* VariableStatement */: - case 224 /* WithStatement */: - case 215 /* IfStatement */: - case 225 /* SwitchStatement */: - case 239 /* CaseBlock */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 226 /* LabeledStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 228 /* TryStatement */: - case 267 /* CatchClause */: + case 216 /* Block */: + case 217 /* VariableStatement */: + case 229 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 231 /* LabeledStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 272 /* CatchClause */: return true; } return false; } ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; + function isValueSignatureDeclaration(node) { + return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); + } + ts.isValueSignatureDeclaration = isValueSignatureDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -9588,15 +9076,15 @@ var ts; return node; } function walkUpParenthesizedTypes(node) { - return walkUp(node, 172 /* ParenthesizedType */); + return walkUp(node, 175 /* ParenthesizedType */); } ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes; function walkUpParenthesizedExpressions(node) { - return walkUp(node, 189 /* ParenthesizedExpression */); + return walkUp(node, 193 /* ParenthesizedExpression */); } ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions; function skipParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */) { + while (node.kind === 193 /* ParenthesizedExpression */) { node = node.expression; } return node; @@ -9604,11 +9092,11 @@ var ts; ts.skipParentheses = skipParentheses; // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped function isDeleteTarget(node) { - if (node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { + if (node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { return false; } node = walkUpParenthesizedExpressions(node.parent); - return node && node.kind === 192 /* DeleteExpression */; + return node && node.kind === 196 /* DeleteExpression */; } ts.isDeleteTarget = isDeleteTarget; function isNodeDescendantOf(node, ancestor) { @@ -9630,12 +9118,20 @@ var ts; switch (name.kind) { case 71 /* Identifier */: case 9 /* StringLiteral */: - case 8 /* NumericLiteral */: - if (ts.isDeclaration(name.parent)) { - return name.parent.name === name; + case 8 /* NumericLiteral */: { + var parent = name.parent; + if (ts.isDeclaration(parent)) { + return parent.name === name; } - var binExp = name.parent.parent; - return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + else if (ts.isQualifiedName(name.parent)) { + var tag = name.parent.parent; + return ts.isJSDocParameterTag(tag) && tag.name === name.parent; + } + else { + var binExp = name.parent.parent; + return ts.isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== 0 /* None */ && ts.getNameOfDeclaration(binExp) === name; + } + } default: return false; } @@ -9643,7 +9139,7 @@ var ts; ts.isAnyDeclarationName = isAnyDeclarationName; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && - node.parent.kind === 146 /* ComputedPropertyName */ && + node.parent.kind === 147 /* ComputedPropertyName */ && ts.isDeclaration(node.parent.parent); } ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName; @@ -9651,32 +9147,32 @@ var ts; function isIdentifierName(node) { var parent = node.parent; switch (parent.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 271 /* EnumMember */: - case 268 /* PropertyAssignment */: - case 183 /* PropertyAccessExpression */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 276 /* EnumMember */: + case 273 /* PropertyAssignment */: + case 187 /* PropertyAccessExpression */: // Name in member declaration or property name in property access return parent.name === node; - case 145 /* QualifiedName */: - // Name on right hand side of dot in a type query + case 146 /* QualifiedName */: + // Name on right hand side of dot in a type query or type reference if (parent.right === node) { - while (parent.kind === 145 /* QualifiedName */) { + while (parent.kind === 146 /* QualifiedName */) { parent = parent.parent; } - return parent.kind === 164 /* TypeQuery */; + return parent.kind === 165 /* TypeQuery */ || parent.kind === 162 /* TypeReference */; } return false; - case 180 /* BindingElement */: - case 246 /* ImportSpecifier */: + case 184 /* BindingElement */: + case 251 /* ImportSpecifier */: // Property name in binding element or import specifier return parent.propertyName === node; - case 250 /* ExportSpecifier */: - case 260 /* JsxAttribute */: + case 255 /* ExportSpecifier */: + case 265 /* JsxAttribute */: // Any name in an export specifier or JSX Attribute return true; } @@ -9692,29 +9188,49 @@ var ts; // export = // export default function isAliasSymbolDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */ || - node.kind === 240 /* NamespaceExportDeclaration */ || - node.kind === 243 /* ImportClause */ && !!node.name || - node.kind === 244 /* NamespaceImport */ || - node.kind === 246 /* ImportSpecifier */ || - node.kind === 250 /* ExportSpecifier */ || - node.kind === 247 /* ExportAssignment */ && exportAssignmentIsAlias(node); + return node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 245 /* NamespaceExportDeclaration */ || + node.kind === 248 /* ImportClause */ && !!node.name || + node.kind === 249 /* NamespaceImport */ || + node.kind === 251 /* ImportSpecifier */ || + node.kind === 255 /* ExportSpecifier */ || + node.kind === 252 /* ExportAssignment */ && exportAssignmentIsAlias(node) || + ts.isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */; } ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration; function exportAssignmentIsAlias(node) { - return isEntityNameExpression(node.expression); + var e = ts.isExportAssignment(node) ? node.expression : node.right; + return isEntityNameExpression(e) || ts.isClassExpression(e); } ts.exportAssignmentIsAlias = exportAssignmentIsAlias; - function getClassExtendsHeritageClauseElement(node) { + function getEffectiveBaseTypeNode(node) { + if (isInJavaScriptFile(node)) { + // Prefer an @augments tag because it may have type parameters. + var tag = ts.getJSDocAugmentsTag(node); + if (tag) { + return tag.class; + } + } + return getClassExtendsHeritageElement(node); + } + ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode; + function getClassExtendsHeritageElement(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } - ts.getClassExtendsHeritageClauseElement = getClassExtendsHeritageClauseElement; + ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement; function getClassImplementsHeritageClauseElements(node) { var heritageClause = getHeritageClause(node.heritageClauses, 108 /* ImplementsKeyword */); return heritageClause ? heritageClause.types : undefined; } ts.getClassImplementsHeritageClauseElements = getClassImplementsHeritageClauseElements; + /** Returns the node in an `extends` or `implements` clause of a class or interface. */ + function getAllSuperTypeNodes(node) { + return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray + : ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getClassImplementsHeritageClauseElements(node)) || ts.emptyArray + : ts.emptyArray; + } + ts.getAllSuperTypeNodes = getAllSuperTypeNodes; function getInterfaceBaseTypeNodes(node) { var heritageClause = getHeritageClause(node.heritageClauses, 85 /* ExtendsKeyword */); return heritageClause ? heritageClause.types : undefined; @@ -9750,11 +9266,11 @@ var ts; } ts.getAncestor = getAncestor; function isKeyword(token) { - return 72 /* FirstKeyword */ <= token && token <= 144 /* LastKeyword */; + return 72 /* FirstKeyword */ <= token && token <= 145 /* LastKeyword */; } ts.isKeyword = isKeyword; function isContextualKeyword(token) { - return 117 /* FirstContextualKeyword */ <= token && token <= 144 /* LastContextualKeyword */; + return 117 /* FirstContextualKeyword */ <= token && token <= 145 /* LastContextualKeyword */; } ts.isContextualKeyword = isContextualKeyword; function isNonContextualKeyword(token) { @@ -9784,14 +9300,14 @@ var ts; } var flags = 0 /* Normal */; switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: if (node.asteriskToken) { flags |= 1 /* Generator */; } // falls through - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (hasModifier(node, 256 /* Async */)) { flags |= 2 /* Async */; } @@ -9805,10 +9321,10 @@ var ts; ts.getFunctionFlags = getFunctionFlags; function isAsyncFunction(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: return node.body !== undefined && node.asteriskToken === undefined && hasModifier(node, 256 /* Async */); @@ -9831,11 +9347,11 @@ var ts; */ function hasDynamicName(declaration) { var name = ts.getNameOfDeclaration(declaration); - return name && isDynamicName(name); + return !!name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { - return name.kind === 146 /* ComputedPropertyName */ && + return name.kind === 147 /* ComputedPropertyName */ && !isStringOrNumericLiteral(name.expression) && !isWellKnownSymbolSyntactically(name.expression); } @@ -9856,7 +9372,7 @@ var ts; if (name.kind === 9 /* StringLiteral */ || name.kind === 8 /* NumericLiteral */) { return escapeLeadingUnderscores(name.text); } - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { var nameExpression = name.expression; if (isWellKnownSymbolSyntactically(nameExpression)) { return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); @@ -9909,11 +9425,11 @@ var ts; ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier; function isParameterDeclaration(node) { var root = getRootDeclaration(node); - return root.kind === 148 /* Parameter */; + return root.kind === 149 /* Parameter */; } ts.isParameterDeclaration = isParameterDeclaration; function getRootDeclaration(node) { - while (node.kind === 180 /* BindingElement */) { + while (node.kind === 184 /* BindingElement */) { node = node.parent.parent; } return node; @@ -9921,15 +9437,15 @@ var ts; ts.getRootDeclaration = getRootDeclaration; function nodeStartsNewLexicalEnvironment(node) { var kind = node.kind; - return kind === 154 /* Constructor */ - || kind === 190 /* FunctionExpression */ - || kind === 232 /* FunctionDeclaration */ - || kind === 191 /* ArrowFunction */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 237 /* ModuleDeclaration */ - || kind === 272 /* SourceFile */; + return kind === 155 /* Constructor */ + || kind === 194 /* FunctionExpression */ + || kind === 237 /* FunctionDeclaration */ + || kind === 195 /* ArrowFunction */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 242 /* ModuleDeclaration */ + || kind === 277 /* SourceFile */; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(range) { @@ -9948,23 +9464,23 @@ var ts; })(Associativity = ts.Associativity || (ts.Associativity = {})); function getExpressionAssociativity(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 186 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } ts.getExpressionAssociativity = getExpressionAssociativity; function getOperatorAssociativity(kind, operator, hasArguments) { switch (kind) { - case 186 /* NewExpression */: + case 190 /* NewExpression */: return hasArguments ? 0 /* Left */ : 1 /* Right */; - case 196 /* PrefixUnaryExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 195 /* AwaitExpression */: - case 199 /* ConditionalExpression */: - case 201 /* YieldExpression */: + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: return 1 /* Right */; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (operator) { case 40 /* AsteriskAsteriskToken */: case 58 /* EqualsToken */: @@ -9988,15 +9504,15 @@ var ts; ts.getOperatorAssociativity = getOperatorAssociativity; function getExpressionPrecedence(expression) { var operator = getOperator(expression); - var hasArguments = expression.kind === 186 /* NewExpression */ && expression.arguments !== undefined; + var hasArguments = expression.kind === 190 /* NewExpression */ && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } ts.getExpressionPrecedence = getExpressionPrecedence; function getOperator(expression) { - if (expression.kind === 198 /* BinaryExpression */) { + if (expression.kind === 202 /* BinaryExpression */) { return expression.operatorToken.kind; } - else if (expression.kind === 196 /* PrefixUnaryExpression */ || expression.kind === 197 /* PostfixUnaryExpression */) { + else if (expression.kind === 200 /* PrefixUnaryExpression */ || expression.kind === 201 /* PostfixUnaryExpression */) { return expression.operator; } else { @@ -10006,83 +9522,18 @@ var ts; ts.getOperator = getOperator; function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 99 /* ThisKeyword */: - case 97 /* SuperKeyword */: - case 71 /* Identifier */: - case 95 /* NullKeyword */: - case 101 /* TrueKeyword */: - case 86 /* FalseKeyword */: - case 8 /* NumericLiteral */: - case 9 /* StringLiteral */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 203 /* ClassExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* TemplateExpression */: - case 189 /* ParenthesizedExpression */: - case 204 /* OmittedExpression */: - return 19; - case 187 /* TaggedTemplateExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - return 18; - case 186 /* NewExpression */: - return hasArguments ? 18 : 17; - case 185 /* CallExpression */: - return 17; - case 197 /* PostfixUnaryExpression */: - return 16; - case 196 /* PrefixUnaryExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 192 /* DeleteExpression */: - case 195 /* AwaitExpression */: - return 15; - case 198 /* BinaryExpression */: + case 306 /* CommaListExpression */: + return 0; + case 206 /* SpreadElement */: + return 1; + case 205 /* YieldExpression */: + return 2; + case 203 /* ConditionalExpression */: + return 4; + case 202 /* BinaryExpression */: switch (operatorKind) { - case 51 /* ExclamationToken */: - case 52 /* TildeToken */: - return 15; - case 40 /* AsteriskAsteriskToken */: - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 14; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 13; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 12; - case 27 /* LessThanToken */: - case 30 /* LessThanEqualsToken */: - case 29 /* GreaterThanToken */: - case 31 /* GreaterThanEqualsToken */: - case 92 /* InKeyword */: - case 93 /* InstanceOfKeyword */: - return 11; - case 32 /* EqualsEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 10; - case 48 /* AmpersandToken */: - return 9; - case 50 /* CaretToken */: - return 8; - case 49 /* BarToken */: - return 7; - case 53 /* AmpersandAmpersandToken */: - return 6; - case 54 /* BarBarToken */: - return 5; + case 26 /* CommaToken */: + return 0; case 58 /* EqualsToken */: case 59 /* PlusEqualsToken */: case 60 /* MinusEqualsToken */: @@ -10097,49 +9548,135 @@ var ts; case 70 /* CaretEqualsToken */: case 69 /* BarEqualsToken */: return 3; - case 26 /* CommaToken */: - return 0; default: - return -1; + return getBinaryOperatorPrecedence(operatorKind); } - case 199 /* ConditionalExpression */: - return 4; - case 201 /* YieldExpression */: - return 2; - case 202 /* SpreadElement */: - return 1; - case 296 /* CommaListExpression */: - return 0; + case 200 /* PrefixUnaryExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 196 /* DeleteExpression */: + case 199 /* AwaitExpression */: + return 16; + case 201 /* PostfixUnaryExpression */: + return 17; + case 189 /* CallExpression */: + return 18; + case 190 /* NewExpression */: + return hasArguments ? 19 : 18; + case 191 /* TaggedTemplateExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + return 19; + case 99 /* ThisKeyword */: + case 97 /* SuperKeyword */: + case 71 /* Identifier */: + case 95 /* NullKeyword */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 204 /* TemplateExpression */: + case 193 /* ParenthesizedExpression */: + case 208 /* OmittedExpression */: + return 20; default: return -1; } } ts.getOperatorPrecedence = getOperatorPrecedence; + /* @internal */ + function getBinaryOperatorPrecedence(kind) { + switch (kind) { + case 54 /* BarBarToken */: + return 5; + case 53 /* AmpersandAmpersandToken */: + return 6; + case 49 /* BarToken */: + return 7; + case 50 /* CaretToken */: + return 8; + case 48 /* AmpersandToken */: + return 9; + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return 10; + case 27 /* LessThanToken */: + case 29 /* GreaterThanToken */: + case 30 /* LessThanEqualsToken */: + case 31 /* GreaterThanEqualsToken */: + case 93 /* InstanceOfKeyword */: + case 92 /* InKeyword */: + case 118 /* AsKeyword */: + return 11; + case 45 /* LessThanLessThanToken */: + case 46 /* GreaterThanGreaterThanToken */: + case 47 /* GreaterThanGreaterThanGreaterThanToken */: + return 12; + case 37 /* PlusToken */: + case 38 /* MinusToken */: + return 13; + case 39 /* AsteriskToken */: + case 41 /* SlashToken */: + case 42 /* PercentToken */: + return 14; + case 40 /* AsteriskAsteriskToken */: + return 15; + } + // -1 is lower than all other precedences. Returning it will cause binary expression + // parsing to stop. + return -1; + } + ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence; function createDiagnosticCollection() { - var nonFileDiagnostics = []; + var nonFileDiagnostics = []; // See GH#19873 var filesWithDiagnostics = []; var fileDiagnostics = ts.createMap(); var hasReadNonFileDiagnostics = false; - var modificationCount = 0; return { add: add, + lookup: lookup, getGlobalDiagnostics: getGlobalDiagnostics, getDiagnostics: getDiagnostics, - getModificationCount: getModificationCount, reattachFileDiagnostics: reattachFileDiagnostics }; - function getModificationCount() { - return modificationCount; - } function reattachFileDiagnostics(newFile) { ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; }); } + function lookup(diagnostic) { + var diagnostics; + if (diagnostic.file) { + diagnostics = fileDiagnostics.get(diagnostic.file.fileName); + } + else { + diagnostics = nonFileDiagnostics; + } + if (!diagnostics) { + return undefined; + } + var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, ts.compareDiagnosticsSkipRelatedInformation); + if (result >= 0) { + return diagnostics[result]; + } + return undefined; + } function add(diagnostic) { var diagnostics; if (diagnostic.file) { diagnostics = fileDiagnostics.get(diagnostic.file.fileName); if (!diagnostics) { - diagnostics = []; + diagnostics = []; // See GH#19873 fileDiagnostics.set(diagnostic.file.fileName, diagnostics); ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive); } @@ -10153,7 +9690,6 @@ var ts; diagnostics = nonFileDiagnostics; } ts.insertSorted(diagnostics, diagnostic, ts.compareDiagnostics); - modificationCount++; } function getGlobalDiagnostics() { hasReadNonFileDiagnostics = true; @@ -10257,13 +9793,25 @@ var ts; var lineStart; var lineCount; var linePos; + function updateLineCountAndPosFor(s) { + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + ts.last(lineStartsOfS); + lineStart = (linePos - output.length) === 0; + } + else { + lineStart = false; + } + } function write(s) { if (s && s.length) { if (lineStart) { - output += getIndentString(indent); + s = getIndentString(indent) + s; lineStart = false; } output += s; + updateLineCountAndPosFor(s); } } function reset() { @@ -10275,20 +9823,13 @@ var ts; } function rawWrite(s) { if (s !== undefined) { - if (lineStart) { - lineStart = false; - } output += s; + updateLineCountAndPosFor(s); } } function writeLiteral(s) { if (s && s.length) { write(s); - var lineStartsOfS = ts.computeLineStarts(s); - if (lineStartsOfS.length > 1) { - lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); - } } } function writeLine() { @@ -10300,7 +9841,9 @@ var ts; } } function writeTextOfNode(text, node) { - write(getTextOfNodeFromSourceText(text, node)); + var s = getTextOfNodeFromSourceText(text, node); + write(s); + updateLineCountAndPosFor(s); } reset(); return { @@ -10313,8 +9856,8 @@ var ts; decreaseIndent: function () { indent--; }, getIndent: function () { return indent; }, getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getLine: function () { return lineCount; }, + getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, clear: reset, @@ -10333,8 +9876,8 @@ var ts; }; } ts.createTextWriter = createTextWriter; - function getResolvedExternalModuleName(host, file) { - return file.moduleName || getExternalModuleNameFromPath(host, file.fileName); + function getResolvedExternalModuleName(host, file, referenceFile) { + return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } ts.getResolvedExternalModuleName = getResolvedExternalModuleName; function getExternalModuleNameFromDeclaration(host, resolver, declaration) { @@ -10348,35 +9891,46 @@ var ts; /** * Resolves a local path to a path which is absolute to the base of the emit */ - function getExternalModuleNameFromPath(host, fileName) { + function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = ts.toPath(host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.removeFileExtension(relativePath); + var extensionless = ts.removeFileExtension(relativePath); + return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath; - function getOwnEmitOutputFilePath(sourceFile, host, extension) { + function getOwnEmitOutputFilePath(fileName, host, extension) { var compilerOptions = host.getCompilerOptions(); var emitOutputFilePathWithoutExtension; if (compilerOptions.outDir) { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir)); } else { - emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName); + emitOutputFilePathWithoutExtension = ts.removeFileExtension(fileName); } return emitOutputFilePathWithoutExtension + extension; } ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath; - function getDeclarationEmitOutputFilePath(sourceFile, host) { + function getDeclarationEmitOutputFilePath(fileName, host) { + // TODO: GH#25810 following should work but makes the build break: + // return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; + ? getSourceFilePathInNewDir(fileName, host, outputDir) + : fileName; return ts.removeFileExtension(path) + ".d.ts" /* Dts */; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; + function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified + var path = outputDir + ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName) + : fileName; + return ts.removeFileExtension(path) + ".d.ts" /* Dts */; + } + ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker; /** * Gets the source files that are expected to have an emit output. * @@ -10408,14 +9962,17 @@ var ts; return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted; - function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, host.getCurrentDirectory()); - var commonSourceDirectory = host.getCommonSourceDirectory(); - var isSourceFileInCommonSourceDirectory = host.getCanonicalFileName(sourceFilePath).indexOf(host.getCanonicalFileName(commonSourceDirectory)) === 0; + function getSourceFilePathInNewDir(fileName, host, newDirPath) { + return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); }); + } + ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) { + var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); + var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath; return ts.combinePaths(newDirPath, sourceFilePath); } - ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir; + ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker; function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) { host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) { diagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -10431,11 +9988,7 @@ var ts; } ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap; function getFirstConstructorWithBody(node) { - return ts.forEach(node.members, function (member) { - if (member.kind === 154 /* Constructor */ && nodeIsPresent(member.body)) { - return member; - } - }); + return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorValueParameter(accessor) { @@ -10451,7 +10004,8 @@ var ts; } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; function getThisParameter(signature) { - if (signature.parameters.length) { + // callback tags do not currently support this parameters + if (signature.parameters.length && !ts.isJSDocSignature(signature)) { var thisParameter = signature.parameters[0]; if (parameterIsThisKeyword(thisParameter)) { return thisParameter; @@ -10464,7 +10018,7 @@ var ts; } ts.parameterIsThisKeyword = parameterIsThisKeyword; function isThisIdentifier(node) { - return node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); + return !!node && node.kind === 71 /* Identifier */ && identifierIsThisKeyword(node); } ts.isThisIdentifier = isThisIdentifier; function identifierIsThisKeyword(id) { @@ -10472,16 +10026,17 @@ var ts; } ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { + // TODO: GH#18217 var firstAccessor; var secondAccessor; var getAccessor; var setAccessor; if (hasDynamicName(accessor)) { firstAccessor = accessor; - if (accessor.kind === 155 /* GetAccessor */) { + if (accessor.kind === 156 /* GetAccessor */) { getAccessor = accessor; } - else if (accessor.kind === 156 /* SetAccessor */) { + else if (accessor.kind === 157 /* SetAccessor */) { setAccessor = accessor; } else { @@ -10490,7 +10045,7 @@ var ts; } else { ts.forEach(declarations, function (member) { - if ((member.kind === 155 /* GetAccessor */ || member.kind === 156 /* SetAccessor */) + if ((member.kind === 156 /* GetAccessor */ || member.kind === 157 /* SetAccessor */) && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); @@ -10501,10 +10056,10 @@ var ts; else if (!secondAccessor) { secondAccessor = member; } - if (member.kind === 155 /* GetAccessor */ && !getAccessor) { + if (member.kind === 156 /* GetAccessor */ && !getAccessor) { getAccessor = member; } - if (member.kind === 156 /* SetAccessor */ && !setAccessor) { + if (member.kind === 157 /* SetAccessor */ && !setAccessor) { setAccessor = member; } } @@ -10527,27 +10082,29 @@ var ts; return node.type || (isInJavaScriptFile(node) ? ts.getJSDocType(node) : undefined); } ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode; + function getTypeAnnotationNode(node) { + return node.type; + } + ts.getTypeAnnotationNode = getTypeAnnotationNode; /** * Gets the effective return type annotation of a signature. If the node was parsed in a * JavaScript file, gets the return type annotation from JSDoc. */ function getEffectiveReturnTypeNode(node) { + if (ts.isJSDocSignature(node)) { + return node.type && node.type.typeExpression && node.type.typeExpression.type; + } return node.type || (isInJavaScriptFile(node) ? ts.getJSDocReturnType(node) : undefined); } ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode; - /** - * Gets the effective type parameters. If the node was parsed in a - * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. - */ - function getEffectiveTypeParameterDeclarations(node) { - return node.typeParameters || (isInJavaScriptFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined); - } - ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; function getJSDocTypeParameterDeclarations(node) { - var templateTag = ts.getJSDocTemplateTag(node); - return templateTag && templateTag.typeParameters; + return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; }); } ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations; + /** template tags are only available when a typedef isn't already using them */ + function isNonTypeAliasTemplate(tag) { + return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 289 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias)); + } /** * Gets the effective type annotation of the value parameter of a set accessor. If the node * was parsed in a JavaScript file, gets the type annotation from JSDoc. @@ -10646,19 +10203,19 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.lastOrUndefined(detachedComments).end); + var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end); var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments); emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment); - currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end }; } } } return currentDetachedCommentInfo; function isPinnedCommentLocal(comment) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } ts.emitDetachedComments = emitDetachedComments; @@ -10821,7 +10378,7 @@ var ts; ts.isAssignmentOperator = isAssignmentOperator; /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ function tryGetClassExtendingExpressionWithTypeArguments(node) { - if (node.kind === 205 /* ExpressionWithTypeArguments */ && + if (ts.isExpressionWithTypeArguments(node) && node.parent.token === 85 /* ExtendsKeyword */ && ts.isClassLike(node.parent.parent)) { return node.parent.parent; @@ -10839,8 +10396,8 @@ var ts; function isDestructuringAssignment(node) { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { var kind = node.left.kind; - return kind === 182 /* ObjectLiteralExpression */ - || kind === 181 /* ArrayLiteralExpression */; + return kind === 186 /* ObjectLiteralExpression */ + || kind === 185 /* ArrayLiteralExpression */; } return false; } @@ -10850,7 +10407,7 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause; function isExpressionWithTypeArgumentsInClassImplementsClause(node) { - return node.kind === 205 /* ExpressionWithTypeArguments */ + return node.kind === 209 /* ExpressionWithTypeArguments */ && isEntityNameExpression(node.expression) && node.parent && node.parent.token === 108 /* ImplementsKeyword */ @@ -10859,22 +10416,29 @@ var ts; } ts.isExpressionWithTypeArgumentsInClassImplementsClause = isExpressionWithTypeArgumentsInClassImplementsClause; function isEntityNameExpression(node) { - return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isEntityNameExpression(node.expression); + return node.kind === 71 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function isPropertyAccessEntityNameExpression(node) { + return ts.isPropertyAccessExpression(node) && isEntityNameExpression(node.expression); + } + ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression; + function isPrototypeAccess(node) { + return ts.isPropertyAccessExpression(node) && node.name.escapedText === "prototype"; + } + ts.isPrototypeAccess = isPrototypeAccess; function isRightSideOfQualifiedNameOrPropertyAccess(node) { - return (node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node) || - (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node); + return (node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node) || + (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node); } ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess; function isEmptyObjectLiteral(expression) { - return expression.kind === 182 /* ObjectLiteralExpression */ && + return expression.kind === 186 /* ObjectLiteralExpression */ && expression.properties.length === 0; } ts.isEmptyObjectLiteral = isEmptyObjectLiteral; function isEmptyArrayLiteral(expression) { - return expression.kind === 181 /* ArrayLiteralExpression */ && + return expression.kind === 185 /* ArrayLiteralExpression */ && expression.elements.length === 0; } ts.isEmptyArrayLiteral = isEmptyArrayLiteral; @@ -10899,7 +10463,7 @@ var ts; var length = input.length; for (var i = 0; i < length; i++) { var charCode = input.charCodeAt(i); - // handel utf8 + // handle utf8 if (charCode < 0x80) { output.push(charCode); } @@ -10956,6 +10520,78 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function getStringFromExpandedCharCodes(codes) { + var output = ""; + var i = 0; + var length = codes.length; + while (i < length) { + var charCode = codes[i]; + if (charCode < 0x80) { + output += String.fromCharCode(charCode); + i++; + } + else if ((charCode & 192) === 192) { + var value = charCode & 63; + i++; + var nextCode = codes[i]; + while ((nextCode & 192) === 128) { + value = (value << 6) | (nextCode & 63); + i++; + nextCode = codes[i]; + } + // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us + output += String.fromCharCode(value); + } + else { + // We don't want to kill the process when decoding fails (due to a following char byte not + // following a leading char), so we just print the (bad) value + output += String.fromCharCode(charCode); + i++; + } + } + return output; + } + function base64encode(host, input) { + if (host && host.base64encode) { + return host.base64encode(input); + } + return convertToBase64(input); + } + ts.base64encode = base64encode; + function base64decode(host, input) { + if (host && host.base64decode) { + return host.base64decode(input); + } + var length = input.length; + var expandedCharCodes = []; + var i = 0; + while (i < length) { + // Stop decoding once padding characters are present + if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) { + break; + } + // convert 4 input digits into three characters, ignoring padding characters at the end + var ch1 = base64Digits.indexOf(input[i]); + var ch2 = base64Digits.indexOf(input[i + 1]); + var ch3 = base64Digits.indexOf(input[i + 2]); + var ch4 = base64Digits.indexOf(input[i + 3]); + var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3); + var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15); + var code3 = ((ch3 & 3) << 6) | (ch4 & 63); + if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3 + expandedCharCodes.push(code1); + } + else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3 + expandedCharCodes.push(code1, code2); + } + else { + expandedCharCodes.push(code1, code2, code3); + } + i += 4; + } + return getStringFromExpandedCharCodes(expandedCharCodes); + } + ts.base64decode = base64decode; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options, getNewLine) { @@ -11143,8 +10779,8 @@ var ts; var parseNode = ts.getParseTreeNode(node); if (parseNode) { switch (parseNode.parent.kind) { - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return parseNode === parseNode.parent.name; } } @@ -11163,6 +10799,10 @@ var ts; return options.watch && options.hasOwnProperty("watch"); } ts.isWatchSet = isWatchSet; + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; function getCheckFlags(symbol) { return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0; } @@ -11217,21 +10857,21 @@ var ts; if (!parent) return 0 /* Read */; switch (parent.kind) { - case 197 /* PostfixUnaryExpression */: - case 196 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: var operator = parent.operator; return operator === 43 /* PlusPlusToken */ || operator === 44 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var _a = parent, left = _a.left, operatorToken = _a.operatorToken; return left === node && isAssignmentOperator(operatorToken.kind) ? writeOrReadWrite() : 0 /* Read */; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return parent.name !== node ? 0 /* Read */ : accessKind(parent); default: return 0 /* Read */; } function writeOrReadWrite() { // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect. - return parent.parent && parent.parent.kind === 214 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; + return parent.parent && parent.parent.kind === 219 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */; } } function compareDataObjects(dst, src) { @@ -11322,7 +10962,7 @@ var ts; } ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol; function getObjectFlags(type) { - return type.flags & 65536 /* Object */ ? type.objectFlags : 0; + return type.flags & 131072 /* Object */ ? type.objectFlags : 0; } ts.getObjectFlags = getObjectFlags; function typeHasCallOrConstructSignatures(type, checker) { @@ -11334,7 +10974,7 @@ var ts; } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { - return symbol && symbol.declarations && symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); + return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } ts.isUMDExportSymbol = isUMDExportSymbol; function showModuleSpecifier(_a) { @@ -11342,12 +10982,45 @@ var ts; return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); } ts.showModuleSpecifier = showModuleSpecifier; + function getLastChild(node) { + var lastChild; + ts.forEachChild(node, function (child) { + if (nodeIsPresent(child)) + lastChild = child; + }, function (children) { + // As an optimization, jump straight to the end of the list. + for (var i = children.length - 1; i >= 0; i--) { + if (nodeIsPresent(children[i])) { + lastChild = children[i]; + break; + } + } + }); + return lastChild; + } + ts.getLastChild = getLastChild; + function addToSeen(seen, key, value) { + if (value === void 0) { value = true; } + key = String(key); + if (seen.has(key)) { + return false; + } + seen.set(key, value); + return true; + } + ts.addToSeen = addToSeen; + function isObjectTypeDeclaration(node) { + return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); + } + ts.isObjectTypeDeclaration = isObjectTypeDeclaration; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { switch (options.target) { case 6 /* ESNext */: return "lib.esnext.full.d.ts"; + case 5 /* ES2018 */: + return "lib.es2018.full.d.ts"; case 4 /* ES2017 */: return "lib.es2017.full.d.ts"; case 3 /* ES2016 */: @@ -11371,6 +11044,11 @@ var ts; return position >= span.start && position < textSpanEnd(span); } ts.textSpanContainsPosition = textSpanContainsPosition; + /* @internal */ + function textRangeContainsPositionInclusive(span, position) { + return position >= span.pos && position <= span.end; + } + ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive; // Returns true if 'span' contains 'other'. function textSpanContainsTextSpan(span, other) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); @@ -11419,6 +11097,13 @@ var ts; return { start: start, length: length }; } ts.createTextSpan = createTextSpan; + /* @internal */ + function createTextRange(pos, end) { + if (end === void 0) { end = pos; } + ts.Debug.assert(end >= pos); + return { pos: pos, end: end }; + } + ts.createTextRange = createTextRange; function createTextSpanFromBounds(start, end) { return createTextSpan(start, end - start); } @@ -11555,9 +11240,9 @@ var ts; } ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; function getTypeParameterOwner(d) { - if (d && d.kind === 147 /* TypeParameter */) { + if (d && d.kind === 148 /* TypeParameter */) { for (var current = d; current; current = current.parent) { - if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 234 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(current) || ts.isClassLike(current) || current.kind === 239 /* InterfaceDeclaration */) { return current; } } @@ -11565,7 +11250,7 @@ var ts; } ts.getTypeParameterOwner = getTypeParameterOwner; function isParameterPropertyDeclaration(node) { - return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 154 /* Constructor */ && ts.isClassLike(node.parent.parent); + return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && node.parent.kind === 155 /* Constructor */; } ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration; function isEmptyBindingPattern(node) { @@ -11582,27 +11267,34 @@ var ts; return isEmptyBindingPattern(node.name); } ts.isEmptyBindingElement = isEmptyBindingElement; - function walkUpBindingElementsAndPatterns(node) { - while (node && (node.kind === 180 /* BindingElement */ || ts.isBindingPattern(node))) { - node = node.parent; + function walkUpBindingElementsAndPatterns(binding) { + var node = binding.parent; + while (ts.isBindingElement(node.parent)) { + node = node.parent.parent; } - return node; + return node.parent; } - function getCombinedModifierFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = ts.getModifierFlags(node); - if (node.kind === 230 /* VariableDeclaration */) { + ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns; + function getCombinedFlags(node, getFlags) { + if (ts.isBindingElement(node)) { + node = walkUpBindingElementsAndPatterns(node); + } + var flags = getFlags(node); + if (node.kind === 235 /* VariableDeclaration */) { node = node.parent; } - if (node && node.kind === 231 /* VariableDeclarationList */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 236 /* VariableDeclarationList */) { + flags |= getFlags(node); node = node.parent; } - if (node && node.kind === 212 /* VariableStatement */) { - flags |= ts.getModifierFlags(node); + if (node && node.kind === 217 /* VariableStatement */) { + flags |= getFlags(node); } return flags; } + function getCombinedModifierFlags(node) { + return getCombinedFlags(node, ts.getModifierFlags); + } ts.getCombinedModifierFlags = getCombinedModifierFlags; // Returns the node flags for this node and all relevant parent nodes. This is done so that // nodes like variable declarations and binding elements can returned a view of their flags @@ -11612,19 +11304,7 @@ var ts; // list. By calling this function, all those flags are combined so that the client can treat // the node as if it actually had those flags. function getCombinedNodeFlags(node) { - node = walkUpBindingElementsAndPatterns(node); - var flags = node.flags; - if (node.kind === 230 /* VariableDeclaration */) { - node = node.parent; - } - if (node && node.kind === 231 /* VariableDeclarationList */) { - flags |= node.flags; - node = node.parent; - } - if (node && node.kind === 212 /* VariableStatement */) { - flags |= node.flags; - } - return flags; + return getCombinedFlags(node, function (n) { return n.flags; }); } ts.getCombinedNodeFlags = getCombinedNodeFlags; /** @@ -11674,7 +11354,7 @@ var ts; // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } - catch (e) { + catch (_a) { if (errors) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath)); } @@ -11732,16 +11412,6 @@ var ts; return unescapeLeadingUnderscores(symbol.escapedName); } ts.symbolName = symbolName; - /** - * Remove extra underscore from escaped identifier text content. - * @deprecated Use `id.text` for the unescaped text. - * @param identifier The escaped identifier text. - * @returns The unescaped identifier text. - */ - function unescapeIdentifier(id) { - return id; - } - ts.unescapeIdentifier = unescapeIdentifier; /** * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol @@ -11758,17 +11428,17 @@ var ts; } // Covers remaining cases switch (hostNode.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); } return undefined; - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: var expr = hostNode.expression; switch (expr.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return expr.name; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: var arg = expr.argumentExpression; if (ts.isIdentifier(arg)) { return arg; @@ -11777,10 +11447,10 @@ var ts; return undefined; case 1 /* EndOfFileToken */: return undefined; - case 189 /* ParenthesizedExpression */: { + case 193 /* ParenthesizedExpression */: { return getDeclarationIdentifier(hostNode.expression); } - case 226 /* LabeledStatement */: { + case 231 /* LabeledStatement */: { if (ts.isDeclaration(hostNode.statement) || ts.isExpression(hostNode.statement)) { return getDeclarationIdentifier(hostNode.statement); } @@ -11792,7 +11462,7 @@ var ts; } function getDeclarationIdentifier(node) { var name = getNameOfDeclaration(node); - return ts.isIdentifier(name) ? name : undefined; + return name && ts.isIdentifier(name) ? name : undefined; } function getNameOfJSDocTypedef(declaration) { return declaration.name || nameForNamelessJSDocTypedef(declaration); @@ -11803,22 +11473,20 @@ var ts; return !!node.name; // A 'name' property should always be a DeclarationName. } ts.isNamedDeclaration = isNamedDeclaration; - function getNameOfDeclaration(declaration) { - if (!declaration) { - return undefined; - } + /** @internal */ + function getNonAssignedNameOfDeclaration(declaration) { switch (declaration.kind) { case 71 /* Identifier */: return declaration; - case 292 /* JSDocPropertyTag */: - case 287 /* JSDocParameterTag */: { + case 302 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: { var name = declaration.name; - if (name.kind === 145 /* QualifiedName */) { + if (name.kind === 146 /* QualifiedName */) { return name.right; } break; } - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var expr = declaration; switch (ts.getSpecialPropertyAssignmentKind(expr)) { case 1 /* ExportsProperty */: @@ -11830,16 +11498,39 @@ var ts; return undefined; } } - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: return getNameOfJSDocTypedef(declaration); - case 247 /* ExportAssignment */: { + case 252 /* ExportAssignment */: { var expression = declaration.expression; return ts.isIdentifier(expression) ? expression : undefined; } } return declaration.name; } + ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration; + function getNameOfDeclaration(declaration) { + if (declaration === undefined) + return undefined; + return getNonAssignedNameOfDeclaration(declaration) || + (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + } ts.getNameOfDeclaration = getNameOfDeclaration; + function getAssignedName(node) { + if (!node.parent) { + return undefined; + } + else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) { + return node.parent.name; + } + else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) { + if (ts.isIdentifier(node.parent.left)) { + return node.parent.left; + } + else if (ts.isPropertyAccessExpression(node.parent.left)) { + return node.parent.left.name; + } + } + } /** * Gets the JSDoc parameter tags for the node if present. * @@ -11854,12 +11545,22 @@ var ts; * parameters by name and binding patterns do not have a name. */ 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; }); + if (param.name) { + if (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; }); + } + else { + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); + var paramTags = getJSDocTags(param.parent).filter(ts.isJSDocParameterTag); + if (i < paramTags.length) { + return [paramTags[i]]; + } + } } - // a binding pattern doesn't have a name, so it's not possible to match it a JSDoc parameter, which is identified by name - return undefined; + // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters + return ts.emptyArray; } ts.getJSDocParameterTags = getJSDocParameterTags; /** @@ -11869,33 +11570,38 @@ var ts; * for example on a variable declaration whose initializer is a function expression. */ function hasJSDocParameterTags(node) { - return !!getFirstJSDocTag(node, 287 /* JSDocParameterTag */); + return !!getFirstJSDocTag(node, ts.isJSDocParameterTag); } ts.hasJSDocParameterTags = hasJSDocParameterTags; /** Gets the JSDoc augments tag for the node if present */ function getJSDocAugmentsTag(node) { - return getFirstJSDocTag(node, 285 /* JSDocAugmentsTag */); + return getFirstJSDocTag(node, ts.isJSDocAugmentsTag); } ts.getJSDocAugmentsTag = getJSDocAugmentsTag; /** Gets the JSDoc class tag for the node if present */ function getJSDocClassTag(node) { - return getFirstJSDocTag(node, 286 /* JSDocClassTag */); + return getFirstJSDocTag(node, ts.isJSDocClassTag); } ts.getJSDocClassTag = getJSDocClassTag; + /** Gets the JSDoc this tag for the node if present */ + function getJSDocThisTag(node) { + return getFirstJSDocTag(node, ts.isJSDocThisTag); + } + ts.getJSDocThisTag = getJSDocThisTag; /** Gets the JSDoc return tag for the node if present */ function getJSDocReturnTag(node) { - return getFirstJSDocTag(node, 288 /* JSDocReturnTag */); + return getFirstJSDocTag(node, ts.isJSDocReturnTag); } ts.getJSDocReturnTag = getJSDocReturnTag; /** Gets the JSDoc template tag for the node if present */ function getJSDocTemplateTag(node) { - return getFirstJSDocTag(node, 290 /* JSDocTemplateTag */); + return getFirstJSDocTag(node, ts.isJSDocTemplateTag); } ts.getJSDocTemplateTag = getJSDocTemplateTag; /** Gets the JSDoc type tag for the node if present and valid */ function getJSDocTypeTag(node) { // We should have already issued an error if there were multiple type jsdocs, so just use the first one. - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); if (tag && tag.typeExpression && tag.typeExpression.type) { return tag; } @@ -11914,25 +11620,35 @@ var ts; * tag directly on the node would be returned. */ function getJSDocType(node) { - var tag = getFirstJSDocTag(node, 289 /* JSDocTypeTag */); - if (!tag && node.kind === 148 /* Parameter */) { - var paramTags = getJSDocParameterTags(node); - if (paramTags) { - tag = ts.find(paramTags, function (tag) { return !!tag.typeExpression; }); - } + var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag); + if (!tag && ts.isParameter(node)) { + tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; }); } return tag && tag.typeExpression && tag.typeExpression.type; } ts.getJSDocType = getJSDocType; /** - * Gets the return type node for the node if provided via JSDoc's return tag. + * Gets the return type node for the node if provided via JSDoc return tag or type tag. * * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function - * gets the type from inside the braces. + * gets the type from inside the braces, after the fat arrow, etc. */ function getJSDocReturnType(node) { var returnTag = getJSDocReturnTag(node); - return returnTag && returnTag.typeExpression && returnTag.typeExpression.type; + if (returnTag && returnTag.typeExpression) { + return returnTag.typeExpression.type; + } + var typeTag = getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression) { + var type = typeTag.typeExpression.type; + if (ts.isTypeLiteralNode(type)) { + var sig = ts.find(type.members, ts.isCallSignatureDeclaration); + return sig && sig.type; + } + if (ts.isFunctionTypeNode(type)) { + return type.type; + } + } } ts.getJSDocReturnType = getJSDocReturnType; /** Get all JSDoc tags related to a node, including those on parent nodes. */ @@ -11940,22 +11656,37 @@ var ts; var tags = node.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined) { - node.jsDocCache = tags = ts.flatMap(ts.getJSDocCommentsAndTags(node), function (j) { return ts.isJSDoc(j) ? j.tags : j; }); + var comments = ts.getJSDocCommentsAndTags(node); + ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]); + node.jsDocCache = tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; }); } return tags; } ts.getJSDocTags = getJSDocTags; /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ - function getFirstJSDocTag(node, kind) { - var tags = getJSDocTags(node); - return ts.find(tags, function (doc) { return doc.kind === kind; }); + function getFirstJSDocTag(node, predicate) { + return ts.find(getJSDocTags(node), predicate); } /** Gets all JSDoc tags of a specified kind, or undefined if not present. */ function getAllJSDocTagsOfKind(node, kind) { - var tags = getJSDocTags(node); - return ts.filter(tags, function (doc) { return doc.kind === kind; }); + return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; }); } ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind; + /** + * Gets the effective type parameters. If the node was parsed in a + * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. + */ + function getEffectiveTypeParameterDeclarations(node) { + if (ts.isJSDocSignature(node)) { + return ts.emptyArray; + } + if (ts.isJSDocTypeAlias(node)) { + ts.Debug.assert(node.parent.kind === 289 /* JSDocComment */); + return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; }); + } + return node.typeParameters || (ts.isInJavaScriptFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : ts.emptyArray); + } + ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations; })(ts || (ts = {})); // Simple node tests of the form `node.kind === SyntaxKind.Foo`. (function (ts) { @@ -11999,618 +11730,647 @@ var ts; ts.isIdentifier = isIdentifier; // Names function isQualifiedName(node) { - return node.kind === 145 /* QualifiedName */; + return node.kind === 146 /* QualifiedName */; } ts.isQualifiedName = isQualifiedName; function isComputedPropertyName(node) { - return node.kind === 146 /* ComputedPropertyName */; + return node.kind === 147 /* ComputedPropertyName */; } ts.isComputedPropertyName = isComputedPropertyName; // Signature elements function isTypeParameterDeclaration(node) { - return node.kind === 147 /* TypeParameter */; + return node.kind === 148 /* TypeParameter */; } ts.isTypeParameterDeclaration = isTypeParameterDeclaration; function isParameter(node) { - return node.kind === 148 /* Parameter */; + return node.kind === 149 /* Parameter */; } ts.isParameter = isParameter; function isDecorator(node) { - return node.kind === 149 /* Decorator */; + return node.kind === 150 /* Decorator */; } ts.isDecorator = isDecorator; // TypeMember function isPropertySignature(node) { - return node.kind === 150 /* PropertySignature */; + return node.kind === 151 /* PropertySignature */; } ts.isPropertySignature = isPropertySignature; function isPropertyDeclaration(node) { - return node.kind === 151 /* PropertyDeclaration */; + return node.kind === 152 /* PropertyDeclaration */; } ts.isPropertyDeclaration = isPropertyDeclaration; function isMethodSignature(node) { - return node.kind === 152 /* MethodSignature */; + return node.kind === 153 /* MethodSignature */; } ts.isMethodSignature = isMethodSignature; function isMethodDeclaration(node) { - return node.kind === 153 /* MethodDeclaration */; + return node.kind === 154 /* MethodDeclaration */; } ts.isMethodDeclaration = isMethodDeclaration; function isConstructorDeclaration(node) { - return node.kind === 154 /* Constructor */; + return node.kind === 155 /* Constructor */; } ts.isConstructorDeclaration = isConstructorDeclaration; function isGetAccessorDeclaration(node) { - return node.kind === 155 /* GetAccessor */; + return node.kind === 156 /* GetAccessor */; } ts.isGetAccessorDeclaration = isGetAccessorDeclaration; function isSetAccessorDeclaration(node) { - return node.kind === 156 /* SetAccessor */; + return node.kind === 157 /* SetAccessor */; } ts.isSetAccessorDeclaration = isSetAccessorDeclaration; function isCallSignatureDeclaration(node) { - return node.kind === 157 /* CallSignature */; + return node.kind === 158 /* CallSignature */; } ts.isCallSignatureDeclaration = isCallSignatureDeclaration; function isConstructSignatureDeclaration(node) { - return node.kind === 158 /* ConstructSignature */; + return node.kind === 159 /* ConstructSignature */; } ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration; function isIndexSignatureDeclaration(node) { - return node.kind === 159 /* IndexSignature */; + return node.kind === 160 /* IndexSignature */; } ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration; + /* @internal */ + function isGetOrSetAccessorDeclaration(node) { + return node.kind === 157 /* SetAccessor */ || node.kind === 156 /* GetAccessor */; + } + ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration; // Type function isTypePredicateNode(node) { - return node.kind === 160 /* TypePredicate */; + return node.kind === 161 /* TypePredicate */; } ts.isTypePredicateNode = isTypePredicateNode; function isTypeReferenceNode(node) { - return node.kind === 161 /* TypeReference */; + return node.kind === 162 /* TypeReference */; } ts.isTypeReferenceNode = isTypeReferenceNode; function isFunctionTypeNode(node) { - return node.kind === 162 /* FunctionType */; + return node.kind === 163 /* FunctionType */; } ts.isFunctionTypeNode = isFunctionTypeNode; function isConstructorTypeNode(node) { - return node.kind === 163 /* ConstructorType */; + return node.kind === 164 /* ConstructorType */; } ts.isConstructorTypeNode = isConstructorTypeNode; function isTypeQueryNode(node) { - return node.kind === 164 /* TypeQuery */; + return node.kind === 165 /* TypeQuery */; } ts.isTypeQueryNode = isTypeQueryNode; function isTypeLiteralNode(node) { - return node.kind === 165 /* TypeLiteral */; + return node.kind === 166 /* TypeLiteral */; } ts.isTypeLiteralNode = isTypeLiteralNode; function isArrayTypeNode(node) { - return node.kind === 166 /* ArrayType */; + return node.kind === 167 /* ArrayType */; } ts.isArrayTypeNode = isArrayTypeNode; function isTupleTypeNode(node) { - return node.kind === 167 /* TupleType */; + return node.kind === 168 /* TupleType */; } ts.isTupleTypeNode = isTupleTypeNode; function isUnionTypeNode(node) { - return node.kind === 168 /* UnionType */; + return node.kind === 171 /* UnionType */; } ts.isUnionTypeNode = isUnionTypeNode; function isIntersectionTypeNode(node) { - return node.kind === 169 /* IntersectionType */; + return node.kind === 172 /* IntersectionType */; } ts.isIntersectionTypeNode = isIntersectionTypeNode; function isConditionalTypeNode(node) { - return node.kind === 170 /* ConditionalType */; + return node.kind === 173 /* ConditionalType */; } ts.isConditionalTypeNode = isConditionalTypeNode; function isInferTypeNode(node) { - return node.kind === 171 /* InferType */; + return node.kind === 174 /* InferType */; } ts.isInferTypeNode = isInferTypeNode; function isParenthesizedTypeNode(node) { - return node.kind === 172 /* ParenthesizedType */; + return node.kind === 175 /* ParenthesizedType */; } ts.isParenthesizedTypeNode = isParenthesizedTypeNode; function isThisTypeNode(node) { - return node.kind === 173 /* ThisType */; + return node.kind === 176 /* ThisType */; } ts.isThisTypeNode = isThisTypeNode; function isTypeOperatorNode(node) { - return node.kind === 174 /* TypeOperator */; + return node.kind === 177 /* TypeOperator */; } ts.isTypeOperatorNode = isTypeOperatorNode; function isIndexedAccessTypeNode(node) { - return node.kind === 175 /* IndexedAccessType */; + return node.kind === 178 /* IndexedAccessType */; } ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode; function isMappedTypeNode(node) { - return node.kind === 176 /* MappedType */; + return node.kind === 179 /* MappedType */; } ts.isMappedTypeNode = isMappedTypeNode; function isLiteralTypeNode(node) { - return node.kind === 177 /* LiteralType */; + return node.kind === 180 /* LiteralType */; } ts.isLiteralTypeNode = isLiteralTypeNode; + function isImportTypeNode(node) { + return node.kind === 181 /* ImportType */; + } + ts.isImportTypeNode = isImportTypeNode; // Binding patterns function isObjectBindingPattern(node) { - return node.kind === 178 /* ObjectBindingPattern */; + return node.kind === 182 /* ObjectBindingPattern */; } ts.isObjectBindingPattern = isObjectBindingPattern; function isArrayBindingPattern(node) { - return node.kind === 179 /* ArrayBindingPattern */; + return node.kind === 183 /* ArrayBindingPattern */; } ts.isArrayBindingPattern = isArrayBindingPattern; function isBindingElement(node) { - return node.kind === 180 /* BindingElement */; + return node.kind === 184 /* BindingElement */; } ts.isBindingElement = isBindingElement; // Expression function isArrayLiteralExpression(node) { - return node.kind === 181 /* ArrayLiteralExpression */; + return node.kind === 185 /* ArrayLiteralExpression */; } ts.isArrayLiteralExpression = isArrayLiteralExpression; function isObjectLiteralExpression(node) { - return node.kind === 182 /* ObjectLiteralExpression */; + return node.kind === 186 /* ObjectLiteralExpression */; } ts.isObjectLiteralExpression = isObjectLiteralExpression; function isPropertyAccessExpression(node) { - return node.kind === 183 /* PropertyAccessExpression */; + return node.kind === 187 /* PropertyAccessExpression */; } ts.isPropertyAccessExpression = isPropertyAccessExpression; function isElementAccessExpression(node) { - return node.kind === 184 /* ElementAccessExpression */; + return node.kind === 188 /* ElementAccessExpression */; } ts.isElementAccessExpression = isElementAccessExpression; function isCallExpression(node) { - return node.kind === 185 /* CallExpression */; + return node.kind === 189 /* CallExpression */; } ts.isCallExpression = isCallExpression; function isNewExpression(node) { - return node.kind === 186 /* NewExpression */; + return node.kind === 190 /* NewExpression */; } ts.isNewExpression = isNewExpression; function isTaggedTemplateExpression(node) { - return node.kind === 187 /* TaggedTemplateExpression */; + return node.kind === 191 /* TaggedTemplateExpression */; } ts.isTaggedTemplateExpression = isTaggedTemplateExpression; function isTypeAssertion(node) { - return node.kind === 188 /* TypeAssertionExpression */; + return node.kind === 192 /* TypeAssertionExpression */; } ts.isTypeAssertion = isTypeAssertion; function isParenthesizedExpression(node) { - return node.kind === 189 /* ParenthesizedExpression */; + return node.kind === 193 /* ParenthesizedExpression */; } ts.isParenthesizedExpression = isParenthesizedExpression; function skipPartiallyEmittedExpressions(node) { - while (node.kind === 295 /* PartiallyEmittedExpression */) { + while (node.kind === 305 /* PartiallyEmittedExpression */) { node = node.expression; } return node; } ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions; function isFunctionExpression(node) { - return node.kind === 190 /* FunctionExpression */; + return node.kind === 194 /* FunctionExpression */; } ts.isFunctionExpression = isFunctionExpression; function isArrowFunction(node) { - return node.kind === 191 /* ArrowFunction */; + return node.kind === 195 /* ArrowFunction */; } ts.isArrowFunction = isArrowFunction; function isDeleteExpression(node) { - return node.kind === 192 /* DeleteExpression */; + return node.kind === 196 /* DeleteExpression */; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 193 /* TypeOfExpression */; + return node.kind === 197 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { - return node.kind === 194 /* VoidExpression */; + return node.kind === 198 /* VoidExpression */; } ts.isVoidExpression = isVoidExpression; function isAwaitExpression(node) { - return node.kind === 195 /* AwaitExpression */; + return node.kind === 199 /* AwaitExpression */; } ts.isAwaitExpression = isAwaitExpression; function isPrefixUnaryExpression(node) { - return node.kind === 196 /* PrefixUnaryExpression */; + return node.kind === 200 /* PrefixUnaryExpression */; } ts.isPrefixUnaryExpression = isPrefixUnaryExpression; function isPostfixUnaryExpression(node) { - return node.kind === 197 /* PostfixUnaryExpression */; + return node.kind === 201 /* PostfixUnaryExpression */; } ts.isPostfixUnaryExpression = isPostfixUnaryExpression; function isBinaryExpression(node) { - return node.kind === 198 /* BinaryExpression */; + return node.kind === 202 /* BinaryExpression */; } ts.isBinaryExpression = isBinaryExpression; function isConditionalExpression(node) { - return node.kind === 199 /* ConditionalExpression */; + return node.kind === 203 /* ConditionalExpression */; } ts.isConditionalExpression = isConditionalExpression; function isTemplateExpression(node) { - return node.kind === 200 /* TemplateExpression */; + return node.kind === 204 /* TemplateExpression */; } ts.isTemplateExpression = isTemplateExpression; function isYieldExpression(node) { - return node.kind === 201 /* YieldExpression */; + return node.kind === 205 /* YieldExpression */; } ts.isYieldExpression = isYieldExpression; function isSpreadElement(node) { - return node.kind === 202 /* SpreadElement */; + return node.kind === 206 /* SpreadElement */; } ts.isSpreadElement = isSpreadElement; function isClassExpression(node) { - return node.kind === 203 /* ClassExpression */; + return node.kind === 207 /* ClassExpression */; } ts.isClassExpression = isClassExpression; function isOmittedExpression(node) { - return node.kind === 204 /* OmittedExpression */; + return node.kind === 208 /* OmittedExpression */; } ts.isOmittedExpression = isOmittedExpression; function isExpressionWithTypeArguments(node) { - return node.kind === 205 /* ExpressionWithTypeArguments */; + return node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments; function isAsExpression(node) { - return node.kind === 206 /* AsExpression */; + return node.kind === 210 /* AsExpression */; } ts.isAsExpression = isAsExpression; function isNonNullExpression(node) { - return node.kind === 207 /* NonNullExpression */; + return node.kind === 211 /* NonNullExpression */; } ts.isNonNullExpression = isNonNullExpression; function isMetaProperty(node) { - return node.kind === 208 /* MetaProperty */; + return node.kind === 212 /* MetaProperty */; } ts.isMetaProperty = isMetaProperty; // Misc function isTemplateSpan(node) { - return node.kind === 209 /* TemplateSpan */; + return node.kind === 214 /* TemplateSpan */; } ts.isTemplateSpan = isTemplateSpan; function isSemicolonClassElement(node) { - return node.kind === 210 /* SemicolonClassElement */; + return node.kind === 215 /* SemicolonClassElement */; } ts.isSemicolonClassElement = isSemicolonClassElement; // Block function isBlock(node) { - return node.kind === 211 /* Block */; + return node.kind === 216 /* Block */; } ts.isBlock = isBlock; function isVariableStatement(node) { - return node.kind === 212 /* VariableStatement */; + return node.kind === 217 /* VariableStatement */; } ts.isVariableStatement = isVariableStatement; function isEmptyStatement(node) { - return node.kind === 213 /* EmptyStatement */; + return node.kind === 218 /* EmptyStatement */; } ts.isEmptyStatement = isEmptyStatement; function isExpressionStatement(node) { - return node.kind === 214 /* ExpressionStatement */; + return node.kind === 219 /* ExpressionStatement */; } ts.isExpressionStatement = isExpressionStatement; function isIfStatement(node) { - return node.kind === 215 /* IfStatement */; + return node.kind === 220 /* IfStatement */; } ts.isIfStatement = isIfStatement; function isDoStatement(node) { - return node.kind === 216 /* DoStatement */; + return node.kind === 221 /* DoStatement */; } ts.isDoStatement = isDoStatement; function isWhileStatement(node) { - return node.kind === 217 /* WhileStatement */; + return node.kind === 222 /* WhileStatement */; } ts.isWhileStatement = isWhileStatement; function isForStatement(node) { - return node.kind === 218 /* ForStatement */; + return node.kind === 223 /* ForStatement */; } ts.isForStatement = isForStatement; function isForInStatement(node) { - return node.kind === 219 /* ForInStatement */; + return node.kind === 224 /* ForInStatement */; } ts.isForInStatement = isForInStatement; function isForOfStatement(node) { - return node.kind === 220 /* ForOfStatement */; + return node.kind === 225 /* ForOfStatement */; } ts.isForOfStatement = isForOfStatement; function isContinueStatement(node) { - return node.kind === 221 /* ContinueStatement */; + return node.kind === 226 /* ContinueStatement */; } ts.isContinueStatement = isContinueStatement; function isBreakStatement(node) { - return node.kind === 222 /* BreakStatement */; + return node.kind === 227 /* BreakStatement */; } ts.isBreakStatement = isBreakStatement; function isBreakOrContinueStatement(node) { - return node.kind === 222 /* BreakStatement */ || node.kind === 221 /* ContinueStatement */; + return node.kind === 227 /* BreakStatement */ || node.kind === 226 /* ContinueStatement */; } ts.isBreakOrContinueStatement = isBreakOrContinueStatement; function isReturnStatement(node) { - return node.kind === 223 /* ReturnStatement */; + return node.kind === 228 /* ReturnStatement */; } ts.isReturnStatement = isReturnStatement; function isWithStatement(node) { - return node.kind === 224 /* WithStatement */; + return node.kind === 229 /* WithStatement */; } ts.isWithStatement = isWithStatement; function isSwitchStatement(node) { - return node.kind === 225 /* SwitchStatement */; + return node.kind === 230 /* SwitchStatement */; } ts.isSwitchStatement = isSwitchStatement; function isLabeledStatement(node) { - return node.kind === 226 /* LabeledStatement */; + return node.kind === 231 /* LabeledStatement */; } ts.isLabeledStatement = isLabeledStatement; function isThrowStatement(node) { - return node.kind === 227 /* ThrowStatement */; + return node.kind === 232 /* ThrowStatement */; } ts.isThrowStatement = isThrowStatement; function isTryStatement(node) { - return node.kind === 228 /* TryStatement */; + return node.kind === 233 /* TryStatement */; } ts.isTryStatement = isTryStatement; function isDebuggerStatement(node) { - return node.kind === 229 /* DebuggerStatement */; + return node.kind === 234 /* DebuggerStatement */; } ts.isDebuggerStatement = isDebuggerStatement; function isVariableDeclaration(node) { - return node.kind === 230 /* VariableDeclaration */; + return node.kind === 235 /* VariableDeclaration */; } ts.isVariableDeclaration = isVariableDeclaration; function isVariableDeclarationList(node) { - return node.kind === 231 /* VariableDeclarationList */; + return node.kind === 236 /* VariableDeclarationList */; } ts.isVariableDeclarationList = isVariableDeclarationList; function isFunctionDeclaration(node) { - return node.kind === 232 /* FunctionDeclaration */; + return node.kind === 237 /* FunctionDeclaration */; } ts.isFunctionDeclaration = isFunctionDeclaration; function isClassDeclaration(node) { - return node.kind === 233 /* ClassDeclaration */; + return node.kind === 238 /* ClassDeclaration */; } ts.isClassDeclaration = isClassDeclaration; function isInterfaceDeclaration(node) { - return node.kind === 234 /* InterfaceDeclaration */; + return node.kind === 239 /* InterfaceDeclaration */; } ts.isInterfaceDeclaration = isInterfaceDeclaration; function isTypeAliasDeclaration(node) { - return node.kind === 235 /* TypeAliasDeclaration */; + return node.kind === 240 /* TypeAliasDeclaration */; } ts.isTypeAliasDeclaration = isTypeAliasDeclaration; function isEnumDeclaration(node) { - return node.kind === 236 /* EnumDeclaration */; + return node.kind === 241 /* EnumDeclaration */; } ts.isEnumDeclaration = isEnumDeclaration; function isModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */; + return node.kind === 242 /* ModuleDeclaration */; } ts.isModuleDeclaration = isModuleDeclaration; function isModuleBlock(node) { - return node.kind === 238 /* ModuleBlock */; + return node.kind === 243 /* ModuleBlock */; } ts.isModuleBlock = isModuleBlock; function isCaseBlock(node) { - return node.kind === 239 /* CaseBlock */; + return node.kind === 244 /* CaseBlock */; } ts.isCaseBlock = isCaseBlock; function isNamespaceExportDeclaration(node) { - return node.kind === 240 /* NamespaceExportDeclaration */; + return node.kind === 245 /* NamespaceExportDeclaration */; } ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration; function isImportEqualsDeclaration(node) { - return node.kind === 241 /* ImportEqualsDeclaration */; + return node.kind === 246 /* ImportEqualsDeclaration */; } ts.isImportEqualsDeclaration = isImportEqualsDeclaration; function isImportDeclaration(node) { - return node.kind === 242 /* ImportDeclaration */; + return node.kind === 247 /* ImportDeclaration */; } ts.isImportDeclaration = isImportDeclaration; function isImportClause(node) { - return node.kind === 243 /* ImportClause */; + return node.kind === 248 /* ImportClause */; } ts.isImportClause = isImportClause; function isNamespaceImport(node) { - return node.kind === 244 /* NamespaceImport */; + return node.kind === 249 /* NamespaceImport */; } ts.isNamespaceImport = isNamespaceImport; function isNamedImports(node) { - return node.kind === 245 /* NamedImports */; + return node.kind === 250 /* NamedImports */; } ts.isNamedImports = isNamedImports; function isImportSpecifier(node) { - return node.kind === 246 /* ImportSpecifier */; + return node.kind === 251 /* ImportSpecifier */; } ts.isImportSpecifier = isImportSpecifier; function isExportAssignment(node) { - return node.kind === 247 /* ExportAssignment */; + return node.kind === 252 /* ExportAssignment */; } ts.isExportAssignment = isExportAssignment; function isExportDeclaration(node) { - return node.kind === 248 /* ExportDeclaration */; + return node.kind === 253 /* ExportDeclaration */; } ts.isExportDeclaration = isExportDeclaration; function isNamedExports(node) { - return node.kind === 249 /* NamedExports */; + return node.kind === 254 /* NamedExports */; } ts.isNamedExports = isNamedExports; function isExportSpecifier(node) { - return node.kind === 250 /* ExportSpecifier */; + return node.kind === 255 /* ExportSpecifier */; } ts.isExportSpecifier = isExportSpecifier; function isMissingDeclaration(node) { - return node.kind === 251 /* MissingDeclaration */; + return node.kind === 256 /* MissingDeclaration */; } ts.isMissingDeclaration = isMissingDeclaration; // Module References function isExternalModuleReference(node) { - return node.kind === 252 /* ExternalModuleReference */; + return node.kind === 257 /* ExternalModuleReference */; } ts.isExternalModuleReference = isExternalModuleReference; // JSX function isJsxElement(node) { - return node.kind === 253 /* JsxElement */; + return node.kind === 258 /* JsxElement */; } ts.isJsxElement = isJsxElement; function isJsxSelfClosingElement(node) { - return node.kind === 254 /* JsxSelfClosingElement */; + return node.kind === 259 /* JsxSelfClosingElement */; } ts.isJsxSelfClosingElement = isJsxSelfClosingElement; function isJsxOpeningElement(node) { - return node.kind === 255 /* JsxOpeningElement */; + return node.kind === 260 /* JsxOpeningElement */; } ts.isJsxOpeningElement = isJsxOpeningElement; function isJsxClosingElement(node) { - return node.kind === 256 /* JsxClosingElement */; + return node.kind === 261 /* JsxClosingElement */; } ts.isJsxClosingElement = isJsxClosingElement; function isJsxFragment(node) { - return node.kind === 257 /* JsxFragment */; + return node.kind === 262 /* JsxFragment */; } ts.isJsxFragment = isJsxFragment; function isJsxOpeningFragment(node) { - return node.kind === 258 /* JsxOpeningFragment */; + return node.kind === 263 /* JsxOpeningFragment */; } ts.isJsxOpeningFragment = isJsxOpeningFragment; function isJsxClosingFragment(node) { - return node.kind === 259 /* JsxClosingFragment */; + return node.kind === 264 /* JsxClosingFragment */; } ts.isJsxClosingFragment = isJsxClosingFragment; function isJsxAttribute(node) { - return node.kind === 260 /* JsxAttribute */; + return node.kind === 265 /* JsxAttribute */; } ts.isJsxAttribute = isJsxAttribute; function isJsxAttributes(node) { - return node.kind === 261 /* JsxAttributes */; + return node.kind === 266 /* JsxAttributes */; } ts.isJsxAttributes = isJsxAttributes; function isJsxSpreadAttribute(node) { - return node.kind === 262 /* JsxSpreadAttribute */; + return node.kind === 267 /* JsxSpreadAttribute */; } ts.isJsxSpreadAttribute = isJsxSpreadAttribute; function isJsxExpression(node) { - return node.kind === 263 /* JsxExpression */; + return node.kind === 268 /* JsxExpression */; } ts.isJsxExpression = isJsxExpression; // Clauses function isCaseClause(node) { - return node.kind === 264 /* CaseClause */; + return node.kind === 269 /* CaseClause */; } ts.isCaseClause = isCaseClause; function isDefaultClause(node) { - return node.kind === 265 /* DefaultClause */; + return node.kind === 270 /* DefaultClause */; } ts.isDefaultClause = isDefaultClause; function isHeritageClause(node) { - return node.kind === 266 /* HeritageClause */; + return node.kind === 271 /* HeritageClause */; } ts.isHeritageClause = isHeritageClause; function isCatchClause(node) { - return node.kind === 267 /* CatchClause */; + return node.kind === 272 /* CatchClause */; } ts.isCatchClause = isCatchClause; // Property assignments function isPropertyAssignment(node) { - return node.kind === 268 /* PropertyAssignment */; + return node.kind === 273 /* PropertyAssignment */; } ts.isPropertyAssignment = isPropertyAssignment; function isShorthandPropertyAssignment(node) { - return node.kind === 269 /* ShorthandPropertyAssignment */; + return node.kind === 274 /* ShorthandPropertyAssignment */; } ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment; function isSpreadAssignment(node) { - return node.kind === 270 /* SpreadAssignment */; + return node.kind === 275 /* SpreadAssignment */; } ts.isSpreadAssignment = isSpreadAssignment; // Enum function isEnumMember(node) { - return node.kind === 271 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } ts.isEnumMember = isEnumMember; // Top-level nodes function isSourceFile(node) { - return node.kind === 272 /* SourceFile */; + return node.kind === 277 /* SourceFile */; } ts.isSourceFile = isSourceFile; function isBundle(node) { - return node.kind === 273 /* Bundle */; + return node.kind === 278 /* Bundle */; } ts.isBundle = isBundle; + function isUnparsedSource(node) { + return node.kind === 279 /* UnparsedSource */; + } + ts.isUnparsedSource = isUnparsedSource; // JSDoc function isJSDocTypeExpression(node) { - return node.kind === 274 /* JSDocTypeExpression */; + return node.kind === 281 /* JSDocTypeExpression */; } ts.isJSDocTypeExpression = isJSDocTypeExpression; function isJSDocAllType(node) { - return node.kind === 275 /* JSDocAllType */; + return node.kind === 282 /* JSDocAllType */; } ts.isJSDocAllType = isJSDocAllType; function isJSDocUnknownType(node) { - return node.kind === 276 /* JSDocUnknownType */; + return node.kind === 283 /* JSDocUnknownType */; } ts.isJSDocUnknownType = isJSDocUnknownType; function isJSDocNullableType(node) { - return node.kind === 277 /* JSDocNullableType */; + return node.kind === 284 /* JSDocNullableType */; } ts.isJSDocNullableType = isJSDocNullableType; function isJSDocNonNullableType(node) { - return node.kind === 278 /* JSDocNonNullableType */; + return node.kind === 285 /* JSDocNonNullableType */; } ts.isJSDocNonNullableType = isJSDocNonNullableType; function isJSDocOptionalType(node) { - return node.kind === 279 /* JSDocOptionalType */; + return node.kind === 286 /* JSDocOptionalType */; } ts.isJSDocOptionalType = isJSDocOptionalType; function isJSDocFunctionType(node) { - return node.kind === 280 /* JSDocFunctionType */; + return node.kind === 287 /* JSDocFunctionType */; } ts.isJSDocFunctionType = isJSDocFunctionType; function isJSDocVariadicType(node) { - return node.kind === 281 /* JSDocVariadicType */; + return node.kind === 288 /* JSDocVariadicType */; } ts.isJSDocVariadicType = isJSDocVariadicType; function isJSDoc(node) { - return node.kind === 282 /* JSDocComment */; + return node.kind === 289 /* JSDocComment */; } ts.isJSDoc = isJSDoc; function isJSDocAugmentsTag(node) { - return node.kind === 285 /* JSDocAugmentsTag */; + return node.kind === 293 /* JSDocAugmentsTag */; } ts.isJSDocAugmentsTag = isJSDocAugmentsTag; + function isJSDocClassTag(node) { + return node.kind === 294 /* JSDocClassTag */; + } + ts.isJSDocClassTag = isJSDocClassTag; + function isJSDocThisTag(node) { + return node.kind === 298 /* JSDocThisTag */; + } + ts.isJSDocThisTag = isJSDocThisTag; function isJSDocParameterTag(node) { - return node.kind === 287 /* JSDocParameterTag */; + return node.kind === 296 /* JSDocParameterTag */; } ts.isJSDocParameterTag = isJSDocParameterTag; function isJSDocReturnTag(node) { - return node.kind === 288 /* JSDocReturnTag */; + return node.kind === 297 /* JSDocReturnTag */; } ts.isJSDocReturnTag = isJSDocReturnTag; function isJSDocTypeTag(node) { - return node.kind === 289 /* JSDocTypeTag */; + return node.kind === 299 /* JSDocTypeTag */; } ts.isJSDocTypeTag = isJSDocTypeTag; function isJSDocTemplateTag(node) { - return node.kind === 290 /* JSDocTemplateTag */; + return node.kind === 300 /* JSDocTemplateTag */; } ts.isJSDocTemplateTag = isJSDocTemplateTag; function isJSDocTypedefTag(node) { - return node.kind === 291 /* JSDocTypedefTag */; + return node.kind === 301 /* JSDocTypedefTag */; } ts.isJSDocTypedefTag = isJSDocTypedefTag; function isJSDocPropertyTag(node) { - return node.kind === 292 /* JSDocPropertyTag */; + return node.kind === 302 /* JSDocPropertyTag */; } ts.isJSDocPropertyTag = isJSDocPropertyTag; function isJSDocPropertyLikeTag(node) { - return node.kind === 292 /* JSDocPropertyTag */ || node.kind === 287 /* JSDocParameterTag */; + return node.kind === 302 /* JSDocPropertyTag */ || node.kind === 296 /* JSDocParameterTag */; } ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag; function isJSDocTypeLiteral(node) { - return node.kind === 283 /* JSDocTypeLiteral */; + return node.kind === 290 /* JSDocTypeLiteral */; } ts.isJSDocTypeLiteral = isJSDocTypeLiteral; + function isJSDocCallbackTag(node) { + return node.kind === 295 /* JSDocCallbackTag */; + } + ts.isJSDocCallbackTag = isJSDocCallbackTag; + function isJSDocSignature(node) { + return node.kind === 291 /* JSDocSignature */; + } + ts.isJSDocSignature = isJSDocSignature; })(ts || (ts = {})); // Node tests // @@ -12619,7 +12379,7 @@ var ts; (function (ts) { /* @internal */ function isSyntaxList(n) { - return n.kind === 293 /* SyntaxList */; + return n.kind === 303 /* SyntaxList */; } ts.isSyntaxList = isSyntaxList; /* @internal */ @@ -12629,7 +12389,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 145 /* FirstNode */; + return kind >= 146 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -12638,7 +12398,7 @@ var ts; * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail. */ function isToken(n) { - return n.kind >= 0 /* FirstToken */ && n.kind <= 144 /* LastToken */; + return n.kind >= 0 /* FirstToken */ && n.kind <= 145 /* LastToken */; } ts.isToken = isToken; // Node Arrays @@ -12663,6 +12423,10 @@ var ts; return 13 /* FirstTemplateToken */ <= kind && kind <= 16 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; + function isTemplateLiteralToken(node) { + return isTemplateLiteralKind(node.kind); + } + ts.isTemplateLiteralToken = isTemplateLiteralToken; function isTemplateMiddleOrTemplateTail(node) { var kind = node.kind; return kind === 15 /* TemplateMiddle */ @@ -12676,7 +12440,6 @@ var ts; // Identifiers /* @internal */ function isGeneratedIdentifier(node) { - // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; @@ -12700,13 +12463,23 @@ var ts; return false; } ts.isModifierKind = isModifierKind; + /* @internal */ + function isParameterPropertyModifier(kind) { + return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */); + } + ts.isParameterPropertyModifier = isParameterPropertyModifier; + /* @internal */ + function isClassMemberModifier(idToken) { + return isParameterPropertyModifier(idToken) || idToken === 115 /* StaticKeyword */; + } + ts.isClassMemberModifier = isClassMemberModifier; function isModifier(node) { return isModifierKind(node.kind); } ts.isModifier = isModifier; function isEntityName(node) { var kind = node.kind; - return kind === 145 /* QualifiedName */ + return kind === 146 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isEntityName = isEntityName; @@ -12715,14 +12488,14 @@ var ts; return kind === 71 /* Identifier */ || kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ - || kind === 146 /* ComputedPropertyName */; + || kind === 147 /* ComputedPropertyName */; } ts.isPropertyName = isPropertyName; function isBindingName(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 178 /* ObjectBindingPattern */ - || kind === 179 /* ArrayBindingPattern */; + || kind === 182 /* ObjectBindingPattern */ + || kind === 183 /* ArrayBindingPattern */; } ts.isBindingName = isBindingName; // Functions @@ -12737,13 +12510,13 @@ var ts; ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration; function isFunctionLikeDeclarationKind(kind) { switch (kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; default: return false; @@ -12752,13 +12525,14 @@ var ts; /* @internal */ function isFunctionLikeKind(kind) { switch (kind) { - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 162 /* FunctionType */: - case 280 /* JSDocFunctionType */: - case 163 /* ConstructorType */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 163 /* FunctionType */: + case 287 /* JSDocFunctionType */: + case 164 /* ConstructorType */: return true; default: return isFunctionLikeDeclarationKind(kind); @@ -12773,30 +12547,29 @@ var ts; // Classes function isClassElement(node) { var kind = node.kind; - return kind === 154 /* Constructor */ - || kind === 151 /* PropertyDeclaration */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 159 /* IndexSignature */ - || kind === 210 /* SemicolonClassElement */ - || kind === 251 /* MissingDeclaration */; + return kind === 155 /* Constructor */ + || kind === 152 /* PropertyDeclaration */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 160 /* IndexSignature */ + || kind === 215 /* SemicolonClassElement */; } ts.isClassElement = isClassElement; function isClassLike(node) { - return node && (node.kind === 233 /* ClassDeclaration */ || node.kind === 203 /* ClassExpression */); + return node && (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */); } ts.isClassLike = isClassLike; function isAccessor(node) { - return node && (node.kind === 155 /* GetAccessor */ || node.kind === 156 /* SetAccessor */); + return node && (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */); } ts.isAccessor = isAccessor; /* @internal */ function isMethodOrAccessor(node) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; default: return false; @@ -12806,29 +12579,32 @@ var ts; // Type members function isTypeElement(node) { var kind = node.kind; - return kind === 158 /* ConstructSignature */ - || kind === 157 /* CallSignature */ - || kind === 150 /* PropertySignature */ - || kind === 152 /* MethodSignature */ - || kind === 159 /* IndexSignature */ - || kind === 251 /* MissingDeclaration */; + return kind === 159 /* ConstructSignature */ + || kind === 158 /* CallSignature */ + || kind === 151 /* PropertySignature */ + || kind === 153 /* MethodSignature */ + || kind === 160 /* IndexSignature */; } ts.isTypeElement = isTypeElement; + function isClassOrTypeElement(node) { + return isTypeElement(node) || isClassElement(node); + } + ts.isClassOrTypeElement = isClassOrTypeElement; function isObjectLiteralElementLike(node) { var kind = node.kind; - return kind === 268 /* PropertyAssignment */ - || kind === 269 /* ShorthandPropertyAssignment */ - || kind === 270 /* SpreadAssignment */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 251 /* MissingDeclaration */; + return kind === 273 /* PropertyAssignment */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 275 /* SpreadAssignment */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } ts.isObjectLiteralElementLike = isObjectLiteralElementLike; // Type function isTypeNodeKind(kind) { - return (kind >= 160 /* FirstTypeNode */ && kind <= 177 /* LastTypeNode */) + return (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) || kind === 119 /* AnyKeyword */ + || kind === 142 /* UnknownKeyword */ || kind === 134 /* NumberKeyword */ || kind === 135 /* ObjectKeyword */ || kind === 122 /* BooleanKeyword */ @@ -12839,14 +12615,14 @@ var ts; || kind === 140 /* UndefinedKeyword */ || kind === 95 /* NullKeyword */ || kind === 131 /* NeverKeyword */ - || kind === 205 /* ExpressionWithTypeArguments */ - || kind === 275 /* JSDocAllType */ - || kind === 276 /* JSDocUnknownType */ - || kind === 277 /* JSDocNullableType */ - || kind === 278 /* JSDocNonNullableType */ - || kind === 279 /* JSDocOptionalType */ - || kind === 280 /* JSDocFunctionType */ - || kind === 281 /* JSDocVariadicType */; + || kind === 209 /* ExpressionWithTypeArguments */ + || kind === 282 /* JSDocAllType */ + || kind === 283 /* JSDocUnknownType */ + || kind === 284 /* JSDocNullableType */ + || kind === 285 /* JSDocNonNullableType */ + || kind === 286 /* JSDocOptionalType */ + || kind === 287 /* JSDocFunctionType */ + || kind === 288 /* JSDocVariadicType */; } /** * Node test that determines whether a node is a valid type node. @@ -12859,8 +12635,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return true; } return false; @@ -12871,8 +12647,8 @@ var ts; function isBindingPattern(node) { if (node) { var kind = node.kind; - return kind === 179 /* ArrayBindingPattern */ - || kind === 178 /* ObjectBindingPattern */; + return kind === 183 /* ArrayBindingPattern */ + || kind === 182 /* ObjectBindingPattern */; } return false; } @@ -12880,15 +12656,15 @@ var ts; /* @internal */ function isAssignmentPattern(node) { var kind = node.kind; - return kind === 181 /* ArrayLiteralExpression */ - || kind === 182 /* ObjectLiteralExpression */; + return kind === 185 /* ArrayLiteralExpression */ + || kind === 186 /* ObjectLiteralExpression */; } ts.isAssignmentPattern = isAssignmentPattern; /* @internal */ function isArrayBindingElement(node) { var kind = node.kind; - return kind === 180 /* BindingElement */ - || kind === 204 /* OmittedExpression */; + return kind === 184 /* BindingElement */ + || kind === 208 /* OmittedExpression */; } ts.isArrayBindingElement = isArrayBindingElement; /** @@ -12897,9 +12673,9 @@ var ts; /* @internal */ function isDeclarationBindingElement(bindingElement) { switch (bindingElement.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 184 /* BindingElement */: return true; } return false; @@ -12920,8 +12696,8 @@ var ts; /* @internal */ function isObjectBindingOrAssignmentPattern(node) { switch (node.kind) { - case 178 /* ObjectBindingPattern */: - case 182 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return true; } return false; @@ -12933,28 +12709,36 @@ var ts; /* @internal */ function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return true; } return false; } ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern; + /* @internal */ + function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { + var kind = node.kind; + return kind === 187 /* PropertyAccessExpression */ + || kind === 146 /* QualifiedName */ + || kind === 181 /* ImportType */; + } + ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode; // Expression function isPropertyAccessOrQualifiedName(node) { var kind = node.kind; - return kind === 183 /* PropertyAccessExpression */ - || kind === 145 /* QualifiedName */; + return kind === 187 /* PropertyAccessExpression */ + || kind === 146 /* QualifiedName */; } ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName; function isCallLikeExpression(node) { switch (node.kind) { - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 187 /* TaggedTemplateExpression */: - case 149 /* Decorator */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 191 /* TaggedTemplateExpression */: + case 150 /* Decorator */: return true; default: return false; @@ -12962,12 +12746,12 @@ var ts; } ts.isCallLikeExpression = isCallLikeExpression; function isCallOrNewExpression(node) { - return node.kind === 185 /* CallExpression */ || node.kind === 186 /* NewExpression */; + return node.kind === 189 /* CallExpression */ || node.kind === 190 /* NewExpression */; } ts.isCallOrNewExpression = isCallOrNewExpression; function isTemplateLiteral(node) { var kind = node.kind; - return kind === 200 /* TemplateExpression */ + return kind === 204 /* TemplateExpression */ || kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isTemplateLiteral = isTemplateLiteral; @@ -12978,32 +12762,32 @@ var ts; ts.isLeftHandSideExpression = isLeftHandSideExpression; function isLeftHandSideExpressionKind(kind) { switch (kind) { - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - case 186 /* NewExpression */: - case 185 /* CallExpression */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 257 /* JsxFragment */: - case 187 /* TaggedTemplateExpression */: - case 181 /* ArrayLiteralExpression */: - case 189 /* ParenthesizedExpression */: - case 182 /* ObjectLiteralExpression */: - case 203 /* ClassExpression */: - case 190 /* FunctionExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + case 190 /* NewExpression */: + case 189 /* CallExpression */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 262 /* JsxFragment */: + case 191 /* TaggedTemplateExpression */: + case 185 /* ArrayLiteralExpression */: + case 193 /* ParenthesizedExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: case 71 /* Identifier */: case 12 /* RegularExpressionLiteral */: case 8 /* NumericLiteral */: case 9 /* StringLiteral */: case 13 /* NoSubstitutionTemplateLiteral */: - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 99 /* ThisKeyword */: case 101 /* TrueKeyword */: case 97 /* SuperKeyword */: - case 207 /* NonNullExpression */: - case 208 /* MetaProperty */: + case 211 /* NonNullExpression */: + case 212 /* MetaProperty */: case 91 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression return true; default: @@ -13017,13 +12801,13 @@ var ts; ts.isUnaryExpression = isUnaryExpression; function isUnaryExpressionKind(kind) { switch (kind) { - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 195 /* AwaitExpression */: - case 188 /* TypeAssertionExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 192 /* TypeAssertionExpression */: return true; default: return isLeftHandSideExpressionKind(kind); @@ -13032,9 +12816,9 @@ var ts; /* @internal */ function isUnaryExpressionWithWrite(expr) { switch (expr.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return true; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; default: @@ -13053,15 +12837,15 @@ var ts; ts.isExpression = isExpression; function isExpressionKind(kind) { switch (kind) { - case 199 /* ConditionalExpression */: - case 201 /* YieldExpression */: - case 191 /* ArrowFunction */: - case 198 /* BinaryExpression */: - case 202 /* SpreadElement */: - case 206 /* AsExpression */: - case 204 /* OmittedExpression */: - case 296 /* CommaListExpression */: - case 295 /* PartiallyEmittedExpression */: + case 203 /* ConditionalExpression */: + case 205 /* YieldExpression */: + case 195 /* ArrowFunction */: + case 202 /* BinaryExpression */: + case 206 /* SpreadElement */: + case 210 /* AsExpression */: + case 208 /* OmittedExpression */: + case 306 /* CommaListExpression */: + case 305 /* PartiallyEmittedExpression */: return true; default: return isUnaryExpressionKind(kind); @@ -13069,18 +12853,18 @@ var ts; } function isAssertionExpression(node) { var kind = node.kind; - return kind === 188 /* TypeAssertionExpression */ - || kind === 206 /* AsExpression */; + return kind === 192 /* TypeAssertionExpression */ + || kind === 210 /* AsExpression */; } ts.isAssertionExpression = isAssertionExpression; /* @internal */ function isPartiallyEmittedExpression(node) { - return node.kind === 295 /* PartiallyEmittedExpression */; + return node.kind === 305 /* PartiallyEmittedExpression */; } ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression; /* @internal */ function isNotEmittedStatement(node) { - return node.kind === 294 /* NotEmittedStatement */; + return node.kind === 304 /* NotEmittedStatement */; } ts.isNotEmittedStatement = isNotEmittedStatement; /* @internal */ @@ -13091,13 +12875,13 @@ var ts; ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode; function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return true; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -13105,7 +12889,7 @@ var ts; ts.isIterationStatement = isIterationStatement; /* @internal */ function isForInOrOfStatement(node) { - return node.kind === 219 /* ForInStatement */ || node.kind === 220 /* ForOfStatement */; + return node.kind === 224 /* ForInStatement */ || node.kind === 225 /* ForOfStatement */; } ts.isForInOrOfStatement = isForInOrOfStatement; // Element @@ -13129,111 +12913,113 @@ var ts; /* @internal */ function isModuleBody(node) { var kind = node.kind; - return kind === 238 /* ModuleBlock */ - || kind === 237 /* ModuleDeclaration */ + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */ || kind === 71 /* Identifier */; } ts.isModuleBody = isModuleBody; /* @internal */ function isNamespaceBody(node) { var kind = node.kind; - return kind === 238 /* ModuleBlock */ - || kind === 237 /* ModuleDeclaration */; + return kind === 243 /* ModuleBlock */ + || kind === 242 /* ModuleDeclaration */; } ts.isNamespaceBody = isNamespaceBody; /* @internal */ function isJSDocNamespaceBody(node) { var kind = node.kind; return kind === 71 /* Identifier */ - || kind === 237 /* ModuleDeclaration */; + || kind === 242 /* ModuleDeclaration */; } ts.isJSDocNamespaceBody = isJSDocNamespaceBody; /* @internal */ function isNamedImportBindings(node) { var kind = node.kind; - return kind === 245 /* NamedImports */ - || kind === 244 /* NamespaceImport */; + return kind === 250 /* NamedImports */ + || kind === 249 /* NamespaceImport */; } ts.isNamedImportBindings = isNamedImportBindings; /* @internal */ function isModuleOrEnumDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ || node.kind === 236 /* EnumDeclaration */; + return node.kind === 242 /* ModuleDeclaration */ || node.kind === 241 /* EnumDeclaration */; } ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration; function isDeclarationKind(kind) { - return kind === 191 /* ArrowFunction */ - || kind === 180 /* BindingElement */ - || kind === 233 /* ClassDeclaration */ - || kind === 203 /* ClassExpression */ - || kind === 154 /* Constructor */ - || kind === 236 /* EnumDeclaration */ - || kind === 271 /* EnumMember */ - || kind === 250 /* ExportSpecifier */ - || kind === 232 /* FunctionDeclaration */ - || kind === 190 /* FunctionExpression */ - || kind === 155 /* GetAccessor */ - || kind === 243 /* ImportClause */ - || kind === 241 /* ImportEqualsDeclaration */ - || kind === 246 /* ImportSpecifier */ - || kind === 234 /* InterfaceDeclaration */ - || kind === 260 /* JsxAttribute */ - || kind === 153 /* MethodDeclaration */ - || kind === 152 /* MethodSignature */ - || kind === 237 /* ModuleDeclaration */ - || kind === 240 /* NamespaceExportDeclaration */ - || kind === 244 /* NamespaceImport */ - || kind === 148 /* Parameter */ - || kind === 268 /* PropertyAssignment */ - || kind === 151 /* PropertyDeclaration */ - || kind === 150 /* PropertySignature */ - || kind === 156 /* SetAccessor */ - || kind === 269 /* ShorthandPropertyAssignment */ - || kind === 235 /* TypeAliasDeclaration */ - || kind === 147 /* TypeParameter */ - || kind === 230 /* VariableDeclaration */ - || kind === 291 /* JSDocTypedefTag */; + return kind === 195 /* ArrowFunction */ + || kind === 184 /* BindingElement */ + || kind === 238 /* ClassDeclaration */ + || kind === 207 /* ClassExpression */ + || kind === 155 /* Constructor */ + || kind === 241 /* EnumDeclaration */ + || kind === 276 /* EnumMember */ + || kind === 255 /* ExportSpecifier */ + || kind === 237 /* FunctionDeclaration */ + || kind === 194 /* FunctionExpression */ + || kind === 156 /* GetAccessor */ + || kind === 248 /* ImportClause */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 251 /* ImportSpecifier */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 265 /* JsxAttribute */ + || kind === 154 /* MethodDeclaration */ + || kind === 153 /* MethodSignature */ + || kind === 242 /* ModuleDeclaration */ + || kind === 245 /* NamespaceExportDeclaration */ + || kind === 249 /* NamespaceImport */ + || kind === 149 /* Parameter */ + || kind === 273 /* PropertyAssignment */ + || kind === 152 /* PropertyDeclaration */ + || kind === 151 /* PropertySignature */ + || kind === 157 /* SetAccessor */ + || kind === 274 /* ShorthandPropertyAssignment */ + || kind === 240 /* TypeAliasDeclaration */ + || kind === 148 /* TypeParameter */ + || kind === 235 /* VariableDeclaration */ + || kind === 301 /* JSDocTypedefTag */ + || kind === 295 /* JSDocCallbackTag */ + || kind === 302 /* JSDocPropertyTag */; } function isDeclarationStatementKind(kind) { - return kind === 232 /* FunctionDeclaration */ - || kind === 251 /* MissingDeclaration */ - || kind === 233 /* ClassDeclaration */ - || kind === 234 /* InterfaceDeclaration */ - || kind === 235 /* TypeAliasDeclaration */ - || kind === 236 /* EnumDeclaration */ - || kind === 237 /* ModuleDeclaration */ - || kind === 242 /* ImportDeclaration */ - || kind === 241 /* ImportEqualsDeclaration */ - || kind === 248 /* ExportDeclaration */ - || kind === 247 /* ExportAssignment */ - || kind === 240 /* NamespaceExportDeclaration */; + return kind === 237 /* FunctionDeclaration */ + || kind === 256 /* MissingDeclaration */ + || kind === 238 /* ClassDeclaration */ + || kind === 239 /* InterfaceDeclaration */ + || kind === 240 /* TypeAliasDeclaration */ + || kind === 241 /* EnumDeclaration */ + || kind === 242 /* ModuleDeclaration */ + || kind === 247 /* ImportDeclaration */ + || kind === 246 /* ImportEqualsDeclaration */ + || kind === 253 /* ExportDeclaration */ + || kind === 252 /* ExportAssignment */ + || kind === 245 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 222 /* BreakStatement */ - || kind === 221 /* ContinueStatement */ - || kind === 229 /* DebuggerStatement */ - || kind === 216 /* DoStatement */ - || kind === 214 /* ExpressionStatement */ - || kind === 213 /* EmptyStatement */ - || kind === 219 /* ForInStatement */ - || kind === 220 /* ForOfStatement */ - || kind === 218 /* ForStatement */ - || kind === 215 /* IfStatement */ - || kind === 226 /* LabeledStatement */ - || kind === 223 /* ReturnStatement */ - || kind === 225 /* SwitchStatement */ - || kind === 227 /* ThrowStatement */ - || kind === 228 /* TryStatement */ - || kind === 212 /* VariableStatement */ - || kind === 217 /* WhileStatement */ - || kind === 224 /* WithStatement */ - || kind === 294 /* NotEmittedStatement */ - || kind === 298 /* EndOfDeclarationMarker */ - || kind === 297 /* MergeDeclarationMarker */; + return kind === 227 /* BreakStatement */ + || kind === 226 /* ContinueStatement */ + || kind === 234 /* DebuggerStatement */ + || kind === 221 /* DoStatement */ + || kind === 219 /* ExpressionStatement */ + || kind === 218 /* EmptyStatement */ + || kind === 224 /* ForInStatement */ + || kind === 225 /* ForOfStatement */ + || kind === 223 /* ForStatement */ + || kind === 220 /* IfStatement */ + || kind === 231 /* LabeledStatement */ + || kind === 228 /* ReturnStatement */ + || kind === 230 /* SwitchStatement */ + || kind === 232 /* ThrowStatement */ + || kind === 233 /* TryStatement */ + || kind === 217 /* VariableStatement */ + || kind === 222 /* WhileStatement */ + || kind === 229 /* WithStatement */ + || kind === 304 /* NotEmittedStatement */ + || kind === 308 /* EndOfDeclarationMarker */ + || kind === 307 /* MergeDeclarationMarker */; } /* @internal */ function isDeclaration(node) { - if (node.kind === 147 /* TypeParameter */) { - return node.parent.kind !== 290 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); + if (node.kind === 148 /* TypeParameter */) { + return node.parent.kind !== 300 /* JSDocTemplateTag */ || ts.isInJavaScriptFile(node); } return isDeclarationKind(node.kind); } @@ -13260,10 +13046,10 @@ var ts; } ts.isStatement = isStatement; function isBlockStatement(node) { - if (node.kind !== 211 /* Block */) + if (node.kind !== 216 /* Block */) return false; if (node.parent !== undefined) { - if (node.parent.kind === 228 /* TryStatement */ || node.parent.kind === 267 /* CatchClause */) { + if (node.parent.kind === 233 /* TryStatement */ || node.parent.kind === 272 /* CatchClause */) { return false; } } @@ -13273,8 +13059,8 @@ var ts; /* @internal */ function isModuleReference(node) { var kind = node.kind; - return kind === 252 /* ExternalModuleReference */ - || kind === 145 /* QualifiedName */ + return kind === 257 /* ExternalModuleReference */ + || kind === 146 /* QualifiedName */ || kind === 71 /* Identifier */; } ts.isModuleReference = isModuleReference; @@ -13284,76 +13070,78 @@ var ts; var kind = node.kind; return kind === 99 /* ThisKeyword */ || kind === 71 /* Identifier */ - || kind === 183 /* PropertyAccessExpression */; + || kind === 187 /* PropertyAccessExpression */; } ts.isJsxTagNameExpression = isJsxTagNameExpression; /* @internal */ function isJsxChild(node) { var kind = node.kind; - return kind === 253 /* JsxElement */ - || kind === 263 /* JsxExpression */ - || kind === 254 /* JsxSelfClosingElement */ + return kind === 258 /* JsxElement */ + || kind === 268 /* JsxExpression */ + || kind === 259 /* JsxSelfClosingElement */ || kind === 10 /* JsxText */ - || kind === 257 /* JsxFragment */; + || kind === 262 /* JsxFragment */; } ts.isJsxChild = isJsxChild; /* @internal */ function isJsxAttributeLike(node) { var kind = node.kind; - return kind === 260 /* JsxAttribute */ - || kind === 262 /* JsxSpreadAttribute */; + return kind === 265 /* JsxAttribute */ + || kind === 267 /* JsxSpreadAttribute */; } ts.isJsxAttributeLike = isJsxAttributeLike; /* @internal */ function isStringLiteralOrJsxExpression(node) { var kind = node.kind; return kind === 9 /* StringLiteral */ - || kind === 263 /* JsxExpression */; + || kind === 268 /* JsxExpression */; } ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression; function isJsxOpeningLikeElement(node) { var kind = node.kind; - return kind === 255 /* JsxOpeningElement */ - || kind === 254 /* JsxSelfClosingElement */; + return kind === 260 /* JsxOpeningElement */ + || kind === 259 /* JsxSelfClosingElement */; } ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement; // Clauses function isCaseOrDefaultClause(node) { var kind = node.kind; - return kind === 264 /* CaseClause */ - || kind === 265 /* DefaultClause */; + return kind === 269 /* CaseClause */ + || kind === 270 /* DefaultClause */; } ts.isCaseOrDefaultClause = isCaseOrDefaultClause; // JSDoc /** True if node is of some JSDoc syntax kind. */ /* @internal */ function isJSDocNode(node) { - return node.kind >= 274 /* FirstJSDocNode */ && node.kind <= 292 /* LastJSDocNode */; + return node.kind >= 281 /* FirstJSDocNode */ && node.kind <= 302 /* LastJSDocNode */; } ts.isJSDocNode = isJSDocNode; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node) { - return node.kind === 282 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node); + return node.kind === 289 /* JSDocComment */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node); } ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode; // TODO: determine what this does before making it public. /* @internal */ function isJSDocTag(node) { - return node.kind >= 284 /* FirstJSDocTagNode */ && node.kind <= 292 /* LastJSDocTagNode */; + return node.kind >= 292 /* FirstJSDocTagNode */ && node.kind <= 302 /* LastJSDocTagNode */; } ts.isJSDocTag = isJSDocTag; function isSetAccessor(node) { - return node.kind === 156 /* SetAccessor */; + return node.kind === 157 /* SetAccessor */; } ts.isSetAccessor = isSetAccessor; function isGetAccessor(node) { - return node.kind === 155 /* GetAccessor */; + return node.kind === 156 /* GetAccessor */; } ts.isGetAccessor = isGetAccessor; /** True if has jsdoc nodes attached to it. */ /* @internal */ + // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times function hasJSDocNodes(node) { - return !!node.jsDoc && node.jsDoc.length > 0; + var jsDoc = node.jsDoc; + return !!jsDoc && jsDoc.length > 0; } ts.hasJSDocNodes = hasJSDocNodes; /** True if has type node attached to it. */ @@ -13376,13 +13164,13 @@ var ts; ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; function isObjectLiteralElement(node) { switch (node.kind) { - case 260 /* JsxAttribute */: - case 262 /* JsxSpreadAttribute */: - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; default: return false; @@ -13391,16 +13179,1318 @@ var ts; ts.isObjectLiteralElement = isObjectLiteralElement; /* @internal */ function isTypeReferenceType(node) { - return node.kind === 161 /* TypeReference */ || node.kind === 205 /* ExpressionWithTypeArguments */; + return node.kind === 162 /* TypeReference */ || node.kind === 209 /* ExpressionWithTypeArguments */; } ts.isTypeReferenceType = isTypeReferenceType; + var MAX_SMI_X86 = 1073741823; + /* @internal */ + function guessIndentation(lines) { + var indentation = MAX_SMI_X86; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + if (!line.length) { + continue; + } + var i = 0; + for (; i < line.length && i < indentation; i++) { + if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + ts.guessIndentation = guessIndentation; function isStringLiteralLike(node) { return node.kind === 9 /* StringLiteral */ || node.kind === 13 /* NoSubstitutionTemplateLiteral */; } ts.isStringLiteralLike = isStringLiteralLike; })(ts || (ts = {})); -/// -/// +/* @internal */ +(function (ts) { + /** @internal */ + function isNamedImportsOrExports(node) { + return node.kind === 250 /* NamedImports */ || node.kind === 254 /* NamedExports */; + } + ts.isNamedImportsOrExports = isNamedImportsOrExports; + function Symbol(flags, name) { + this.flags = flags; + this.escapedName = name; + this.declarations = undefined; + this.valueDeclaration = undefined; + this.id = undefined; + this.mergeId = undefined; + this.parent = undefined; + } + function Type(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } + function Signature() { } // tslint:disable-line no-empty + function Node(kind, pos, end) { + this.pos = pos; + this.end = end; + this.kind = kind; + this.id = 0; + this.flags = 0 /* None */; + this.modifierFlagsCache = 0 /* None */; + this.transformFlags = 0 /* None */; + this.parent = undefined; + this.original = undefined; + } + function SourceMapSource(fileName, text, skipTrivia) { + this.fileName = fileName; + this.text = text; + this.skipTrivia = skipTrivia || (function (pos) { return pos; }); + } + ts.objectAllocator = { + getNodeConstructor: function () { return Node; }, + getTokenConstructor: function () { return Node; }, + getIdentifierConstructor: function () { return Node; }, + getSourceFileConstructor: function () { return Node; }, + getSymbolConstructor: function () { return Symbol; }, + getTypeConstructor: function () { return Type; }, + getSignatureConstructor: function () { return Signature; }, + getSourceMapSourceConstructor: function () { return SourceMapSource; }, + }; + /* @internal */ + function formatStringFromArgs(text, args, baseIndex) { + if (baseIndex === void 0) { baseIndex = 0; } + return text.replace(/{(\d+)}/g, function (_match, index) { return ts.Debug.assertDefined(args[+index + baseIndex]); }); + } + ts.formatStringFromArgs = formatStringFromArgs; + function getLocaleSpecificMessage(message) { + return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + } + ts.getLocaleSpecificMessage = getLocaleSpecificMessage; + function createFileDiagnostic(file, start, length, message) { + ts.Debug.assertGreaterThanOrEqual(start, 0); + ts.Debug.assertGreaterThanOrEqual(length, 0); + if (file) { + ts.Debug.assertLessThanOrEqual(start, file.text.length); + ts.Debug.assertLessThanOrEqual(start + length, file.text.length); + } + var text = getLocaleSpecificMessage(message); + if (arguments.length > 4) { + text = formatStringFromArgs(text, arguments, 4); + } + return { + file: file, + start: start, + length: length, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createFileDiagnostic = createFileDiagnostic; + /* @internal */ + function formatMessage(_dummy, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return text; + } + ts.formatMessage = formatMessage; + function createCompilerDiagnostic(message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 1) { + text = formatStringFromArgs(text, arguments, 1); + } + return { + file: undefined, + start: undefined, + length: undefined, + messageText: text, + category: message.category, + code: message.code, + reportsUnnecessary: message.reportsUnnecessary, + }; + } + ts.createCompilerDiagnostic = createCompilerDiagnostic; + /* @internal */ + function createCompilerDiagnosticFromMessageChain(chain) { + return { + file: undefined, + start: undefined, + length: undefined, + code: chain.code, + category: chain.category, + messageText: chain.next ? chain : chain.messageText, + }; + } + ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain; + function chainDiagnosticMessages(details, message) { + var text = getLocaleSpecificMessage(message); + if (arguments.length > 2) { + text = formatStringFromArgs(text, arguments, 2); + } + return { + messageText: text, + category: message.category, + code: message.code, + next: details + }; + } + ts.chainDiagnosticMessages = chainDiagnosticMessages; + function concatenateDiagnosticMessageChains(headChain, tailChain) { + var lastChain = headChain; + while (lastChain.next) { + lastChain = lastChain.next; + } + lastChain.next = tailChain; + return headChain; + } + ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains; + function getDiagnosticFilePath(diagnostic) { + return diagnostic.file ? diagnostic.file.path : undefined; + } + /* @internal */ + function compareDiagnostics(d1, d2) { + return compareDiagnosticsSkipRelatedInformation(d1, d2) || + compareRelatedInformation(d1, d2) || + 0 /* EqualTo */; + } + ts.compareDiagnostics = compareDiagnostics; + /* @internal */ + function compareDiagnosticsSkipRelatedInformation(d1, d2) { + return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || + ts.compareValues(d1.start, d2.start) || + ts.compareValues(d1.length, d2.length) || + ts.compareValues(d1.code, d2.code) || + compareMessageText(d1.messageText, d2.messageText) || + 0 /* EqualTo */; + } + ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation; + function compareRelatedInformation(d1, d2) { + if (!d1.relatedInformation && !d2.relatedInformation) { + return 0 /* EqualTo */; + } + if (d1.relatedInformation && d2.relatedInformation) { + return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) { + var d2i = d2.relatedInformation[index]; + return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared + }) || 0 /* EqualTo */; + } + return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; + } + function compareMessageText(t1, t2) { + var text1 = t1; + var text2 = t2; + while (text1 && text2) { + // We still have both chains. + var string1 = ts.isString(text1) ? text1 : text1.messageText; + var string2 = ts.isString(text2) ? text2 : text2.messageText; + var res = ts.compareStringsCaseSensitive(string1, string2); + if (res) { + return res; + } + text1 = ts.isString(text1) ? undefined : text1.next; + text2 = ts.isString(text2) ? undefined : text2.next; + } + if (!text1 && !text2) { + // if the chains are done, then these messages are the same. + return 0 /* EqualTo */; + } + // We still have one chain remaining. The shorter chain should come first. + return text1 ? 1 /* GreaterThan */ : -1 /* LessThan */; + } + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function getEmitModuleResolutionKind(compilerOptions) { + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + } + return moduleResolution; + } + ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind; + function unreachableCodeIsError(options) { + return options.allowUnreachableCode === false; + } + ts.unreachableCodeIsError = unreachableCodeIsError; + function unusedLabelIsError(options) { + return options.allowUnusedLabels === false; + } + ts.unusedLabelIsError = unusedLabelIsError; + function getAreDeclarationMapsEnabled(options) { + return !!(getEmitDeclarations(options) && options.declarationMap); + } + ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled; + function getAllowSyntheticDefaultImports(compilerOptions) { + var moduleKind = getEmitModuleKind(compilerOptions); + return compilerOptions.allowSyntheticDefaultImports !== undefined + ? compilerOptions.allowSyntheticDefaultImports + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; + } + ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; + function getEmitDeclarations(compilerOptions) { + return !!(compilerOptions.declaration || compilerOptions.composite); + } + ts.getEmitDeclarations = getEmitDeclarations; + function getStrictOptionValue(compilerOptions, flag) { + return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; + } + ts.getStrictOptionValue = getStrictOptionValue; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + /** + * Normalize path separators. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + // TODO(rbuckton): replace references with `resolvePath` + function normalizePath(path) { + return ts.resolvePath(path); + } + ts.normalizePath = normalizePath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = ts.removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /* @internal */ + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return [root].concat(rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = ts.combinePaths(currentDirectory, path); + var rootLength = getRootLength(path); + return pathComponents(path, rootLength); + } + ts.getPathComponents = getPathComponents; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); + if (pathComponents.length === 1) + return root; + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); + var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return [""].concat(relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return ts.getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + */ + function ensurePathIsNonModuleName(path) { + return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function getBaseFileName(path, extensions, ignoreCase) { + path = ts.normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = ts.getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + /** + * Combines paths. If a path is absolute, it replaces any previous path. + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = ts.normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = ts.normalizeSlashes(relativePath); + if (!path || ts.getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + var combined = ts.some(paths) ? combinePaths.apply(void 0, [path].concat(paths)) : ts.normalizeSlashes(path); + var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); + return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.resolvePath = resolvePath; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + if (path.length === 0) + return false; + var ch = path.charCodeAt(path.length - 1); + return ch === 47 /* slash */ || ch === 92 /* backslash */; + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); + var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 0; i < sharedLength; i++) { + var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; + var result = stringComparer(aComponents[i], bComponents[i]); + if (result !== 0 /* EqualTo */) { + return result; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); + var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function isDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + function stripLeadingDirectorySeparator(s) { + return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + } + function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { + var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); + return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); + } + ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix; + // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character. + // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future + // proof. + var reservedCharacterPattern = /[^\w\s\/]/g; + var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + 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 separators) + * (\\.(?!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) { + return undefined; + } + var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|"); + // If excluding, match "foo/bar/baz...", but if including, only allow "foo". + var terminator = usage === "exclude" ? "($|/)" : "$"; + return "^(" + pattern + ")" + terminator; + } + ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard; + function getRegularExpressionsForWildcards(specs, basePath, usage) { + if (specs === undefined || specs.length === 0) { + return undefined; + } + return ts.flatMap(specs, function (spec) { + return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); + }); + } + /** + * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, + * and does not contain any glob characters itself. + */ + function isImplicitGlob(lastPathComponent) { + return !/[.*?]/.test(lastPathComponent); + } + ts.isImplicitGlob = isImplicitGlob; + function getSubPatternFromSpec(spec, basePath, usage, _a) { + var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter; + var subpattern = ""; + var hasWrittenComponent = false; + var components = ts.getNormalizedPathComponents(spec, basePath); + var lastComponent = ts.last(components); + if (usage !== "exclude" && lastComponent === "**") { + return undefined; + } + // getNormalizedPathComponents includes the separator for the root component. + // We need to remove to create our regex correctly. + components[0] = removeTrailingDirectorySeparator(components[0]); + if (isImplicitGlob(lastComponent)) { + components.push("**", "*"); + } + var optionalCount = 0; + for (var _i = 0, components_1 = components; _i < components_1.length; _i++) { + var component = components_1[_i]; + if (component === "**") { + subpattern += doubleAsteriskRegexFragment; + } + else { + if (usage === "directories") { + subpattern += "("; + optionalCount++; + } + if (hasWrittenComponent) { + 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 */) { + componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?"; + component = component.substr(1); + } + else if (component.charCodeAt(0) === 63 /* question */) { + 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); + } + } + hasWrittenComponent = true; + } + while (optionalCount > 0) { + subpattern += ")?"; + optionalCount--; + } + return subpattern; + } + function replaceWildcardCharacter(match, singleAsteriskRegexFragment) { + return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; + } + /** @param path directory of the tsconfig.json */ + function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var absolutePath = combinePaths(currentDirectory, path); + return { + includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), + includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), + includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"), + excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"), + basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) + }; + } + ts.getFileMatcherPatterns = getFileMatcherPatterns; + function getRegexFromPattern(pattern, useCaseSensitiveFileNames) { + return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); + } + ts.getRegexFromPattern = getRegexFromPattern; + /** @param path directory of the tsconfig.json */ + function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries) { + path = ts.normalizePath(path); + currentDirectory = ts.normalizePath(currentDirectory); + var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory); + var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); }); + var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames); + var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames); + // Associate an array of results with each include regex. This keeps results in order of the "include" order. + // If there are no "includes", then just put everything in results[0]. + var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]]; + for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { + var basePath = _a[_i]; + visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + } + return ts.flatten(results); + function visitDirectory(path, absolutePath, depth) { + var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; + var _loop_1 = function (current) { + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) + return "continue"; + if (excludeRegex && excludeRegex.test(absoluteName)) + return "continue"; + if (!includeFileRegexes) { + results[0].push(name); + } + else { + var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); }); + if (includeIndex !== -1) { + results[includeIndex].push(name); + } + } + }; + for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) { + var current = _b[_i]; + _loop_1(current); + } + if (depth !== undefined) { + depth--; + if (depth === 0) { + return; + } + } + for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { + var current = _d[_c]; + var name = combinePaths(path, current); + var absoluteName = combinePaths(absolutePath, current); + if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && + (!excludeRegex || !excludeRegex.test(absoluteName))) { + visitDirectory(name, absoluteName, depth); + } + } + } + } + ts.matchFiles = matchFiles; + /** + * Computes the unique non-wildcard base paths amongst the provided include patterns. + */ + function getBasePaths(path, includes, useCaseSensitiveFileNames) { + // Storage for our results in the form of literal paths (e.g. the paths as written by the user). + var basePaths = [path]; + if (includes) { + // Storage for literal base paths amongst the include patterns. + var includeBasePaths = []; + for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { + var include = includes_1[_i]; + // We also need to check the relative paths by converting them to absolute and normalizing + // in case they escape the base path (e.g "..\somedirectory") + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + // Append the literal and canonical candidate base paths. + includeBasePaths.push(getIncludeBasePath(absolute)); + } + // Sort the offsets array using either the literal or canonical path representations. + includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); + var _loop_2 = function (includeBasePath) { + if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + basePaths.push(includeBasePath); + } + }; + // Iterate over each include base path and include unique base paths that are not a + // subpath of an existing base path + for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) { + var includeBasePath = includeBasePaths_1[_a]; + _loop_2(includeBasePath); + } + } + return basePaths; + } + function getIncludeBasePath(absolute) { + var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); + if (wildcardOffset < 0) { + // No "*" or "?" in the path + return !hasExtension(absolute) + ? absolute + : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + } + return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); + } + function ensureScriptKind(fileName, scriptKind) { + // Using scriptKind as a condition handles both: + // - 'scriptKind' is unspecified and thus it is `undefined` + // - 'scriptKind' is set and it is `Unknown` (0) + // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt + // to get the ScriptKind from the file name. If it cannot be resolved + // from the file name then the default 'TS' script kind is returned. + return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */; + } + ts.ensureScriptKind = ensureScriptKind; + function getScriptKindFromFileName(fileName) { + var ext = fileName.substr(fileName.lastIndexOf(".")); + switch (ext.toLowerCase()) { + case ".js" /* Js */: + return 1 /* JS */; + case ".jsx" /* Jsx */: + return 2 /* JSX */; + case ".ts" /* Ts */: + return 3 /* TS */; + case ".tsx" /* Tsx */: + return 4 /* TSX */; + case ".json" /* Json */: + return 6 /* JSON */; + default: + return 0 /* Unknown */; + } + } + ts.getScriptKindFromFileName = getScriptKindFromFileName; + /** + * List of supported extensions in order of file resolution precedence. + */ + ts.supportedTypeScriptExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */]; + /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ + ts.supportedTypescriptExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; + ts.supportedJavascriptExtensions = [".js" /* Js */, ".jsx" /* Jsx */]; + var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); + function getSupportedExtensions(options, extraFileExtensions) { + var needJsExtensions = options && options.allowJs; + if (!extraFileExtensions || extraFileExtensions.length === 0) { + return needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; + } + var extensions = (needJsExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).concat(ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined; })); + return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + } + ts.getSupportedExtensions = getSupportedExtensions; + function isJavaScriptLike(scriptKind) { + return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */; + } + function hasJavaScriptFileExtension(fileName) { + return ts.some(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return ts.some(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; + function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { + if (!fileName) { + return false; + } + for (var _i = 0, _a = getSupportedExtensions(compilerOptions, extraFileExtensions); _i < _a.length; _i++) { + var extension = _a[_i]; + if (ts.fileExtensionIs(fileName, extension)) { + return true; + } + } + return false; + } + ts.isSupportedSourceFileName = isSupportedSourceFileName; + /** + * Extension boundaries by priority. Lower numbers indicate higher priorities, and are + * aligned to the offset of the highest priority extension in the + * allSupportedExtensions array. + */ + 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 (ts.fileExtensionIs(path, supportedExtensions[i])) { + return adjustExtensionPriority(i, supportedExtensions); + } + } + // If its not in the list of supported extensions, this is likely a + // TypeScript file with a non-ts extension + return 0 /* Highest */; + } + ts.getExtensionPriority = getExtensionPriority; + /** + * Adjusts an extension priority to be the highest priority within the same range. + */ + function adjustExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 0 /* TypeScriptFiles */; + } + else if (extensionPriority < supportedExtensions.length) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.adjustExtensionPriority = adjustExtensionPriority; + /** + * Gets the next lowest extension priority for a given priority. + */ + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { + if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { + return 2 /* DeclarationAndJavaScriptFiles */; + } + else { + return supportedExtensions.length; + } + } + ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; + var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */]; + function removeFileExtension(path) { + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; + var extensionless = tryRemoveExtension(path, ext); + if (extensionless !== undefined) { + return extensionless; + } + } + return path; + } + ts.removeFileExtension = removeFileExtension; + function tryRemoveExtension(path, extension) { + return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; + } + ts.tryRemoveExtension = tryRemoveExtension; + function removeExtension(path, extension) { + return path.substring(0, path.length - extension.length); + } + ts.removeExtension = removeExtension; + function changeExtension(path, newExtension) { + return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + } + ts.changeExtension = changeExtension; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var Debug; + (function (Debug) { + function showSymbol(symbol) { + var symbolFlags = ts.SymbolFlags; + return "{ flags: " + (symbolFlags ? showFlags(symbol.flags, symbolFlags) : symbol.flags) + "; declarations: " + ts.map(symbol.declarations, showSyntaxKind) + " }"; + } + Debug.showSymbol = showSymbol; + function showFlags(flags, flagsEnum) { + var out = []; + for (var pow = 0; pow <= 30; pow++) { + var n = 1 << pow; + if (flags & n) { + out.push(flagsEnum[n]); + } + } + return out.join("|"); + } + function showSyntaxKind(node) { + var syntaxKind = ts.SyntaxKind; + return syntaxKind ? syntaxKind[node.kind] : node.kind.toString(); + } + Debug.showSyntaxKind = showSyntaxKind; + })(Debug = ts.Debug || (ts.Debug = {})); + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; + /** True if an extension is one of the supported TypeScript extensions. */ + function extensionIsTypeScript(ext) { + return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */; + } + ts.extensionIsTypeScript = extensionIsTypeScript; + function resolutionExtensionIsTypeScriptOrJson(ext) { + return extensionIsTypeScript(ext) || ext === ".json" /* Json */; + } + ts.resolutionExtensionIsTypeScriptOrJson = resolutionExtensionIsTypeScriptOrJson; + /** + * Gets the extension from a path. + * Path must have a valid extension. + */ + function extensionFromPath(path) { + var ext = tryGetExtensionFromPath(path); + return ext !== undefined ? ext : Debug.fail("File " + path + " has unknown extension."); + } + ts.extensionFromPath = extensionFromPath; + function isAnySupportedFileExtension(path) { + return tryGetExtensionFromPath(path) !== undefined; + } + ts.isAnySupportedFileExtension = isAnySupportedFileExtension; + function tryGetExtensionFromPath(path) { + return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); + } + ts.tryGetExtensionFromPath = tryGetExtensionFromPath; + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") + extensions = [extensions]; + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function isCheckJsEnabledForFile(sourceFile, compilerOptions) { + return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; + } + ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function sliceAfter(arr, value) { + var index = arr.indexOf(value); + Debug.assert(index !== -1); + return arr.slice(index); + } + ts.sliceAfter = sliceAfter; + function minAndMax(arr, getValue) { + Debug.assert(arr.length !== 0); + var min = getValue(arr[0]); + var max = min; + for (var i = 1; i < arr.length; i++) { + var value = getValue(arr[i]); + if (value < min) { + min = value; + } + else if (value > max) { + max = value; + } + } + return { min: min, max: max }; + } + ts.minAndMax = minAndMax; +})(ts || (ts = {})); var ts; (function (ts) { var SignatureFlags; @@ -13409,7 +14499,6 @@ var ts; 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 = {})); @@ -13420,7 +14509,7 @@ var ts; var SourceFileConstructor; // tslint:enable variable-name function createNode(kind, pos, end) { - if (kind === 272 /* SourceFile */) { + if (kind === 277 /* SourceFile */) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end); } else if (kind === 71 /* Identifier */) { @@ -13451,6 +14540,13 @@ var ts; } } } + /*@internal*/ + function isJSDocLikeText(text, start) { + return text.charCodeAt(start + 1) === 42 /* asterisk */ && + text.charCodeAt(start + 2) === 42 /* asterisk */ && + text.charCodeAt(start + 3) !== 47 /* slash */; + } + ts.isJSDocLikeText = isJSDocLikeText; /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -13465,28 +14561,28 @@ var ts; * that they appear in the source code. The language service depends on this property to locate nodes by position. */ function forEachChild(node, cbNode, cbNodes) { - if (!node || node.kind <= 144 /* LastToken */) { + if (!node || node.kind <= 145 /* LastToken */) { return; } switch (node.kind) { - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || visitNode(cbNode, node.expression); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.equalsToken) || visitNode(cbNode, node.objectAssignmentInitializer); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return visitNode(cbNode, node.expression); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || @@ -13494,7 +14590,7 @@ var ts; visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || @@ -13502,51 +14598,51 @@ var ts; visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.initializer); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || visitNode(cbNode, node.initializer); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || @@ -13557,298 +14653,302 @@ var ts; visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || visitNode(cbNode, node.body); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return visitNode(cbNode, node.typeName) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return visitNode(cbNode, node.parameterName) || visitNode(cbNode, node.type); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return visitNode(cbNode, node.exprName); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return visitNodes(cbNode, cbNodes, node.members); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return visitNode(cbNode, node.elementType); - case 167 /* TupleType */: + case 168 /* TupleType */: return visitNodes(cbNode, cbNodes, node.elementTypes); - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return visitNodes(cbNode, cbNodes, node.types); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || visitNode(cbNode, node.falseType); - case 171 /* InferType */: + case 174 /* InferType */: return visitNode(cbNode, node.typeParameter); - case 172 /* ParenthesizedType */: - case 174 /* TypeOperator */: + case 181 /* ImportType */: + return visitNode(cbNode, node.argument) || + visitNode(cbNode, node.qualifier) || + visitNodes(cbNode, cbNodes, node.typeArguments); + case 175 /* ParenthesizedType */: + case 177 /* TypeOperator */: return visitNode(cbNode, node.type); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return visitNode(cbNode, node.objectType) || visitNode(cbNode, node.indexType); - case 176 /* MappedType */: + case 179 /* MappedType */: return visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return visitNode(cbNode, node.literal); - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return visitNodes(cbNode, cbNodes, node.elements); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitNodes(cbNode, cbNodes, node.properties); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.name); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.argumentExpression); - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments) || visitNodes(cbNode, cbNodes, node.arguments); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitNode(cbNode, node.tag) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.template); - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: return visitNode(cbNode, node.type) || visitNode(cbNode, node.expression); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitNode(cbNode, node.expression); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return visitNode(cbNode, node.expression); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return visitNode(cbNode, node.expression); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return visitNode(cbNode, node.expression); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return visitNode(cbNode, node.operand); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.expression); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitNode(cbNode, node.expression); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return visitNode(cbNode, node.operand); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || visitNode(cbNode, node.right); - case 206 /* AsExpression */: + case 210 /* AsExpression */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return visitNode(cbNode, node.expression); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return visitNode(cbNode, node.name); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || visitNode(cbNode, node.whenFalse); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return visitNode(cbNode, node.expression); - case 211 /* Block */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return visitNodes(cbNode, cbNodes, node.statements); - case 272 /* SourceFile */: + case 277 /* SourceFile */: return visitNodes(cbNode, cbNodes, node.statements) || visitNode(cbNode, node.endOfFileToken); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.declarationList); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitNodes(cbNode, cbNodes, node.declarations); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitNode(cbNode, node.expression); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || visitNode(cbNode, node.elseStatement); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitNode(cbNode, node.statement) || visitNode(cbNode, node.expression); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || visitNode(cbNode, node.statement); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return visitNode(cbNode, node.label); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitNode(cbNode, node.expression); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.statement); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.caseBlock); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitNodes(cbNode, cbNodes, node.clauses); - case 264 /* CaseClause */: + case 269 /* CaseClause */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.statements); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return visitNodes(cbNode, cbNodes, node.statements); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitNode(cbNode, node.label) || visitNode(cbNode, node.statement); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return visitNode(cbNode, node.expression); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || visitNode(cbNode, node.finallyBlock); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitNode(cbNode, node.variableDeclaration) || visitNode(cbNode, node.block); - case 149 /* Decorator */: + case 150 /* Decorator */: return visitNode(cbNode, node.expression); - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || visitNodes(cbNode, cbNodes, node.members); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNode(cbNode, node.type); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.members); - case 271 /* EnumMember */: + case 276 /* EnumMember */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.body); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.moduleReference); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.namedBindings); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return visitNode(cbNode, node.name); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return visitNode(cbNode, node.name); - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return visitNodes(cbNode, cbNodes, node.elements); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier); - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.expression); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans); - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return visitNode(cbNode, node.expression); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: return visitNodes(cbNode, cbNodes, node.types); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return visitNode(cbNode, node.expression) || visitNodes(cbNode, cbNodes, node.typeArguments); - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return visitNode(cbNode, node.expression); - case 251 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return visitNodes(cbNode, cbNodes, node.decorators); - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: return visitNodes(cbNode, cbNodes, node.elements); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingElement); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || visitNode(cbNode, node.closingFragment); - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: return visitNode(cbNode, node.tagName) || + visitNodes(cbNode, cbNodes, node.typeArguments) || visitNode(cbNode, node.attributes); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return visitNodes(cbNode, cbNodes, node.properties); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return visitNode(cbNode, node.expression); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.expression); - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: return visitNode(cbNode, node.tagName); - case 274 /* JSDocTypeExpression */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 281 /* JSDocTypeExpression */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 286 /* JSDocOptionalType */: + case 288 /* JSDocVariadicType */: return visitNode(cbNode, node.type); - case 278 /* JSDocNonNullableType */: - return visitNode(cbNode, node.type); - case 277 /* JSDocNullableType */: - return visitNode(cbNode, node.type); - case 279 /* JSDocOptionalType */: - return visitNode(cbNode, node.type); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type); - case 281 /* JSDocVariadicType */: - return visitNode(cbNode, node.type); - case 282 /* JSDocComment */: + case 289 /* JSDocComment */: return visitNodes(cbNode, cbNodes, node.tags); - case 287 /* JSDocParameterTag */: - case 292 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: + case 302 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -13857,17 +14957,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 288 /* JSDocReturnTag */: + case 297 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 285 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: return visitNodes(cbNode, cbNodes, node.typeParameters); - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 274 /* JSDocTypeExpression */) { + node.typeExpression.kind === 281 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -13875,7 +14975,18 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 283 /* JSDocTypeLiteral */: + case 295 /* JSDocCallbackTag */: + return visitNode(cbNode, node.fullName) || + visitNode(cbNode, node.typeExpression); + case 298 /* JSDocThisTag */: + return visitNode(cbNode, node.typeExpression); + case 291 /* JSDocSignature */: + return visitNodes(cbNode, cbNodes, node.decorators) || + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNodes(cbNode, cbNodes, node.typeParameters) || + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type); + case 290 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -13883,7 +14994,7 @@ var ts; } } return; - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -13891,7 +15002,13 @@ var ts; function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) { if (setParentNodes === void 0) { setParentNodes = false; } ts.performance.mark("beforeParse"); - var result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + var result; + if (languageVersion === 100 /* JSON */) { + result = Parser.parseJsonText(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + } + else { + result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind); + } ts.performance.mark("afterParse"); ts.performance.measure("Parse", "beforeParse", "afterParse"); return result; @@ -13925,10 +15042,11 @@ var ts; // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) { + if (aggressiveChecks === void 0) { aggressiveChecks = false; } var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. - newSourceFile.flags |= (sourceFile.flags & 524288 /* PossiblyContainsDynamicImport */); + newSourceFile.flags |= (sourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */); return newSourceFile; } ts.updateSourceFile = updateSourceFile; @@ -14050,7 +15168,15 @@ var ts; // attached to the EOF token. var parseErrorBeforeNextFinishedNode = false; function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) { + if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); + if (scriptKind === 6 /* JSON */) { + var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_1.typeReferenceDirectives = ts.emptyArray; + result_1.amdDependencies = ts.emptyArray; + return result_1; + } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); clearState(); @@ -14068,25 +15194,58 @@ var ts; return isInvalid ? entityName : undefined; } Parser.parseIsolatedEntityName = parseIsolatedEntityName; - function parseJsonText(fileName, sourceText) { - initializeState(sourceText, 2 /* ES2015 */, /*syntaxCursor*/ undefined, 6 /* JSON */); + function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) { + if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; } + initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */); // Set source file so that errors will be reported with this file name sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false); - var result = sourceFile; + sourceFile.flags = contextFlags; // Prime the scanner. nextToken(); + var pos = getNodePos(); if (token() === 1 /* EndOfFileToken */) { + sourceFile.statements = createNodeArray([], pos, pos); sourceFile.endOfFileToken = parseTokenNode(); } - else if (token() === 17 /* OpenBraceToken */ || - lookAhead(function () { return token() === 9 /* StringLiteral */; })) { - result.jsonObject = parseObjectLiteralExpression(); + else { + var statement = createNode(219 /* ExpressionStatement */); + switch (token()) { + case 21 /* OpenBracketToken */: + statement.expression = parseArrayLiteralExpression(); + break; + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + statement.expression = parseTokenNode(); + break; + case 38 /* MinusToken */: + if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parsePrefixUnaryExpression(); + } + else { + statement.expression = parseObjectLiteralExpression(); + } + break; + case 8 /* NumericLiteral */: + case 9 /* StringLiteral */: + if (lookAhead(function () { return nextToken() !== 56 /* ColonToken */; })) { + statement.expression = parseLiteralNode(); + break; + } + // falls through + default: + statement.expression = parseObjectLiteralExpression(); + break; + } + finishNode(statement); + sourceFile.statements = createNodeArray([statement], pos); sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token); } - else { - parseExpected(17 /* OpenBraceToken */); + if (setParentNodes) { + fixupParentReferences(sourceFile); } sourceFile.parseDiagnostics = parseDiagnostics; + var result = sourceFile; clearState(); return result; } @@ -14110,9 +15269,11 @@ var ts; switch (scriptKind) { case 1 /* JS */: case 2 /* JSX */: - case 6 /* JSON */: contextFlags = 65536 /* JavaScriptFile */; break; + case 6 /* JSON */: + contextFlags = 65536 /* JavaScriptFile */ | 16777216 /* JsonFile */; + break; default: contextFlags = 0 /* None */; break; @@ -14138,7 +15299,7 @@ var ts; function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) { var isDeclarationFile = isDeclarationFileName(fileName); if (isDeclarationFile) { - contextFlags |= 2097152 /* Ambient */; + contextFlags |= 4194304 /* Ambient */; } sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile); sourceFile.flags = contextFlags; @@ -14164,13 +15325,10 @@ var ts; } } function addJSDocComment(node) { - var comments = ts.getJSDocCommentRanges(node, sourceFile.text); - if (comments) { - for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { - var comment = comments_2[_i]; - node.jsDoc = ts.append(node.jsDoc, JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - } - } + ts.Debug.assert(!node.jsDoc); // Should only be called once per node + var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); }); + if (jsDoc.length) + node.jsDoc = jsDoc; return node; } function fixupParentReferences(rootNode) { @@ -14206,10 +15364,11 @@ var ts; function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - var sourceFile = new SourceFileConstructor(272 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); + var sourceFile = new SourceFileConstructor(277 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length); nodeCount++; sourceFile.text = sourceText; sourceFile.bindDiagnostics = []; + sourceFile.bindSuggestionDiagnostics = undefined; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); sourceFile.languageVariant = getLanguageVariant(scriptKind); @@ -14312,9 +15471,7 @@ var ts; return inContext(16384 /* AwaitContext */); } function parseErrorAtCurrentToken(message, arg0) { - var start = scanner.getTokenPos(); - var length = scanner.getTextPos() - start; - parseErrorAtPosition(start, length, message, arg0); + parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0); } function parseErrorAtPosition(start, length, message, arg0) { // Don't report another error if it would just be at the same position as the last error. @@ -14326,9 +15483,14 @@ var ts; // node we finish so that it can't be reused incrementally. parseErrorBeforeNextFinishedNode = true; } + function parseErrorAt(start, end, message, arg0) { + parseErrorAtPosition(start, end - start, message, arg0); + } + function parseErrorAtRange(range, message, arg0) { + parseErrorAt(range.pos, range.end, message, arg0); + } function scanError(message, length) { - var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, length || 0, message); + parseErrorAtPosition(scanner.getTextPos(), length, message); } function getNodePos() { return scanner.getStartPos(); @@ -14488,8 +15650,8 @@ var ts; kind === 71 /* Identifier */ ? new IdentifierConstructor(kind, p, p) : new TokenConstructor(kind, p, p); } - function createNodeWithJSDoc(kind) { - var node = createNode(kind); + function createNodeWithJSDoc(kind, pos) { + var node = createNode(kind, pos); if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */) { addJSDocComment(node); } @@ -14523,7 +15685,7 @@ var ts; if (reportAtCurrentPosition) { parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0); } - else { + else if (diagnosticMessage) { parseErrorAtCurrentToken(diagnosticMessage, arg0); } var result = createNode(kind); @@ -14590,7 +15752,7 @@ var ts; // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - var node = createNode(146 /* ComputedPropertyName */); + var node = createNode(147 /* ComputedPropertyName */); parseExpected(21 /* OpenBracketToken */); // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker @@ -14610,25 +15772,26 @@ var ts; return canFollowModifier(); } function nextTokenCanFollowModifier() { - if (token() === 76 /* ConstKeyword */) { - // 'const' is only a modifier if followed by 'enum'. - return nextToken() === 83 /* EnumKeyword */; + switch (token()) { + case 76 /* ConstKeyword */: + // 'const' is only a modifier if followed by 'enum'. + return nextToken() === 83 /* EnumKeyword */; + case 84 /* ExportKeyword */: + nextToken(); + if (token() === 79 /* DefaultKeyword */) { + return lookAhead(nextTokenCanFollowDefaultKeyword); + } + return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); + case 79 /* DefaultKeyword */: + return nextTokenCanFollowDefaultKeyword(); + case 115 /* StaticKeyword */: + case 125 /* GetKeyword */: + case 136 /* SetKeyword */: + nextToken(); + return canFollowModifier(); + default: + return nextTokenIsOnSameLineAndCanFollowModifier(); } - if (token() === 84 /* ExportKeyword */) { - nextToken(); - if (token() === 79 /* DefaultKeyword */) { - return lookAhead(nextTokenCanFollowDefaultKeyword); - } - return token() !== 39 /* AsteriskToken */ && token() !== 118 /* AsKeyword */ && token() !== 17 /* OpenBraceToken */ && canFollowModifier(); - } - if (token() === 79 /* DefaultKeyword */) { - return nextTokenCanFollowDefaultKeyword(); - } - if (token() === 115 /* StaticKeyword */) { - nextToken(); - return canFollowModifier(); - } - return nextTokenIsOnSameLineAndCanFollowModifier(); } function parseAnyContextualModifier() { return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier); @@ -14726,7 +15889,7 @@ var ts; case 14 /* JsxChildren */: return true; } - ts.Debug.fail("Non-exhaustive case in 'isListElement'."); + return ts.Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); @@ -14815,6 +15978,8 @@ var ts; return token() === 29 /* GreaterThanToken */ || token() === 41 /* SlashToken */; case 14 /* JsxChildren */: return token() === 27 /* LessThanToken */ && lookAhead(nextTokenIsSlash); + default: + return false; } } function isVariableDeclaratorListTerminator() { @@ -14915,7 +16080,7 @@ var ts; // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - var nodeContextFlags = node.flags & 6387712 /* ContextFlags */; + var nodeContextFlags = node.flags & 12679168 /* ContextFlags */; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -15001,14 +16166,14 @@ var ts; function isReusableClassMember(node) { if (node) { switch (node.kind) { - case 154 /* Constructor */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 151 /* PropertyDeclaration */: - case 210 /* SemicolonClassElement */: + case 155 /* Constructor */: + case 160 /* IndexSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 215 /* SemicolonClassElement */: return true; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. @@ -15023,8 +16188,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: return true; } } @@ -15033,58 +16198,58 @@ var ts; function isReusableStatement(node) { if (node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 212 /* VariableStatement */: - case 211 /* Block */: - case 215 /* IfStatement */: - case 214 /* ExpressionStatement */: - case 227 /* ThrowStatement */: - case 223 /* ReturnStatement */: - case 225 /* SwitchStatement */: - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 213 /* EmptyStatement */: - case 228 /* TryStatement */: - case 226 /* LabeledStatement */: - case 216 /* DoStatement */: - case 229 /* DebuggerStatement */: - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - case 247 /* ExportAssignment */: - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 217 /* VariableStatement */: + case 216 /* Block */: + case 220 /* IfStatement */: + case 219 /* ExpressionStatement */: + case 232 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 230 /* SwitchStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 218 /* EmptyStatement */: + case 233 /* TryStatement */: + case 231 /* LabeledStatement */: + case 221 /* DoStatement */: + case 234 /* DebuggerStatement */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: return true; } } return false; } function isReusableEnumMember(node) { - return node.kind === 271 /* EnumMember */; + return node.kind === 276 /* EnumMember */; } function isReusableTypeMember(node) { if (node) { switch (node.kind) { - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 150 /* PropertySignature */: - case 157 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 151 /* PropertySignature */: + case 158 /* CallSignature */: return true; } } return false; } function isReusableVariableDeclaration(node) { - if (node.kind !== 230 /* VariableDeclaration */) { + if (node.kind !== 235 /* VariableDeclaration */) { return false; } // Very subtle incremental parsing bug. Consider the following code: @@ -15105,7 +16270,7 @@ var ts; return variableDeclarator.initializer === undefined; } function isReusableParameter(node) { - if (node.kind !== 148 /* Parameter */) { + if (node.kind !== 149 /* Parameter */) { return false; } // See the comment in isReusableVariableDeclaration for why we do this. @@ -15146,6 +16311,7 @@ var ts; case 22 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected; case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected; case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected; + default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);` } } // Parses a comma-delimited list of elements @@ -15209,7 +16375,12 @@ var ts; return result; } function createMissingList() { - return createNodeArray([], getNodePos()); + var list = createNodeArray([], getNodePos()); + list.isMissingList = true; + return list; + } + function isMissingList(arr) { + return !!arr.isMissingList; } function parseBracketedList(kind, parseElement, open, close) { if (parseExpected(open)) { @@ -15234,7 +16405,7 @@ var ts; return entity; } function createQualifiedName(entity, name) { - var node = createNode(145 /* QualifiedName */, entity.pos); + var node = createNode(146 /* QualifiedName */, entity.pos); node.left = entity; node.right = name; return finishNode(node); @@ -15271,19 +16442,19 @@ var ts; return allowIdentifierNames ? parseIdentifierName() : parseIdentifier(); } function parseTemplateExpression() { - var template = createNode(200 /* TemplateExpression */); + var template = createNode(204 /* TemplateExpression */); template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 14 /* TemplateHead */, "Template head has wrong token kind"); var list = []; var listPos = getNodePos(); do { list.push(parseTemplateSpan()); - } while (ts.lastOrUndefined(list).literal.kind === 15 /* TemplateMiddle */); + } while (ts.last(list).literal.kind === 15 /* TemplateMiddle */); template.templateSpans = createNodeArray(list, listPos); return finishNode(template); } function parseTemplateSpan() { - var span = createNode(209 /* TemplateSpan */); + var span = createNode(214 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token() === 18 /* CloseBraceToken */) { @@ -15334,28 +16505,55 @@ var ts; } // TYPES function parseTypeReference() { - var node = createNode(161 /* TypeReference */); + var node = createNode(162 /* TypeReference */); node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); if (!scanner.hasPrecedingLineBreak() && token() === 27 /* LessThanToken */) { node.typeArguments = parseBracketedList(19 /* TypeArguments */, parseType, 27 /* LessThanToken */, 29 /* GreaterThanToken */); } return finishNode(node); } + // If true, we should abort parsing an error function. + function typeHasArrowFunctionBlockingParseError(node) { + switch (node.kind) { + case 162 /* TypeReference */: + return ts.nodeIsMissing(node.typeName); + case 163 /* FunctionType */: + case 164 /* ConstructorType */: { + var _a = node, parameters = _a.parameters, type = _a.type; + return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + } + case 175 /* ParenthesizedType */: + return typeHasArrowFunctionBlockingParseError(node.type); + default: + return false; + } + } function parseThisTypePredicate(lhs) { nextToken(); - var node = createNode(160 /* TypePredicate */, lhs.pos); + var node = createNode(161 /* TypePredicate */, lhs.pos); node.parameterName = lhs; node.type = parseType(); return finishNode(node); } function parseThisTypeNode() { - var node = createNode(173 /* ThisType */); + var node = createNode(176 /* ThisType */); nextToken(); return finishNode(node); } - function parseJSDocAllType() { - var result = createNode(275 /* JSDocAllType */); + function parseJSDocAllType(postFixEquals) { + var result = createNode(282 /* JSDocAllType */); + if (postFixEquals) { + return createPostfixType(286 /* JSDocOptionalType */, result); + } + else { + nextToken(); + } + return finishNode(result); + } + function parseJSDocNonNullableType() { + var result = createNode(285 /* JSDocNonNullableType */); nextToken(); + result.type = parseNonArrayType(); return finishNode(result); } function parseJSDocUnknownOrNullableType() { @@ -15377,49 +16575,56 @@ var ts; token() === 29 /* GreaterThanToken */ || token() === 58 /* EqualsToken */ || token() === 49 /* BarToken */) { - var result = createNode(276 /* JSDocUnknownType */, pos); + var result = createNode(283 /* JSDocUnknownType */, pos); return finishNode(result); } else { - var result = createNode(277 /* JSDocNullableType */, pos); + var result = createNode(284 /* JSDocNullableType */, pos); result.type = parseType(); return finishNode(result); } } function parseJSDocFunctionType() { if (lookAhead(nextTokenIsOpenParen)) { - var result = createNodeWithJSDoc(280 /* JSDocFunctionType */); + var result = createNodeWithJSDoc(287 /* JSDocFunctionType */); nextToken(); fillSignature(56 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result); return finishNode(result); } - var node = createNode(161 /* TypeReference */); + var node = createNode(162 /* TypeReference */); node.typeName = parseIdentifierName(); return finishNode(node); } function parseJSDocParameter() { - var parameter = createNode(148 /* Parameter */); + var parameter = createNode(149 /* Parameter */); if (token() === 99 /* ThisKeyword */ || token() === 94 /* NewKeyword */) { parameter.name = parseIdentifierName(); parseExpected(56 /* ColonToken */); } - parameter.type = parseType(); + parameter.type = parseJSDocType(); return finishNode(parameter); } - function parseJSDocNodeWithType(kind) { - var result = createNode(kind); - nextToken(); - result.type = parseNonArrayType(); - return finishNode(result); + function parseJSDocType() { + var dotdotdot = parseOptionalToken(24 /* DotDotDotToken */); + var type = parseType(); + if (dotdotdot) { + var variadic = createNode(288 /* JSDocVariadicType */, dotdotdot.pos); + variadic.type = type; + type = finishNode(variadic); + } + if (token() === 58 /* EqualsToken */) { + return createPostfixType(286 /* JSDocOptionalType */, type); + } + return type; } function parseTypeQuery() { - var node = createNode(164 /* TypeQuery */); + var node = createNode(165 /* TypeQuery */); parseExpected(103 /* TypeOfKeyword */); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter() { - var node = createNode(147 /* TypeParameter */); + var node = createNode(148 /* TypeParameter */); node.name = parseIdentifier(); if (parseOptional(85 /* ExtendsKeyword */)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -15464,7 +16669,7 @@ var ts; isStartOfType(/*inStartOfParameter*/ true); } function parseParameter() { - var node = createNodeWithJSDoc(148 /* Parameter */); + var node = createNodeWithJSDoc(149 /* Parameter */); if (token() === 99 /* ThisKeyword */) { node.name = createIdentifier(/*isIdentifier*/ true); node.type = parseParameterType(); @@ -15492,15 +16697,21 @@ var ts; node.initializer = parseInitializer(); return finishNode(node); } + /** + * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined. + * @returns If return type parsing succeeds + */ function fillSignature(returnToken, flags, signature) { if (!(flags & 32 /* JSDoc */)) { signature.typeParameters = parseTypeParameters(); } - signature.parameters = parseParameterList(flags); - signature.type = parseReturnType(returnToken, !!(flags & 4 /* Type */)); - } - function parseReturnType(returnToken, isType) { - return shouldParseReturnType(returnToken, isType) ? parseTypeOrTypePredicate() : undefined; + var parametersParsedSuccessfully = parseParameterList(signature, flags); + if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) { + signature.type = parseTypeOrTypePredicate(); + if (typeHasArrowFunctionBlockingParseError(signature.type)) + return false; + } + return parametersParsedSuccessfully; } function shouldParseReturnType(returnToken, isType) { if (returnToken === 36 /* EqualsGreaterThanToken */) { @@ -15518,7 +16729,8 @@ var ts; } return false; } - function parseParameterList(flags) { + // Returns true on success. + function parseParameterList(signature, flags) { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -15532,25 +16744,18 @@ var ts; // // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt - if (parseExpected(19 /* OpenParenToken */)) { - var savedYieldContext = inYieldContext(); - var savedAwaitContext = inAwaitContext(); - setYieldContext(!!(flags & 1 /* Yield */)); - setAwaitContext(!!(flags & 2 /* Await */)); - var result = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); - setYieldContext(savedYieldContext); - setAwaitContext(savedAwaitContext); - if (!parseExpected(20 /* CloseParenToken */) && (flags & 8 /* RequireCompleteParameterList */)) { - // Caller insisted that we had to end with a ) We didn't. So just return - // undefined here. - return undefined; - } - return result; + if (!parseExpected(19 /* OpenParenToken */)) { + signature.parameters = createMissingList(); + return false; } - // We didn't even have an open paren. If the caller requires a complete parameter list, - // we definitely can't provide that. However, if they're ok with an incomplete one, - // then just return an empty set of parameters. - return (flags & 8 /* RequireCompleteParameterList */) ? undefined : createMissingList(); + var savedYieldContext = inYieldContext(); + var savedAwaitContext = inAwaitContext(); + setYieldContext(!!(flags & 1 /* Yield */)); + setAwaitContext(!!(flags & 2 /* Await */)); + signature.parameters = parseDelimitedList(16 /* Parameters */, flags & 32 /* JSDoc */ ? parseJSDocParameter : parseParameter); + setYieldContext(savedYieldContext); + setAwaitContext(savedAwaitContext); + return parseExpected(20 /* CloseParenToken */); } function parseTypeMemberSemicolon() { // We allow type members to be separated by commas or (possibly ASI) semicolons. @@ -15563,7 +16768,7 @@ var ts; } function parseSignatureMember(kind) { var node = createNodeWithJSDoc(kind); - if (kind === 158 /* ConstructSignature */) { + if (kind === 159 /* ConstructSignature */) { parseExpected(94 /* NewKeyword */); } fillSignature(56 /* ColonToken */, 4 /* Type */, node); @@ -15624,7 +16829,7 @@ var ts; return token() === 56 /* ColonToken */ || token() === 26 /* CommaToken */ || token() === 22 /* CloseBracketToken */; } function parseIndexSignatureDeclaration(node) { - node.kind = 159 /* IndexSignature */; + node.kind = 160 /* IndexSignature */; node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); node.type = parseTypeAnnotation(); parseTypeMemberSemicolon(); @@ -15634,13 +16839,13 @@ var ts; node.name = parsePropertyName(); node.questionToken = parseOptionalToken(55 /* QuestionToken */); if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - node.kind = 152 /* MethodSignature */; + node.kind = 153 /* MethodSignature */; // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] fillSignature(56 /* ColonToken */, 4 /* Type */, node); } else { - node.kind = 150 /* PropertySignature */; + node.kind = 151 /* PropertySignature */; node.type = parseTypeAnnotation(); if (token() === 58 /* EqualsToken */) { // Although type literal properties cannot not have initializers, we attempt @@ -15657,7 +16862,7 @@ var ts; if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { return true; } - var idToken; + var idToken = false; // Eat up all modifiers, but hold on to the last one in case it is actually an identifier while (ts.isModifierKind(token())) { idToken = true; @@ -15686,10 +16891,10 @@ var ts; } function parseTypeMember() { if (token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */) { - return parseSignatureMember(157 /* CallSignature */); + return parseSignatureMember(158 /* CallSignature */); } if (token() === 94 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - return parseSignatureMember(158 /* ConstructSignature */); + return parseSignatureMember(159 /* ConstructSignature */); } var node = createNodeWithJSDoc(0 /* Unknown */); node.modifiers = parseModifiers(); @@ -15702,8 +16907,20 @@ var ts; nextToken(); return token() === 19 /* OpenParenToken */ || token() === 27 /* LessThanToken */; } + function nextTokenIsDot() { + return nextToken() === 23 /* DotToken */; + } + function nextTokenIsOpenParenOrLessThanOrDot() { + switch (nextToken()) { + case 19 /* OpenParenToken */: + case 27 /* LessThanToken */: + case 23 /* DotToken */: + return true; + } + return false; + } function parseTypeLiteral() { - var node = createNode(165 /* TypeLiteral */); + var node = createNode(166 /* TypeLiteral */); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -15729,14 +16946,14 @@ var ts; return token() === 21 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 92 /* InKeyword */; } function parseMappedTypeParameter() { - var node = createNode(147 /* TypeParameter */); + var node = createNode(148 /* TypeParameter */); node.name = parseIdentifier(); parseExpected(92 /* InKeyword */); node.constraint = parseType(); return finishNode(node); } function parseMappedType() { - var node = createNode(176 /* MappedType */); + var node = createNode(179 /* MappedType */); parseExpected(17 /* OpenBraceToken */); if (token() === 132 /* ReadonlyKeyword */ || token() === 37 /* PlusToken */ || token() === 38 /* MinusToken */) { node.readonlyToken = parseTokenNode(); @@ -15758,23 +16975,35 @@ var ts; parseExpected(18 /* CloseBraceToken */); return finishNode(node); } + function parseTupleElementType() { + var pos = getNodePos(); + if (parseOptional(24 /* DotDotDotToken */)) { + var node = createNode(170 /* RestType */, pos); + node.type = parseType(); + return finishNode(node); + } + var type = parseType(); + if (!(contextFlags & 2097152 /* JSDoc */) && type.kind === 284 /* JSDocNullableType */ && type.pos === type.type.pos) { + type.kind = 169 /* OptionalType */; + } + return type; + } function parseTupleType() { - var node = createNode(167 /* TupleType */); - node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); + var node = createNode(168 /* TupleType */); + node.elementTypes = parseBracketedList(20 /* TupleElementTypes */, parseTupleElementType, 21 /* OpenBracketToken */, 22 /* CloseBracketToken */); return finishNode(node); } function parseParenthesizedType() { - var node = createNode(172 /* ParenthesizedType */); + var node = createNode(175 /* ParenthesizedType */); parseExpected(19 /* OpenParenToken */); node.type = parseType(); parseExpected(20 /* CloseParenToken */); return finishNode(node); } - function parseFunctionOrConstructorType(kind) { - var node = createNodeWithJSDoc(kind); - if (kind === 163 /* ConstructorType */) { - parseExpected(94 /* NewKeyword */); - } + function parseFunctionOrConstructorType() { + var pos = getNodePos(); + var kind = parseOptional(94 /* NewKeyword */) ? 164 /* ConstructorType */ : 163 /* FunctionType */; + var node = createNodeWithJSDoc(kind, pos); fillSignature(36 /* EqualsGreaterThanToken */, 4 /* Type */, node); return finishNode(node); } @@ -15783,10 +17012,10 @@ var ts; return token() === 23 /* DotToken */ ? undefined : node; } function parseLiteralTypeNode(negative) { - var node = createNode(177 /* LiteralType */); + var node = createNode(180 /* LiteralType */); var unaryMinusExpression; if (negative) { - unaryMinusExpression = createNode(196 /* PrefixUnaryExpression */); + unaryMinusExpression = createNode(200 /* PrefixUnaryExpression */); unaryMinusExpression.operator = 38 /* MinusToken */; nextToken(); } @@ -15801,12 +17030,33 @@ var ts; node.literal = expression; return finishNode(node); } + function isStartOfTypeOfImportType() { + nextToken(); + return token() === 91 /* ImportKeyword */; + } + function parseImportType() { + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + var node = createNode(181 /* ImportType */); + if (parseOptional(103 /* TypeOfKeyword */)) { + node.isTypeOf = true; + } + parseExpected(91 /* ImportKeyword */); + parseExpected(19 /* OpenParenToken */); + node.argument = parseType(); + parseExpected(20 /* CloseParenToken */); + if (parseOptional(23 /* DotToken */)) { + node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected); + } + node.typeArguments = tryParseTypeArguments(); + return finishNode(node); + } function nextTokenIsNumericLiteral() { return nextToken() === 8 /* NumericLiteral */; } function parseNonArrayType() { switch (token()) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 138 /* SymbolKeyword */: @@ -15817,13 +17067,15 @@ var ts; // If these are followed by a dot, then parse these out as a dotted type reference instead. return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 39 /* AsteriskToken */: - return parseJSDocAllType(); + return parseJSDocAllType(/*postfixEquals*/ false); + case 61 /* AsteriskEqualsToken */: + return parseJSDocAllType(/*postfixEquals*/ true); case 55 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 89 /* FunctionKeyword */: return parseJSDocFunctionType(); case 51 /* ExclamationToken */: - return parseJSDocNodeWithType(278 /* JSDocNonNullableType */); + return parseJSDocNonNullableType(); case 13 /* NoSubstitutionTemplateLiteral */: case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -15845,13 +17097,15 @@ var ts; } } case 103 /* TypeOfKeyword */: - return parseTypeQuery(); + return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); case 17 /* OpenBraceToken */: return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); case 21 /* OpenBracketToken */: return parseTupleType(); case 19 /* OpenParenToken */: return parseParenthesizedType(); + case 91 /* ImportKeyword */: + return parseImportType(); default: return parseTypeReference(); } @@ -15859,6 +17113,7 @@ var ts; function isStartOfType(inStartOfParameter) { switch (token()) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 122 /* BooleanKeyword */: @@ -15886,6 +17141,7 @@ var ts; case 51 /* ExclamationToken */: case 24 /* DotDotDotToken */: case 126 /* InferKeyword */: + case 91 /* ImportKeyword */: return true; case 38 /* MinusToken */: return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral); @@ -15905,34 +17161,27 @@ var ts; var type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak()) { switch (token()) { - case 58 /* EqualsToken */: - // only parse postfix = inside jsdoc, because it's ambiguous elsewhere - if (!(contextFlags & 1048576 /* JSDoc */)) { - return type; - } - type = createJSDocPostfixType(279 /* JSDocOptionalType */, type); - break; case 51 /* ExclamationToken */: - type = createJSDocPostfixType(278 /* JSDocNonNullableType */, type); + type = createPostfixType(285 /* JSDocNonNullableType */, type); break; case 55 /* QuestionToken */: // If not in JSDoc and next token is start of a type we have a conditional type - if (!(contextFlags & 1048576 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { + if (!(contextFlags & 2097152 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) { return type; } - type = createJSDocPostfixType(277 /* JSDocNullableType */, type); + type = createPostfixType(284 /* JSDocNullableType */, type); break; case 21 /* OpenBracketToken */: parseExpected(21 /* OpenBracketToken */); if (isStartOfType()) { - var node = createNode(175 /* IndexedAccessType */, type.pos); + var node = createNode(178 /* IndexedAccessType */, type.pos); node.objectType = type; node.indexType = parseType(); parseExpected(22 /* CloseBracketToken */); type = finishNode(node); } else { - var node = createNode(166 /* ArrayType */, type.pos); + var node = createNode(167 /* ArrayType */, type.pos); node.elementType = type; parseExpected(22 /* CloseBracketToken */); type = finishNode(node); @@ -15944,23 +17193,23 @@ var ts; } return type; } - function createJSDocPostfixType(kind, type) { + function createPostfixType(kind, type) { nextToken(); var postfix = createNode(kind, type.pos); postfix.type = type; return finishNode(postfix); } function parseTypeOperator(operator) { - var node = createNode(174 /* TypeOperator */); + var node = createNode(177 /* TypeOperator */); parseExpected(operator); node.operator = operator; node.type = parseTypeOperatorOrHigher(); return finishNode(node); } function parseInferType() { - var node = createNode(171 /* InferType */); + var node = createNode(174 /* InferType */); parseExpected(126 /* InferKeyword */); - var typeParameter = createNode(147 /* TypeParameter */); + var typeParameter = createNode(148 /* TypeParameter */); typeParameter.name = parseIdentifier(); node.typeParameter = finishNode(typeParameter); return finishNode(node); @@ -15973,12 +17222,6 @@ var ts; return parseTypeOperator(operator); case 126 /* InferKeyword */: return parseInferType(); - case 24 /* DotDotDotToken */: { - var result = createNode(281 /* JSDocVariadicType */); - nextToken(); - result.type = parsePostfixTypeOrHigher(); - return finishNode(result); - } } return parsePostfixTypeOrHigher(); } @@ -15997,10 +17240,10 @@ var ts; return type; } function parseIntersectionTypeOrHigher() { - return parseUnionOrIntersectionType(169 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); + return parseUnionOrIntersectionType(172 /* IntersectionType */, parseTypeOperatorOrHigher, 48 /* AmpersandToken */); } function parseUnionTypeOrHigher() { - return parseUnionOrIntersectionType(168 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); + return parseUnionOrIntersectionType(171 /* UnionType */, parseIntersectionTypeOrHigher, 49 /* BarToken */); } function isStartOfFunctionType() { if (token() === 27 /* LessThanToken */) { @@ -16057,7 +17300,7 @@ var ts; var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); var type = parseType(); if (typePredicateVariable) { - var node = createNode(160 /* TypePredicate */, typePredicateVariable.pos); + var node = createNode(161 /* TypePredicate */, typePredicateVariable.pos); node.parameterName = typePredicateVariable; node.type = type; return finishNode(node); @@ -16079,15 +17322,12 @@ var ts; return doOutsideOfContext(20480 /* TypeExcludesFlags */, parseTypeWorker); } function parseTypeWorker(noConditionalTypes) { - if (isStartOfFunctionType()) { - return parseFunctionOrConstructorType(162 /* FunctionType */); - } - if (token() === 94 /* NewKeyword */) { - return parseFunctionOrConstructorType(163 /* ConstructorType */); + if (isStartOfFunctionType() || token() === 94 /* NewKeyword */) { + return parseFunctionOrConstructorType(); } var type = parseUnionTypeOrHigher(); if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(85 /* ExtendsKeyword */)) { - var node = createNode(170 /* ConditionalType */, type.pos); + var node = createNode(173 /* ConditionalType */, type.pos); node.checkType = type; // The type following 'extends' is not permitted to be another conditional type node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true); @@ -16125,7 +17365,7 @@ var ts; case 71 /* Identifier */: return true; case 91 /* ImportKeyword */: - return lookAhead(nextTokenIsOpenParenOrLessThan); + return lookAhead(nextTokenIsOpenParenOrLessThanOrDot); default: return isIdentifier(); } @@ -16280,7 +17520,7 @@ var ts; return !scanner.hasPrecedingLineBreak() && isIdentifier(); } function parseYieldExpression() { - var node = createNode(201 /* YieldExpression */); + var node = createNode(205 /* YieldExpression */); // YieldExpression[In] : // yield // yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield] @@ -16302,13 +17542,13 @@ var ts; ts.Debug.assert(token() === 36 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); var node; if (asyncModifier) { - node = createNode(191 /* ArrowFunction */, asyncModifier.pos); + node = createNode(195 /* ArrowFunction */, asyncModifier.pos); node.modifiers = asyncModifier; } else { - node = createNode(191 /* ArrowFunction */, identifier.pos); + node = createNode(195 /* ArrowFunction */, identifier.pos); } - var parameter = createNode(148 /* Parameter */, identifier.pos); + var parameter = createNode(149 /* Parameter */, identifier.pos); parameter.name = identifier; finishNode(parameter); node.parameters = createNodeArray([parameter], parameter.pos, parameter.end); @@ -16490,7 +17730,7 @@ var ts; // 2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In] if (token() === 120 /* AsyncKeyword */) { nextToken(); - // If the "async" is followed by "=>" token then it is not a begining of an async arrow-function + // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" if (scanner.hasPrecedingLineBreak() || token() === 36 /* EqualsGreaterThanToken */) { return 0 /* False */; @@ -16504,7 +17744,7 @@ var ts; return 0 /* False */; } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { - var node = createNodeWithJSDoc(191 /* ArrowFunction */); + var node = createNodeWithJSDoc(195 /* ArrowFunction */); node.modifiers = parseModifiersForArrowFunction(); var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; // Arrow functions are never generators. @@ -16514,9 +17754,7 @@ var ts; // a => (b => c) // And think that "(b =>" was actually a parenthesized arrow function with a missing // close paren. - fillSignature(56 /* ColonToken */, isAsync | (allowAmbiguity ? 0 /* None */ : 8 /* RequireCompleteParameterList */), node); - // If we couldn't get parameters, we definitely could not parse out an arrow function. - if (!node.parameters) { + if (!fillSignature(56 /* ColonToken */, isAsync, node) && !allowAmbiguity) { return undefined; } // Parsing a signature isn't enough. @@ -16570,7 +17808,7 @@ var ts; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - var node = createNode(199 /* ConditionalExpression */, leftOperand.pos); + var node = createNode(203 /* ConditionalExpression */, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -16585,14 +17823,14 @@ var ts; return parseBinaryExpressionRest(precedence, leftOperand); } function isInOrOfKeyword(t) { - return t === 92 /* InKeyword */ || t === 144 /* OfKeyword */; + return t === 92 /* InKeyword */ || t === 145 /* OfKeyword */; } function parseBinaryExpressionRest(precedence, leftOperand) { while (true) { // We either have a binary operator here, or we're finished. We call // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - var newPrecedence = getBinaryOperatorPrecedence(); + var newPrecedence = ts.getBinaryOperatorPrecedence(token()); // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, // recursively call the function below, and parse binaryExpression as a rightOperand @@ -16647,85 +17885,42 @@ var ts; if (inDisallowInContext() && token() === 92 /* InKeyword */) { return false; } - return getBinaryOperatorPrecedence() > 0; - } - function getBinaryOperatorPrecedence() { - switch (token()) { - case 54 /* BarBarToken */: - return 1; - case 53 /* AmpersandAmpersandToken */: - return 2; - case 49 /* BarToken */: - return 3; - case 50 /* CaretToken */: - return 4; - case 48 /* AmpersandToken */: - return 5; - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return 6; - case 27 /* LessThanToken */: - case 29 /* GreaterThanToken */: - case 30 /* LessThanEqualsToken */: - case 31 /* GreaterThanEqualsToken */: - case 93 /* InstanceOfKeyword */: - case 92 /* InKeyword */: - case 118 /* AsKeyword */: - return 7; - case 45 /* LessThanLessThanToken */: - case 46 /* GreaterThanGreaterThanToken */: - case 47 /* GreaterThanGreaterThanGreaterThanToken */: - return 8; - case 37 /* PlusToken */: - case 38 /* MinusToken */: - return 9; - case 39 /* AsteriskToken */: - case 41 /* SlashToken */: - case 42 /* PercentToken */: - return 10; - case 40 /* AsteriskAsteriskToken */: - return 11; - } - // -1 is lower than all other precedences. Returning it will cause binary expression - // parsing to stop. - return -1; + return ts.getBinaryOperatorPrecedence(token()) > 0; } function makeBinaryExpression(left, operatorToken, right) { - var node = createNode(198 /* BinaryExpression */, left.pos); + var node = createNode(202 /* BinaryExpression */, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; return finishNode(node); } function makeAsExpression(left, right) { - var node = createNode(206 /* AsExpression */, left.pos); + var node = createNode(210 /* AsExpression */, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - var node = createNode(196 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseSimpleUnaryExpression(); return finishNode(node); } function parseDeleteExpression() { - var node = createNode(192 /* DeleteExpression */); + var node = createNode(196 /* DeleteExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - var node = createNode(193 /* TypeOfExpression */); + var node = createNode(197 /* TypeOfExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - var node = createNode(194 /* VoidExpression */); + var node = createNode(198 /* VoidExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -16741,7 +17936,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(195 /* AwaitExpression */); + var node = createNode(199 /* AwaitExpression */); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -16766,7 +17961,7 @@ var ts; if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); return token() === 40 /* AsteriskAsteriskToken */ ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(), updateExpression) : + parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } /** @@ -16783,12 +17978,13 @@ var ts; var unaryOperator = token(); var simpleUnaryExpression = parseSimpleUnaryExpression(); if (token() === 40 /* AsteriskAsteriskToken */) { - var start = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); - if (simpleUnaryExpression.kind === 188 /* TypeAssertionExpression */) { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos); + var end = simpleUnaryExpression.end; + if (simpleUnaryExpression.kind === 192 /* TypeAssertionExpression */) { + parseErrorAt(pos, end, ts.Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } else { - parseErrorAtPosition(start, simpleUnaryExpression.end - start, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); + parseErrorAt(pos, end, ts.Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, ts.tokenToString(unaryOperator)); } } return simpleUnaryExpression; @@ -16881,7 +18077,7 @@ var ts; */ function parseUpdateExpression() { if (token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) { - var node = createNode(196 /* PrefixUnaryExpression */); + var node = createNode(200 /* PrefixUnaryExpression */); node.operator = token(); nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -16894,7 +18090,7 @@ var ts; var expression = parseLeftHandSideExpressionOrHigher(); ts.Debug.assert(ts.isLeftHandSideExpression(expression)); if ((token() === 43 /* PlusPlusToken */ || token() === 44 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) { - var node = createNode(197 /* PostfixUnaryExpression */, expression.pos); + var node = createNode(201 /* PostfixUnaryExpression */, expression.pos); node.operand = expression; node.operator = token(); nextToken(); @@ -16935,14 +18131,30 @@ var ts; // 3)we have a MemberExpression which either completes the LeftHandSideExpression, // or starts the beginning of the first four CallExpression productions. var expression; - if (token() === 91 /* ImportKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) { - // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" - // For example: - // var foo3 = require("subfolder - // import * as foo1 from "module-from-node - // We want this import to be a statement rather than import call expression - sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; - expression = parseTokenNode(); + if (token() === 91 /* ImportKeyword */) { + if (lookAhead(nextTokenIsOpenParenOrLessThan)) { + // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "(" + // For example: + // var foo3 = require("subfolder + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression + sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; + expression = parseTokenNode(); + } + else if (lookAhead(nextTokenIsDot)) { + // This is an 'import.*' metaproperty (i.e. 'import.meta') + var fullStart = scanner.getStartPos(); + nextToken(); // advance past the 'import' + nextToken(); // advance past the dot + var node = createNode(212 /* MetaProperty */, fullStart); + node.keywordToken = 91 /* ImportKeyword */; + node.name = parseIdentifierName(); + expression = finishNode(node); + sourceFile.flags |= 1048576 /* PossiblyContainsImportMeta */; + } + else { + expression = parseMemberExpressionOrHigher(); + } } else { expression = token() === 97 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher(); @@ -17009,50 +18221,34 @@ var ts; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - var node = createNode(183 /* PropertyAccessExpression */, expression.pos); + var node = createNode(187 /* PropertyAccessExpression */, expression.pos); node.expression = expression; parseExpectedToken(23 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); return finishNode(node); } - function tagNamesAreEquivalent(lhs, rhs) { - if (lhs.kind !== rhs.kind) { - return false; - } - if (lhs.kind === 71 /* Identifier */) { - return lhs.escapedText === rhs.escapedText; - } - if (lhs.kind === 99 /* ThisKeyword */) { - return true; - } - // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only - // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression - // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return lhs.name.escapedText === rhs.name.escapedText && - tagNamesAreEquivalent(lhs.expression, rhs.expression); - } function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) { var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); var result; - if (opening.kind === 255 /* JsxOpeningElement */) { - var node = createNode(253 /* JsxElement */, opening.pos); + if (opening.kind === 260 /* JsxOpeningElement */) { + var node = createNode(258 /* JsxElement */, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement); node.closingElement = parseJsxClosingElement(inExpressionContext); if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) { - parseErrorAtPosition(node.closingElement.pos, node.closingElement.end - node.closingElement.pos, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); + parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName)); } result = finishNode(node); } - else if (opening.kind === 258 /* JsxOpeningFragment */) { - var node = createNode(257 /* JsxFragment */, opening.pos); + else if (opening.kind === 263 /* JsxOpeningFragment */) { + var node = createNode(262 /* JsxFragment */, opening.pos); node.openingFragment = opening; node.children = parseJsxChildren(node.openingFragment); node.closingFragment = parseJsxClosingFragment(inExpressionContext); result = finishNode(node); } else { - ts.Debug.assert(opening.kind === 254 /* JsxSelfClosingElement */); + ts.Debug.assert(opening.kind === 259 /* JsxSelfClosingElement */); // Nothing else to do for self-closing elements result = opening; } @@ -17067,11 +18263,11 @@ var ts; var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); }); if (invalidElement) { parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element); - var badNode = createNode(198 /* BinaryExpression */, result.pos); + var badNode = createNode(202 /* BinaryExpression */, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; - badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); + badNode.operatorToken = createMissingNode(26 /* CommaToken */, /*reportAtCurrentPosition*/ false, /*diagnosticMessage*/ undefined); // TODO: GH#18217 badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos; return badNode; } @@ -17084,8 +18280,21 @@ var ts; currentToken = scanner.scanJsxToken(); return finishNode(node); } - function parseJsxChild() { - switch (token()) { + function parseJsxChild(openingTag, token) { + switch (token) { + case 1 /* EndOfFileToken */: + // If we hit EOF, issue the error at the tag that lacks the closing element + // rather than at the end of the file (which is useless) + if (ts.isJsxOpeningFragment(openingTag)) { + parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + } + else { + parseErrorAtRange(openingTag.tagName, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + } + return undefined; + case 28 /* LessThanSlashToken */: + case 7 /* ConflictMarkerTrivia */: + return undefined; case 10 /* JsxText */: case 11 /* JsxTextAllWhiteSpaces */: return parseJsxText(); @@ -17093,8 +18302,9 @@ var ts; return parseJsxExpression(/*inExpressionContext*/ false); case 27 /* LessThanToken */: return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false); + default: + return ts.Debug.assertNever(token); } - ts.Debug.fail("Unknown JSX child kind " + token()); } function parseJsxChildren(openingTag) { var list = []; @@ -17102,36 +18312,16 @@ var ts; var saveParsingContext = parsingContext; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { - currentToken = scanner.reScanJsxToken(); - if (token() === 28 /* LessThanSlashToken */) { - // Closing tag + var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + if (!child) break; - } - else if (token() === 1 /* EndOfFileToken */) { - // If we hit EOF, issue the error at the tag that lacks the closing element - // rather than at the end of the file (which is useless) - if (ts.isJsxOpeningFragment(openingTag)) { - parseErrorAtPosition(openingTag.pos, openingTag.end - openingTag.pos, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); - } - else { - var openingTagName = openingTag.tagName; - parseErrorAtPosition(openingTagName.pos, openingTagName.end - openingTagName.pos, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTagName)); - } - break; - } - else if (token() === 7 /* ConflictMarkerTrivia */) { - break; - } - var child = parseJsxChild(); - if (child) { - list.push(child); - } + list.push(child); } parsingContext = saveParsingContext; return createNodeArray(list, listPos); } function parseJsxAttributes() { - var jsxAttributes = createNode(261 /* JsxAttributes */); + var jsxAttributes = createNode(266 /* JsxAttributes */); jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute); return finishNode(jsxAttributes); } @@ -17140,18 +18330,19 @@ var ts; parseExpected(27 /* LessThanToken */); if (token() === 29 /* GreaterThanToken */) { // See below for explanation of scanJsxText - var node_1 = createNode(258 /* JsxOpeningFragment */, fullStart); + var node_1 = createNode(263 /* JsxOpeningFragment */, fullStart); scanJsxText(); return finishNode(node_1); } var tagName = parseJsxElementName(); + var typeArguments = tryParseTypeArguments(); var attributes = parseJsxAttributes(); var node; if (token() === 29 /* GreaterThanToken */) { // Closing tag, so scan the immediately-following text with the JSX scanning instead // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors - node = createNode(255 /* JsxOpeningElement */, fullStart); + node = createNode(260 /* JsxOpeningElement */, fullStart); scanJsxText(); } else { @@ -17163,9 +18354,10 @@ var ts; parseExpected(29 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false); scanJsxText(); } - node = createNode(254 /* JsxSelfClosingElement */, fullStart); + node = createNode(259 /* JsxSelfClosingElement */, fullStart); } node.tagName = tagName; + node.typeArguments = typeArguments; node.attributes = attributes; return finishNode(node); } @@ -17179,7 +18371,7 @@ var ts; var expression = token() === 99 /* ThisKeyword */ ? parseTokenNode() : parseIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var propertyAccess = createNode(183 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -17187,7 +18379,7 @@ var ts; return expression; } function parseJsxExpression(inExpressionContext) { - var node = createNode(263 /* JsxExpression */); + var node = createNode(268 /* JsxExpression */); if (!parseExpected(17 /* OpenBraceToken */)) { return undefined; } @@ -17209,7 +18401,7 @@ var ts; return parseJsxSpreadAttribute(); } scanJsxIdentifier(); - var node = createNode(260 /* JsxAttribute */); + var node = createNode(265 /* JsxAttribute */); node.name = parseIdentifierName(); if (token() === 58 /* EqualsToken */) { switch (scanJsxAttributeValue()) { @@ -17224,7 +18416,7 @@ var ts; return finishNode(node); } function parseJsxSpreadAttribute() { - var node = createNode(262 /* JsxSpreadAttribute */); + var node = createNode(267 /* JsxSpreadAttribute */); parseExpected(17 /* OpenBraceToken */); parseExpected(24 /* DotDotDotToken */); node.expression = parseExpression(); @@ -17232,7 +18424,7 @@ var ts; return finishNode(node); } function parseJsxClosingElement(inExpressionContext) { - var node = createNode(256 /* JsxClosingElement */); + var node = createNode(261 /* JsxClosingElement */); parseExpected(28 /* LessThanSlashToken */); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -17245,11 +18437,10 @@ var ts; return finishNode(node); } function parseJsxClosingFragment(inExpressionContext) { - var node = createNode(259 /* JsxClosingFragment */); + var node = createNode(264 /* JsxClosingFragment */); parseExpected(28 /* LessThanSlashToken */); if (ts.tokenIsIdentifierOrKeyword(token())) { - var unexpectedTagName = parseJsxElementName(); - parseErrorAtPosition(unexpectedTagName.pos, unexpectedTagName.end - unexpectedTagName.pos, ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); + parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment); } if (inExpressionContext) { parseExpected(29 /* GreaterThanToken */); @@ -17261,7 +18452,7 @@ var ts; return finishNode(node); } function parseTypeAssertion() { - var node = createNode(188 /* TypeAssertionExpression */); + var node = createNode(192 /* TypeAssertionExpression */); parseExpected(27 /* LessThanToken */); node.type = parseType(); parseExpected(29 /* GreaterThanToken */); @@ -17272,7 +18463,7 @@ var ts; while (true) { var dotToken = parseOptionalToken(23 /* DotToken */); if (dotToken) { - var propertyAccess = createNode(183 /* PropertyAccessExpression */, expression.pos); + var propertyAccess = createNode(187 /* PropertyAccessExpression */, expression.pos); propertyAccess.expression = expression; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); expression = finishNode(propertyAccess); @@ -17280,40 +18471,48 @@ var ts; } if (token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { nextToken(); - var nonNullExpression = createNode(207 /* NonNullExpression */, expression.pos); + var nonNullExpression = createNode(211 /* NonNullExpression */, expression.pos); nonNullExpression.expression = expression; expression = finishNode(nonNullExpression); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(21 /* OpenBracketToken */)) { - var indexedAccess = createNode(184 /* ElementAccessExpression */, expression.pos); + var indexedAccess = createNode(188 /* ElementAccessExpression */, expression.pos); indexedAccess.expression = expression; - // It's not uncommon for a user to write: "new Type[]". - // Check for that common pattern and report a better error message. - if (token() !== 22 /* CloseBracketToken */) { - indexedAccess.argumentExpression = allowInAnd(parseExpression); - if (indexedAccess.argumentExpression.kind === 9 /* StringLiteral */ || indexedAccess.argumentExpression.kind === 8 /* NumericLiteral */) { - var literal = indexedAccess.argumentExpression; - literal.text = internIdentifier(literal.text); + if (token() === 22 /* CloseBracketToken */) { + indexedAccess.argumentExpression = createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument); + } + else { + var argument = allowInAnd(parseExpression); + if (ts.isStringOrNumericLiteral(argument)) { + argument.text = internIdentifier(argument.text); } + indexedAccess.argumentExpression = argument; } parseExpected(22 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } - if (token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */) { - var tagExpression = createNode(187 /* TaggedTemplateExpression */, expression.pos); - tagExpression.tag = expression; - tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ - ? parseLiteralNode() - : parseTemplateExpression(); - expression = finishNode(tagExpression); + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, /*typeArguments*/ undefined); continue; } return expression; } } + function isTemplateStartOfTaggedTemplate() { + return token() === 13 /* NoSubstitutionTemplateLiteral */ || token() === 14 /* TemplateHead */; + } + function parseTaggedTemplateRest(tag, typeArguments) { + var tagExpression = createNode(191 /* TaggedTemplateExpression */, tag.pos); + tagExpression.tag = tag; + tagExpression.typeArguments = typeArguments; + tagExpression.template = token() === 13 /* NoSubstitutionTemplateLiteral */ + ? parseLiteralNode() + : parseTemplateExpression(); + return finishNode(tagExpression); + } function parseCallExpressionRest(expression) { while (true) { expression = parseMemberExpressionRest(expression); @@ -17326,7 +18525,11 @@ var ts; if (!typeArguments) { return expression; } - var callExpr = createNode(185 /* CallExpression */, expression.pos); + if (isTemplateStartOfTaggedTemplate()) { + expression = parseTaggedTemplateRest(expression, typeArguments); + continue; + } + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -17334,7 +18537,7 @@ var ts; continue; } else if (token() === 19 /* OpenParenToken */) { - var callExpr = createNode(185 /* CallExpression */, expression.pos); + var callExpr = createNode(189 /* CallExpression */, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -17367,8 +18570,10 @@ var ts; function canFollowTypeArgumentsInExpression() { switch (token()) { case 19 /* OpenParenToken */: // foo( - // this case are the only case where this token can legally follow a type argument - // list. So we definitely want to treat this as a type arg list. + case 13 /* NoSubstitutionTemplateLiteral */: // foo `...` + case 14 /* TemplateHead */: // foo `...${100}...` + // these are the only tokens can legally follow a type argument + // list. So we definitely want to treat them as type arg lists. case 23 /* DotToken */: // foo. case 20 /* CloseParenToken */: // foo) case 22 /* CloseBracketToken */: // foo] @@ -17431,7 +18636,7 @@ var ts; case 89 /* FunctionKeyword */: return parseFunctionExpression(); case 94 /* NewKeyword */: - return parseNewExpression(); + return parseNewExpressionOrNewDotTarget(); case 41 /* SlashToken */: case 63 /* SlashEqualsToken */: if (reScanSlashToken() === 12 /* RegularExpressionLiteral */) { @@ -17444,28 +18649,28 @@ var ts; return parseIdentifier(ts.Diagnostics.Expression_expected); } function parseParenthesizedExpression() { - var node = createNodeWithJSDoc(189 /* ParenthesizedExpression */); + var node = createNodeWithJSDoc(193 /* ParenthesizedExpression */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); return finishNode(node); } function parseSpreadElement() { - var node = createNode(202 /* SpreadElement */); + var node = createNode(206 /* SpreadElement */); parseExpected(24 /* DotDotDotToken */); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } function parseArgumentOrArrayLiteralElement() { return token() === 24 /* DotDotDotToken */ ? parseSpreadElement() : - token() === 26 /* CommaToken */ ? createNode(204 /* OmittedExpression */) : + token() === 26 /* CommaToken */ ? createNode(208 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); } function parseArgumentExpression() { return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); } function parseArrayLiteralExpression() { - var node = createNode(181 /* ArrayLiteralExpression */); + var node = createNode(185 /* ArrayLiteralExpression */); parseExpected(21 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17477,17 +18682,17 @@ var ts; function parseObjectLiteralElement() { var node = createNodeWithJSDoc(0 /* Unknown */); if (parseOptionalToken(24 /* DotDotDotToken */)) { - node.kind = 270 /* SpreadAssignment */; + node.kind = 275 /* SpreadAssignment */; node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); } node.decorators = parseDecorators(); node.modifiers = parseModifiers(); if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 155 /* GetAccessor */); + return parseAccessorDeclaration(node, 156 /* GetAccessor */); } if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* SetAccessor */); + return parseAccessorDeclaration(node, 157 /* SetAccessor */); } var asteriskToken = parseOptionalToken(39 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); @@ -17504,7 +18709,7 @@ var ts; // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern var isShorthandPropertyAssignment = tokenIsIdentifier && (token() === 26 /* CommaToken */ || token() === 18 /* CloseBraceToken */ || token() === 58 /* EqualsToken */); if (isShorthandPropertyAssignment) { - node.kind = 269 /* ShorthandPropertyAssignment */; + node.kind = 274 /* ShorthandPropertyAssignment */; var equalsToken = parseOptionalToken(58 /* EqualsToken */); if (equalsToken) { node.equalsToken = equalsToken; @@ -17512,14 +18717,14 @@ var ts; } } else { - node.kind = 268 /* PropertyAssignment */; + node.kind = 273 /* PropertyAssignment */; parseExpected(56 /* ColonToken */); node.initializer = allowInAnd(parseAssignmentExpressionOrHigher); } return finishNode(node); } function parseObjectLiteralExpression() { - var node = createNode(182 /* ObjectLiteralExpression */); + var node = createNode(186 /* ObjectLiteralExpression */); parseExpected(17 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17538,7 +18743,7 @@ var ts; if (saveDecoratorContext) { setDecoratorContext(/*val*/ false); } - var node = createNodeWithJSDoc(190 /* FunctionExpression */); + var node = createNodeWithJSDoc(194 /* FunctionExpression */); node.modifiers = parseModifiers(); parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); @@ -17559,18 +18764,30 @@ var ts; function parseOptionalIdentifier() { return isIdentifier() ? parseIdentifier() : undefined; } - function parseNewExpression() { + function parseNewExpressionOrNewDotTarget() { var fullStart = scanner.getStartPos(); parseExpected(94 /* NewKeyword */); if (parseOptional(23 /* DotToken */)) { - var node_2 = createNode(208 /* MetaProperty */, fullStart); + var node_2 = createNode(212 /* MetaProperty */, fullStart); node_2.keywordToken = 94 /* NewKeyword */; node_2.name = parseIdentifierName(); return finishNode(node_2); } - var node = createNode(186 /* NewExpression */, fullStart); - node.expression = parseMemberExpressionOrHigher(); - node.typeArguments = tryParse(parseTypeArgumentsInExpression); + var expression = parsePrimaryExpression(); + var typeArguments; + while (true) { + expression = parseMemberExpressionRest(expression); + typeArguments = tryParse(parseTypeArgumentsInExpression); + if (isTemplateStartOfTaggedTemplate()) { + ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'"); + expression = parseTaggedTemplateRest(expression, typeArguments); + typeArguments = undefined; + } + break; + } + var node = createNode(190 /* NewExpression */, fullStart); + node.expression = expression; + node.typeArguments = typeArguments; if (node.typeArguments || token() === 19 /* OpenParenToken */) { node.arguments = parseArgumentList(); } @@ -17578,7 +18795,7 @@ var ts; } // STATEMENTS function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) { - var node = createNode(211 /* Block */); + var node = createNode(216 /* Block */); if (parseExpected(17 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { if (scanner.hasPrecedingLineBreak()) { node.multiLine = true; @@ -17611,12 +18828,12 @@ var ts; return block; } function parseEmptyStatement() { - var node = createNode(213 /* EmptyStatement */); + var node = createNode(218 /* EmptyStatement */); parseExpected(25 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(215 /* IfStatement */); + var node = createNode(220 /* IfStatement */); parseExpected(90 /* IfKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -17626,7 +18843,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(216 /* DoStatement */); + var node = createNode(221 /* DoStatement */); parseExpected(81 /* DoKeyword */); node.statement = parseStatement(); parseExpected(106 /* WhileKeyword */); @@ -17641,7 +18858,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(217 /* WhileStatement */); + var node = createNode(222 /* WhileStatement */); parseExpected(106 /* WhileKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -17664,8 +18881,8 @@ var ts; } } var forOrForInOrForOfStatement; - if (awaitToken ? parseExpected(144 /* OfKeyword */) : parseOptional(144 /* OfKeyword */)) { - var forOfStatement = createNode(220 /* ForOfStatement */, pos); + if (awaitToken ? parseExpected(145 /* OfKeyword */) : parseOptional(145 /* OfKeyword */)) { + var forOfStatement = createNode(225 /* ForOfStatement */, pos); forOfStatement.awaitModifier = awaitToken; forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); @@ -17673,14 +18890,14 @@ var ts; forOrForInOrForOfStatement = forOfStatement; } else if (parseOptional(92 /* InKeyword */)) { - var forInStatement = createNode(219 /* ForInStatement */, pos); + var forInStatement = createNode(224 /* ForInStatement */, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); forOrForInOrForOfStatement = forInStatement; } else { - var forStatement = createNode(218 /* ForStatement */, pos); + var forStatement = createNode(223 /* ForStatement */, pos); forStatement.initializer = initializer; parseExpected(25 /* SemicolonToken */); if (token() !== 25 /* SemicolonToken */ && token() !== 20 /* CloseParenToken */) { @@ -17698,7 +18915,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 222 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); + parseExpected(kind === 227 /* BreakStatement */ ? 72 /* BreakKeyword */ : 77 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -17706,7 +18923,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(223 /* ReturnStatement */); + var node = createNode(228 /* ReturnStatement */); parseExpected(96 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -17715,16 +18932,16 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(224 /* WithStatement */); + var node = createNode(229 /* WithStatement */); parseExpected(107 /* WithKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - node.statement = doInsideOfContext(4194304 /* InWithStatement */, parseStatement); + node.statement = doInsideOfContext(8388608 /* InWithStatement */, parseStatement); return finishNode(node); } function parseCaseClause() { - var node = createNode(264 /* CaseClause */); + var node = createNode(269 /* CaseClause */); parseExpected(73 /* CaseKeyword */); node.expression = allowInAnd(parseExpression); parseExpected(56 /* ColonToken */); @@ -17732,7 +18949,7 @@ var ts; return finishNode(node); } function parseDefaultClause() { - var node = createNode(265 /* DefaultClause */); + var node = createNode(270 /* DefaultClause */); parseExpected(79 /* DefaultKeyword */); parseExpected(56 /* ColonToken */); node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement); @@ -17742,12 +18959,12 @@ var ts; return token() === 73 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(225 /* SwitchStatement */); + var node = createNode(230 /* SwitchStatement */); parseExpected(98 /* SwitchKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); parseExpected(20 /* CloseParenToken */); - var caseBlock = createNode(239 /* CaseBlock */); + var caseBlock = createNode(244 /* CaseBlock */); parseExpected(17 /* OpenBraceToken */); caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause); parseExpected(18 /* CloseBraceToken */); @@ -17762,7 +18979,7 @@ var ts; // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - var node = createNode(227 /* ThrowStatement */); + var node = createNode(232 /* ThrowStatement */); parseExpected(100 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -17770,7 +18987,7 @@ var ts; } // TODO: Review for error recovery function parseTryStatement() { - var node = createNode(228 /* TryStatement */); + var node = createNode(233 /* TryStatement */); parseExpected(102 /* TryKeyword */); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); node.catchClause = token() === 74 /* CatchKeyword */ ? parseCatchClause() : undefined; @@ -17783,7 +19000,7 @@ var ts; return finishNode(node); } function parseCatchClause() { - var result = createNode(267 /* CatchClause */); + var result = createNode(272 /* CatchClause */); parseExpected(74 /* CatchKeyword */); if (parseOptional(19 /* OpenParenToken */)) { result.variableDeclaration = parseVariableDeclaration(); @@ -17797,7 +19014,7 @@ var ts; return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(229 /* DebuggerStatement */); + var node = createNode(234 /* DebuggerStatement */); parseExpected(78 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -17809,12 +19026,12 @@ var ts; var node = createNodeWithJSDoc(0 /* Unknown */); var expression = allowInAnd(parseExpression); if (expression.kind === 71 /* Identifier */ && parseOptional(56 /* ColonToken */)) { - node.kind = 226 /* LabeledStatement */; + node.kind = 231 /* LabeledStatement */; node.label = expression; node.statement = parseStatement(); } else { - node.kind = 214 /* ExpressionStatement */; + node.kind = 219 /* ExpressionStatement */; node.expression = expression; parseSemicolon(); } @@ -17886,7 +19103,7 @@ var ts; return false; } continue; - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: nextToken(); return token() === 17 /* OpenBraceToken */ || token() === 71 /* Identifier */ || token() === 84 /* ExportKeyword */; case 91 /* ImportKeyword */: @@ -17940,7 +19157,7 @@ var ts; case 87 /* FinallyKeyword */: return true; case 91 /* ImportKeyword */: - return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThan); + return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); case 76 /* ConstKeyword */: case 84 /* ExportKeyword */: return isStartOfDeclaration(); @@ -17950,7 +19167,7 @@ var ts; case 129 /* ModuleKeyword */: case 130 /* NamespaceKeyword */: case 139 /* TypeKeyword */: - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: // When these don't start a declaration, they're an identifier in an expression statement return true; case 114 /* PublicKeyword */: @@ -17981,16 +19198,16 @@ var ts; case 17 /* OpenBraceToken */: return parseBlock(/*ignoreMissingOpenBrace*/ false); case 104 /* VarKeyword */: - return parseVariableStatement(createNodeWithJSDoc(230 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); case 110 /* LetKeyword */: if (isLetDeclaration()) { - return parseVariableStatement(createNodeWithJSDoc(230 /* VariableDeclaration */)); + return parseVariableStatement(createNodeWithJSDoc(235 /* VariableDeclaration */)); } break; case 89 /* FunctionKeyword */: - return parseFunctionDeclaration(createNodeWithJSDoc(232 /* FunctionDeclaration */)); + return parseFunctionDeclaration(createNodeWithJSDoc(237 /* FunctionDeclaration */)); case 75 /* ClassKeyword */: - return parseClassDeclaration(createNodeWithJSDoc(233 /* ClassDeclaration */)); + return parseClassDeclaration(createNodeWithJSDoc(238 /* ClassDeclaration */)); case 90 /* IfKeyword */: return parseIfStatement(); case 81 /* DoKeyword */: @@ -18000,9 +19217,9 @@ var ts; case 88 /* ForKeyword */: return parseForOrForInOrForOfStatement(); case 77 /* ContinueKeyword */: - return parseBreakOrContinueStatement(221 /* ContinueStatement */); + return parseBreakOrContinueStatement(226 /* ContinueStatement */); case 72 /* BreakKeyword */: - return parseBreakOrContinueStatement(222 /* BreakStatement */); + return parseBreakOrContinueStatement(227 /* BreakStatement */); case 96 /* ReturnKeyword */: return parseReturnStatement(); case 107 /* WithKeyword */: @@ -18036,7 +19253,7 @@ var ts; case 117 /* AbstractKeyword */: case 115 /* StaticKeyword */: case 132 /* ReadonlyKeyword */: - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: if (isStartOfDeclaration()) { return parseDeclaration(); } @@ -18054,9 +19271,9 @@ var ts; if (ts.some(node.modifiers, isDeclareModifier)) { for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var m = _a[_i]; - m.flags |= 2097152 /* Ambient */; + m.flags |= 4194304 /* Ambient */; } - return doInsideOfContext(2097152 /* Ambient */, function () { return parseDeclarationWorker(node); }); + return doInsideOfContext(4194304 /* Ambient */, function () { return parseDeclarationWorker(node); }); } else { return parseDeclarationWorker(node); @@ -18078,7 +19295,7 @@ var ts; return parseTypeAliasDeclaration(node); case 83 /* EnumKeyword */: return parseEnumDeclaration(node); - case 143 /* GlobalKeyword */: + case 144 /* GlobalKeyword */: case 129 /* ModuleKeyword */: case 130 /* NamespaceKeyword */: return parseModuleDeclaration(node); @@ -18099,12 +19316,13 @@ var ts; if (node.decorators || node.modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - var missing = createMissingNode(251 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); + var missing = createMissingNode(256 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected); missing.pos = node.pos; missing.decorators = node.decorators; missing.modifiers = node.modifiers; return finishNode(missing); } + return undefined; // TODO: GH#18217 } } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { @@ -18121,16 +19339,16 @@ var ts; // DECLARATIONS function parseArrayBindingElement() { if (token() === 26 /* CommaToken */) { - return createNode(204 /* OmittedExpression */); + return createNode(208 /* OmittedExpression */); } - var node = createNode(180 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(); return finishNode(node); } function parseObjectBindingElement() { - var node = createNode(180 /* BindingElement */); + var node = createNode(184 /* BindingElement */); node.dotDotDotToken = parseOptionalToken(24 /* DotDotDotToken */); var tokenIsIdentifier = isIdentifier(); var propertyName = parsePropertyName(); @@ -18146,14 +19364,14 @@ var ts; return finishNode(node); } function parseObjectBindingPattern() { - var node = createNode(178 /* ObjectBindingPattern */); + var node = createNode(182 /* ObjectBindingPattern */); parseExpected(17 /* OpenBraceToken */); node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement); parseExpected(18 /* CloseBraceToken */); return finishNode(node); } function parseArrayBindingPattern() { - var node = createNode(179 /* ArrayBindingPattern */); + var node = createNode(183 /* ArrayBindingPattern */); parseExpected(21 /* OpenBracketToken */); node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement); parseExpected(22 /* CloseBracketToken */); @@ -18175,7 +19393,7 @@ var ts; return parseVariableDeclaration(/*allowExclamation*/ true); } function parseVariableDeclaration(allowExclamation) { - var node = createNode(230 /* VariableDeclaration */); + var node = createNode(235 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); if (allowExclamation && node.name.kind === 71 /* Identifier */ && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { @@ -18188,7 +19406,7 @@ var ts; return finishNode(node); } function parseVariableDeclarationList(inForStatementInitializer) { - var node = createNode(231 /* VariableDeclarationList */); + var node = createNode(236 /* VariableDeclarationList */); switch (token()) { case 104 /* VarKeyword */: break; @@ -18211,7 +19429,7 @@ var ts; // So we need to look ahead to determine if 'of' should be treated as a keyword in // this context. // The checker will then give an error that there is an empty declaration list. - if (token() === 144 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { + if (token() === 145 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) { node.declarations = createMissingList(); } else { @@ -18226,13 +19444,13 @@ var ts; return nextTokenIsIdentifier() && nextToken() === 20 /* CloseParenToken */; } function parseVariableStatement(node) { - node.kind = 212 /* VariableStatement */; + node.kind = 217 /* VariableStatement */; node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); parseSemicolon(); return finishNode(node); } function parseFunctionDeclaration(node) { - node.kind = 232 /* FunctionDeclaration */; + node.kind = 237 /* FunctionDeclaration */; parseExpected(89 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(39 /* AsteriskToken */); node.name = ts.hasModifier(node, 512 /* Default */) ? parseOptionalIdentifier() : parseIdentifier(); @@ -18243,14 +19461,14 @@ var ts; return finishNode(node); } function parseConstructorDeclaration(node) { - node.kind = 154 /* Constructor */; + node.kind = 155 /* Constructor */; parseExpected(123 /* ConstructorKeyword */); fillSignature(56 /* ColonToken */, 0 /* None */, node); node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected); return finishNode(node); } function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) { - node.kind = 153 /* MethodDeclaration */; + node.kind = 154 /* MethodDeclaration */; node.asteriskToken = asteriskToken; var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; var isAsync = ts.hasModifier(node, 256 /* Async */) ? 2 /* Await */ : 0 /* None */; @@ -18259,7 +19477,7 @@ var ts; return finishNode(node); } function parsePropertyDeclaration(node) { - node.kind = 151 /* PropertyDeclaration */; + node.kind = 152 /* PropertyDeclaration */; if (!node.questionToken && token() === 51 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) { node.exclamationToken = parseTokenNode(); } @@ -18297,18 +19515,6 @@ var ts; node.body = parseFunctionBlockOrSemicolon(0 /* None */); return finishNode(node); } - function isClassMemberModifier(idToken) { - switch (idToken) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 115 /* StaticKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function isClassMemberStart() { var idToken; if (token() === 57 /* AtToken */) { @@ -18323,7 +19529,7 @@ var ts; // public foo() ... // true // public @dec blah ... // true; we will then report an error later // export public ... // true; we will then report an error later - if (isClassMemberModifier(idToken)) { + if (ts.isClassMemberModifier(idToken)) { return true; } nextToken(); @@ -18376,7 +19582,7 @@ var ts; if (!parseOptional(57 /* AtToken */)) { break; } - var decorator = createNode(149 /* Decorator */, decoratorStart); + var decorator = createNode(150 /* Decorator */, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); finishNode(decorator); (list || (list = [])).push(decorator); @@ -18426,7 +19632,7 @@ var ts; } function parseClassElement() { if (token() === 25 /* SemicolonToken */) { - var result = createNode(210 /* SemicolonClassElement */); + var result = createNode(215 /* SemicolonClassElement */); nextToken(); return finishNode(result); } @@ -18434,10 +19640,10 @@ var ts; node.decorators = parseDecorators(); node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true); if (parseContextualModifier(125 /* GetKeyword */)) { - return parseAccessorDeclaration(node, 155 /* GetAccessor */); + return parseAccessorDeclaration(node, 156 /* GetAccessor */); } if (parseContextualModifier(136 /* SetKeyword */)) { - return parseAccessorDeclaration(node, 156 /* SetAccessor */); + return parseAccessorDeclaration(node, 157 /* SetAccessor */); } if (token() === 123 /* ConstructorKeyword */) { return parseConstructorDeclaration(node); @@ -18460,13 +19666,13 @@ var ts; return parsePropertyDeclaration(node); } // 'isClassMemberStart' should have hinted not to attempt parsing. - ts.Debug.fail("Should not have attempted to parse class member declaration."); + return ts.Debug.fail("Should not have attempted to parse class member declaration."); } function parseClassExpression() { - return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 203 /* ClassExpression */); + return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 207 /* ClassExpression */); } function parseClassDeclaration(node) { - return parseClassDeclarationOrExpression(node, 233 /* ClassDeclaration */); + return parseClassDeclarationOrExpression(node, 238 /* ClassDeclaration */); } function parseClassDeclarationOrExpression(node, kind) { node.kind = kind; @@ -18508,17 +19714,15 @@ var ts; } function parseHeritageClause() { var tok = token(); - if (tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */) { - var node = createNode(266 /* HeritageClause */); - node.token = tok; - nextToken(); - node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); - return finishNode(node); - } - return undefined; + ts.Debug.assert(tok === 85 /* ExtendsKeyword */ || tok === 108 /* ImplementsKeyword */); // isListElement() should ensure this. + var node = createNode(271 /* HeritageClause */); + node.token = tok; + nextToken(); + node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments); + return finishNode(node); } function parseExpressionWithTypeArguments() { - var node = createNode(205 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parseLeftHandSideExpressionOrHigher(); node.typeArguments = tryParseTypeArguments(); return finishNode(node); @@ -18535,7 +19739,7 @@ var ts; return parseList(5 /* ClassMembers */, parseClassElement); } function parseInterfaceDeclaration(node) { - node.kind = 234 /* InterfaceDeclaration */; + node.kind = 239 /* InterfaceDeclaration */; parseExpected(109 /* InterfaceKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -18544,7 +19748,7 @@ var ts; return finishNode(node); } function parseTypeAliasDeclaration(node) { - node.kind = 235 /* TypeAliasDeclaration */; + node.kind = 240 /* TypeAliasDeclaration */; parseExpected(139 /* TypeKeyword */); node.name = parseIdentifier(); node.typeParameters = parseTypeParameters(); @@ -18558,13 +19762,13 @@ var ts; // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember() { - var node = createNodeWithJSDoc(271 /* EnumMember */); + var node = createNodeWithJSDoc(276 /* EnumMember */); node.name = parsePropertyName(); node.initializer = allowInAnd(parseInitializer); return finishNode(node); } function parseEnumDeclaration(node) { - node.kind = 236 /* EnumDeclaration */; + node.kind = 241 /* EnumDeclaration */; parseExpected(83 /* EnumKeyword */); node.name = parseIdentifier(); if (parseExpected(17 /* OpenBraceToken */)) { @@ -18577,7 +19781,7 @@ var ts; return finishNode(node); } function parseModuleBlock() { - var node = createNode(238 /* ModuleBlock */); + var node = createNode(243 /* ModuleBlock */); if (parseExpected(17 /* OpenBraceToken */)) { node.statements = parseList(1 /* BlockStatements */, parseStatement); parseExpected(18 /* CloseBraceToken */); @@ -18588,7 +19792,7 @@ var ts; return finishNode(node); } function parseModuleOrNamespaceDeclaration(node, flags) { - node.kind = 237 /* ModuleDeclaration */; + node.kind = 242 /* ModuleDeclaration */; // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. var namespaceFlag = flags & 16 /* Namespace */; @@ -18600,8 +19804,8 @@ var ts; return finishNode(node); } function parseAmbientExternalModuleDeclaration(node) { - node.kind = 237 /* ModuleDeclaration */; - if (token() === 143 /* GlobalKeyword */) { + node.kind = 242 /* ModuleDeclaration */; + if (token() === 144 /* GlobalKeyword */) { // parse 'global' as name of global scope augmentation node.name = parseIdentifier(); node.flags |= 512 /* GlobalAugmentation */; @@ -18620,7 +19824,7 @@ var ts; } function parseModuleDeclaration(node) { var flags = 0; - if (token() === 143 /* GlobalKeyword */) { + if (token() === 144 /* GlobalKeyword */) { // global augmentation return parseAmbientExternalModuleDeclaration(node); } @@ -18646,7 +19850,7 @@ var ts; return nextToken() === 41 /* SlashToken */; } function parseNamespaceExportDeclaration(node) { - node.kind = 240 /* NamespaceExportDeclaration */; + node.kind = 245 /* NamespaceExportDeclaration */; parseExpected(118 /* AsKeyword */); parseExpected(130 /* NamespaceKeyword */); node.name = parseIdentifier(); @@ -18659,12 +19863,12 @@ var ts; var identifier; if (isIdentifier()) { identifier = parseIdentifier(); - if (token() !== 26 /* CommaToken */ && token() !== 142 /* FromKeyword */) { + if (token() !== 26 /* CommaToken */ && token() !== 143 /* FromKeyword */) { return parseImportEqualsDeclaration(node, identifier); } } // Import statement - node.kind = 242 /* ImportDeclaration */; + node.kind = 247 /* ImportDeclaration */; // ImportDeclaration: // import ImportClause from ModuleSpecifier ; // import ModuleSpecifier; @@ -18672,14 +19876,14 @@ var ts; token() === 39 /* AsteriskToken */ || // import * token() === 17 /* OpenBraceToken */) { // import { node.importClause = parseImportClause(identifier, afterImportPos); - parseExpected(142 /* FromKeyword */); + parseExpected(143 /* FromKeyword */); } node.moduleSpecifier = parseModuleSpecifier(); parseSemicolon(); return finishNode(node); } function parseImportEqualsDeclaration(node, identifier) { - node.kind = 241 /* ImportEqualsDeclaration */; + node.kind = 246 /* ImportEqualsDeclaration */; node.name = identifier; parseExpected(58 /* EqualsToken */); node.moduleReference = parseModuleReference(); @@ -18693,7 +19897,7 @@ var ts; // NamedImports // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - var importClause = createNode(243 /* ImportClause */, fullStart); + var importClause = createNode(248 /* ImportClause */, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -18703,7 +19907,7 @@ var ts; // parse namespace or named imports if (!importClause.name || parseOptional(26 /* CommaToken */)) { - importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(245 /* NamedImports */); + importClause.namedBindings = token() === 39 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(250 /* NamedImports */); } return finishNode(importClause); } @@ -18713,7 +19917,7 @@ var ts; : parseEntityName(/*allowReservedWords*/ false); } function parseExternalModuleReference() { - var node = createNode(252 /* ExternalModuleReference */); + var node = createNode(257 /* ExternalModuleReference */); parseExpected(133 /* RequireKeyword */); parseExpected(19 /* OpenParenToken */); node.expression = parseModuleSpecifier(); @@ -18736,7 +19940,7 @@ var ts; function parseNamespaceImport() { // NameSpaceImport: // * as ImportedBinding - var namespaceImport = createNode(244 /* NamespaceImport */); + var namespaceImport = createNode(249 /* NamespaceImport */); parseExpected(39 /* AsteriskToken */); parseExpected(118 /* AsKeyword */); namespaceImport.name = parseIdentifier(); @@ -18751,14 +19955,14 @@ var ts; // ImportsList: // ImportSpecifier // ImportsList, ImportSpecifier - node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 245 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); + node.elements = parseBracketedList(22 /* ImportOrExportSpecifiers */, kind === 250 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 17 /* OpenBraceToken */, 18 /* CloseBraceToken */); return finishNode(node); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(250 /* ExportSpecifier */); + return parseImportOrExportSpecifier(255 /* ExportSpecifier */); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(246 /* ImportSpecifier */); + return parseImportOrExportSpecifier(251 /* ImportSpecifier */); } function parseImportOrExportSpecifier(kind) { var node = createNode(kind); @@ -18783,25 +19987,24 @@ var ts; else { node.name = identifierName; } - if (kind === 246 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - // Report error identifier expected - parseErrorAtPosition(checkIdentifierStart, checkIdentifierEnd - checkIdentifierStart, ts.Diagnostics.Identifier_expected); + if (kind === 251 /* ImportSpecifier */ && checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected); } return finishNode(node); } function parseExportDeclaration(node) { - node.kind = 248 /* ExportDeclaration */; + node.kind = 253 /* ExportDeclaration */; if (parseOptional(39 /* AsteriskToken */)) { - parseExpected(142 /* FromKeyword */); + parseExpected(143 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } else { - node.exportClause = parseNamedImportsOrExports(249 /* NamedExports */); + node.exportClause = parseNamedImportsOrExports(254 /* NamedExports */); // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === 142 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { - parseExpected(142 /* FromKeyword */); + if (token() === 143 /* FromKeyword */ || (token() === 9 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(143 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -18809,7 +20012,7 @@ var ts; return finishNode(node); } function parseExportAssignment(node) { - node.kind = 247 /* ExportAssignment */; + node.kind = 252 /* ExportAssignment */; if (parseOptional(58 /* EqualsToken */)) { node.isExportEquals = true; } @@ -18821,15 +20024,31 @@ var ts; return finishNode(node); } function setExternalModuleIndicator(sourceFile) { - sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return ts.hasModifier(node, 1 /* Export */) - || node.kind === 241 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 252 /* ExternalModuleReference */ - || node.kind === 242 /* ImportDeclaration */ - || node.kind === 247 /* ExportAssignment */ - || node.kind === 248 /* ExportDeclaration */ - ? node - : undefined; - }); + // Try to use the first top-level import/export when available, then + // fall back to looking for an 'import.meta' somewhere in the tree if necessary. + sourceFile.externalModuleIndicator = + ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) || + getImportMetaIfNecessary(sourceFile); + } + function isAnExternalModuleIndicatorNode(node) { + return ts.hasModifier(node, 1 /* Export */) + || node.kind === 246 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 257 /* ExternalModuleReference */ + || node.kind === 247 /* ImportDeclaration */ + || node.kind === 252 /* ExportAssignment */ + || node.kind === 253 /* ExportDeclaration */ + ? node + : undefined; + } + function getImportMetaIfNecessary(sourceFile) { + return sourceFile.flags & 1048576 /* PossiblyContainsImportMeta */ ? + walkTreeForExternalModuleIndicators(sourceFile) : + undefined; + } + function walkTreeForExternalModuleIndicators(node) { + return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators); + } + function isImportMeta(node) { + return ts.isMetaProperty(node) && node.keywordToken === 91 /* ImportKeyword */ && node.name.escapedText === "meta"; } var ParsingContext; (function (ParsingContext) { @@ -18879,9 +20098,9 @@ var ts; JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests; // Parses out a JSDoc type expression. function parseJSDocTypeExpression(mayOmitBraces) { - var result = createNode(274 /* JSDocTypeExpression */, scanner.getTokenPos()); + var result = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(17 /* OpenBraceToken */); - result.type = doInsideOfContext(1048576 /* JSDoc */, parseType); + result.type = doInsideOfContext(2097152 /* JSDoc */, parseJSDocType); if (!mayOmitBraces || hasBrace) { parseExpected(18 /* CloseBraceToken */); } @@ -18899,6 +20118,7 @@ var ts; } JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment; function parseJSDocComment(parent, start, length) { + var _a; var saveToken = currentToken; var saveParseDiagnosticsLength = parseDiagnostics.length; var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -18916,7 +20136,6 @@ var ts; parseDiagnostics.length = saveParseDiagnosticsLength; parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode; return comment; - var _a; } JSDocParser.parseJSDocComment = parseJSDocComment; var JSDocState; @@ -18927,28 +20146,28 @@ var ts; })(JSDocState || (JSDocState = {})); var PropertyLikeParse; (function (PropertyLikeParse) { - PropertyLikeParse[PropertyLikeParse["Property"] = 0] = "Property"; - PropertyLikeParse[PropertyLikeParse["Parameter"] = 1] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property"; + PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter"; + PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start, length) { + if (start === void 0) { start = 0; } var content = sourceText; - start = start || 0; var end = length === undefined ? content.length : start + length; length = end - start; ts.Debug.assert(start >= 0); ts.Debug.assert(start <= end); ts.Debug.assert(end <= content.length); + // Check for /** (JSDoc opening part) + if (!isJSDocLikeText(content, start)) { + return undefined; + } var tags; var tagsPos; var tagsEnd; var comments = []; - var result; - // Check for /** (JSDoc opening part) - if (!isJsDocStart(content, start)) { - return result; - } // + 3 for leading /**, - 5 in total for /** */ - scanner.scanRange(start + 3, length - 5, function () { + return scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. var state = 1 /* SawAsterisk */; @@ -18962,21 +20181,19 @@ var ts; comments.push(text); indent += text.length; } - var t = nextJSDocToken(); - while (t === 5 /* WhitespaceTrivia */) { - t = nextJSDocToken(); - } - if (t === 4 /* NewLineTrivia */) { + nextJSDocToken(); + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) + ; + if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; indent = 0; - t = nextJSDocToken(); } loop: while (true) { - switch (t) { + switch (token()) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); - parseTag(indent); + addTag(parseTag(indent)); // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag. // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning // for malformed examples like `/** @param {string} x @returns {number} the length */` @@ -19032,13 +20249,12 @@ var ts; pushComment(scanner.getTokenText()); break; } - t = nextJSDocToken(); + nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - result = createJSDocComment(); + return createJSDocComment(); }); - return result; function removeLeadingNewlines(comments) { while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { comments.shift(); @@ -19049,19 +20265,30 @@ var ts; comments.pop(); } } - function isJsDocStart(content, start) { - return content.charCodeAt(start) === 47 /* slash */ && - content.charCodeAt(start + 1) === 42 /* asterisk */ && - content.charCodeAt(start + 2) === 42 /* asterisk */ && - content.charCodeAt(start + 3) !== 42 /* asterisk */; - } function createJSDocComment() { - var result = createNode(282 /* JSDocComment */, start); + var result = createNode(289 /* JSDocComment */, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); result.comment = comments.length ? comments.join("") : undefined; return finishNode(result, end); } + function isNextNonwhitespaceTokenEndOfFile() { + // We must use infinite lookahead, as there could be any number of newlines :( + while (true) { + nextJSDocToken(); + if (token() === 1 /* EndOfFileToken */) { + return true; + } + if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) { + return false; + } + } + } function skipWhitespace() { + if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { + if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { + return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range + } + } while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) { nextJSDocToken(); } @@ -19073,52 +20300,48 @@ var ts; nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); - if (!tagName) { - return; - } var tag; - if (tagName) { - switch (tagName.escapedText) { - case "augments": - case "extends": - tag = parseAugmentsTag(atToken, tagName); - break; - case "class": - case "constructor": - tag = parseClassTag(atToken, tagName); - break; - case "arg": - case "argument": - case "param": - tag = parseParameterOrPropertyTag(atToken, tagName, 1 /* Parameter */); - break; - case "return": - case "returns": - tag = parseReturnTag(atToken, tagName); - break; - case "template": - tag = parseTemplateTag(atToken, tagName); - break; - case "type": - tag = parseTypeTag(atToken, tagName); - break; - case "typedef": - tag = parseTypedefTag(atToken, tagName); - break; - default: - tag = parseUnknownTag(atToken, tagName); - break; - } + switch (tagName.escapedText) { + case "augments": + case "extends": + tag = parseAugmentsTag(atToken, tagName); + break; + case "class": + case "constructor": + tag = parseClassTag(atToken, tagName); + break; + case "this": + tag = parseThisTag(atToken, tagName); + break; + case "arg": + case "argument": + case "param": + return parseParameterOrPropertyTag(atToken, tagName, 2 /* Parameter */, indent); + case "return": + case "returns": + tag = parseReturnTag(atToken, tagName); + break; + case "template": + tag = parseTemplateTag(atToken, tagName); + break; + case "type": + tag = parseTypeTag(atToken, tagName); + break; + case "typedef": + tag = parseTypedefTag(atToken, tagName, indent); + break; + case "callback": + tag = parseCallbackTag(atToken, tagName, indent); + break; + default: + tag = parseUnknownTag(atToken, tagName); + break; } - else { - tag = parseUnknownTag(atToken, tagName); + if (!tag.comment) { + // some tags, like typedef and callback, have already parsed their comments earlier + tag.comment = parseTagComments(indent + tag.end - tag.pos); } - if (!tag) { - // a badly malformed tag should not be added to the list of tags - return; - } - tag.comment = parseTagComments(indent + tag.end - tag.pos); - addTag(tag); + return tag; } function parseTagComments(indent) { var comments = []; @@ -19160,6 +20383,16 @@ var ts; indent += whitespace.length; } break; + case 17 /* OpenBraceToken */: + state = 2 /* SavingComments */; + if (lookAhead(function () { return nextJSDocToken() === 57 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextJSDocToken()) && scanner.getTokenText() === "link"; })) { + pushComment(scanner.getTokenText()); + nextJSDocToken(); + pushComment(scanner.getTokenText()); + nextJSDocToken(); + } + pushComment(scanner.getTokenText()); + break; case 39 /* AsteriskToken */: if (state === 0 /* BeginningOfLine */) { // leading asterisks start recording on the *next* (non-whitespace) token @@ -19181,12 +20414,15 @@ var ts; return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { - var result = createNode(284 /* JSDocTag */, atToken.pos); + var result = createNode(292 /* JSDocTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result); } function addTag(tag) { + if (!tag) { + return; + } if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -19201,6 +20437,10 @@ var ts; return token() === 17 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined; } function parseBracketNameInPropertyAndParamTag() { + if (token() === 13 /* NoSubstitutionTemplateLiteral */) { + // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild + return { name: createIdentifier(/*isIdentifier*/ true), isBracketed: false }; + } // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' var isBracketed = parseOptional(21 /* OpenBracketToken */); var name = parseJSDocEntityName(); @@ -19218,13 +20458,13 @@ var ts; switch (node.kind) { case 135 /* ObjectKeyword */: return true; - case 166 /* ArrayType */: + case 167 /* ArrayType */: return isObjectOrObjectArrayTypeReference(node.elementType); default: return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object"; } } - function parseParameterOrPropertyTag(atToken, tagName, target) { + function parseParameterOrPropertyTag(atToken, tagName, target, indent) { var typeExpression = tryParseTypeExpression(); var isNameFirst = !typeExpression; skipWhitespace(); @@ -19233,10 +20473,13 @@ var ts; if (isNameFirst) { typeExpression = tryParseTypeExpression(); } - var result = target === 1 /* Parameter */ ? - createNode(287 /* JSDocParameterTag */, atToken.pos) : - createNode(292 /* JSDocPropertyTag */, atToken.pos); - var nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name); + var result = target === 1 /* Property */ ? + createNode(302 /* JSDocPropertyTag */, atToken.pos) : + createNode(296 /* JSDocParameterTag */, atToken.pos); + var comment; + if (indent !== undefined) + comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -19247,22 +20490,25 @@ var ts; result.name = name; result.isNameFirst = isNameFirst; result.isBracketed = isBracketed; + result.comment = comment; return finishNode(result); } - function parseNestedTypeLiteral(typeExpression, name) { + function parseNestedTypeLiteral(typeExpression, name, target) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { - var typeLiteralExpression = createNode(274 /* JSDocTypeExpression */, scanner.getTokenPos()); + var typeLiteralExpression = createNode(281 /* JSDocTypeExpression */, scanner.getTokenPos()); var child = void 0; var jsdocTypeLiteral = void 0; var start_2 = scanner.getStartPos(); var children = void 0; - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(1 /* Parameter */, name); })) { - children = ts.append(children, child); + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, name); })) { + if (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) { + children = ts.append(children, child); + } } if (children) { - jsdocTypeLiteral = createNode(283 /* JSDocTypeLiteral */, start_2); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_2); jsdocTypeLiteral.jsDocPropertyTags = children; - if (typeExpression.type.kind === 166 /* ArrayType */) { + if (typeExpression.type.kind === 167 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typeLiteralExpression.type = finishNode(jsdocTypeLiteral); @@ -19271,27 +20517,27 @@ var ts; } } function parseReturnTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 288 /* JSDocReturnTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + if (ts.forEach(tags, function (t) { return t.kind === 297 /* JSDocReturnTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(288 /* JSDocReturnTag */, atToken.pos); + var result = createNode(297 /* JSDocReturnTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); return finishNode(result); } function parseTypeTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 289 /* JSDocTypeTag */; })) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + if (ts.forEach(tags, function (t) { return t.kind === 299 /* JSDocTypeTag */; })) { + parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } - var result = createNode(289 /* JSDocTypeTag */, atToken.pos); + var result = createNode(299 /* JSDocTypeTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); return finishNode(result); } function parseAugmentsTag(atToken, tagName) { - var result = createNode(285 /* JSDocAugmentsTag */, atToken.pos); + var result = createNode(293 /* JSDocAugmentsTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.class = parseExpressionWithTypeArgumentsForAugments(); @@ -19299,7 +20545,7 @@ var ts; } function parseExpressionWithTypeArgumentsForAugments() { var usedBrace = parseOptional(17 /* OpenBraceToken */); - var node = createNode(205 /* ExpressionWithTypeArguments */); + var node = createNode(209 /* ExpressionWithTypeArguments */); node.expression = parsePropertyAccessEntityNameExpression(); node.typeArguments = tryParseTypeArguments(); var res = finishNode(node); @@ -19309,9 +20555,9 @@ var ts; return res; } function parsePropertyAccessEntityNameExpression() { - var node = parseJSDocIdentifierName(/*createIfMissing*/ true); + var node = parseJSDocIdentifierName(); while (parseOptional(23 /* DotToken */)) { - var prop = createNode(183 /* PropertyAccessExpression */, node.pos); + var prop = createNode(187 /* PropertyAccessExpression */, node.pos); prop.expression = node; prop.name = parseJSDocIdentifierName(); node = finishNode(prop); @@ -19319,42 +20565,41 @@ var ts; return node; } function parseClassTag(atToken, tagName) { - var tag = createNode(286 /* JSDocClassTag */, atToken.pos); + var tag = createNode(294 /* JSDocClassTag */, atToken.pos); tag.atToken = atToken; tag.tagName = tagName; return finishNode(tag); } - function parseTypedefTag(atToken, tagName) { + function parseThisTag(atToken, tagName) { + var tag = createNode(298 /* JSDocThisTag */, atToken.pos); + tag.atToken = atToken; + tag.tagName = tagName; + tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + skipWhitespace(); + return finishNode(tag); + } + function parseTypedefTag(atToken, tagName, indent) { var typeExpression = tryParseTypeExpression(); skipWhitespace(); - var typedefTag = createNode(291 /* JSDocTypedefTag */, atToken.pos); + var typedefTag = createNode(301 /* JSDocTypedefTag */, atToken.pos); typedefTag.atToken = atToken; typedefTag.tagName = tagName; - typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0); - if (typedefTag.fullName) { - var rightNode = typedefTag.fullName; - while (true) { - if (rightNode.kind === 71 /* Identifier */ || !rightNode.body) { - // if node is identifier - use it as name - // otherwise use name of the rightmost part that we were able to parse - typedefTag.name = rightNode.kind === 71 /* Identifier */ ? rightNode : rightNode.name; - break; - } - rightNode = rightNode.body; - } - } + typedefTag.fullName = parseJSDocTypeNameWithNamespace(); + typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName); skipWhitespace(); + typedefTag.comment = parseTagComments(indent); typedefTag.typeExpression = typeExpression; + var end; if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { var child = void 0; var jsdocTypeLiteral = void 0; var childTypeTag = void 0; var start_3 = scanner.getStartPos(); - while (child = tryParse(function () { return parseChildParameterOrPropertyTag(0 /* Property */); })) { + while (child = tryParse(function () { return parseChildPropertyTag(); })) { if (!jsdocTypeLiteral) { - jsdocTypeLiteral = createNode(283 /* JSDocTypeLiteral */, start_3); + jsdocTypeLiteral = createNode(290 /* JSDocTypeLiteral */, start_3); } - if (child.kind === 289 /* JSDocTypeTag */) { + if (child.kind === 299 /* JSDocTypeTag */) { if (childTypeTag) { break; } @@ -19367,29 +20612,76 @@ var ts; } } if (jsdocTypeLiteral) { - if (typeExpression && typeExpression.type.kind === 166 /* ArrayType */) { + if (typeExpression && typeExpression.type.kind === 167 /* ArrayType */) { jsdocTypeLiteral.isArrayType = true; } typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? childTypeTag.typeExpression : finishNode(jsdocTypeLiteral); + end = typedefTag.typeExpression.end; } } - return finishNode(typedefTag); - function parseJSDocTypeNameWithNamespace(flags) { - var pos = scanner.getTokenPos(); - var typeNameOrNamespaceName = parseJSDocIdentifierName(); - if (typeNameOrNamespaceName && parseOptional(23 /* DotToken */)) { - var jsDocNamespaceNode = createNode(237 /* ModuleDeclaration */, pos); - jsDocNamespaceNode.flags |= flags; - jsDocNamespaceNode.name = typeNameOrNamespaceName; - jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(4 /* NestedNamespace */); - return finishNode(jsDocNamespaceNode); + // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace + return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end); + } + function parseJSDocTypeNameWithNamespace(nested) { + var pos = scanner.getTokenPos(); + if (!ts.tokenIsIdentifierOrKeyword(token())) { + return undefined; + } + var typeNameOrNamespaceName = parseJSDocIdentifierName(); + if (parseOptional(23 /* DotToken */)) { + var jsDocNamespaceNode = createNode(242 /* ModuleDeclaration */, pos); + if (nested) { + jsDocNamespaceNode.flags |= 4 /* NestedNamespace */; } - if (typeNameOrNamespaceName && flags & 4 /* NestedNamespace */) { - typeNameOrNamespaceName.isInJSDocNamespace = true; + jsDocNamespaceNode.name = typeNameOrNamespaceName; + jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + return finishNode(jsDocNamespaceNode); + } + if (nested) { + typeNameOrNamespaceName.isInJSDocNamespace = true; + } + return typeNameOrNamespaceName; + } + function parseCallbackTag(atToken, tagName, indent) { + var callbackTag = createNode(295 /* JSDocCallbackTag */, atToken.pos); + callbackTag.atToken = atToken; + callbackTag.tagName = tagName; + callbackTag.fullName = parseJSDocTypeNameWithNamespace(); + callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName); + skipWhitespace(); + callbackTag.comment = parseTagComments(indent); + var child; + var start = scanner.getStartPos(); + var jsdocSignature = createNode(291 /* JSDocSignature */, start); + jsdocSignature.parameters = []; + while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */); })) { + jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child); + } + var returnTag = tryParse(function () { + if (parseOptionalJsdoc(57 /* AtToken */)) { + var tag = parseTag(indent); + if (tag && tag.kind === 297 /* JSDocReturnTag */) { + return tag; + } + } + }); + if (returnTag) { + jsdocSignature.type = returnTag; + } + callbackTag.typeExpression = finishNode(jsdocSignature); + return finishNode(callbackTag); + } + function getJSDocTypeAliasName(fullName) { + if (fullName) { + var rightNode = fullName; + while (true) { + if (ts.isIdentifier(rightNode) || !rightNode.body) { + return ts.isIdentifier(rightNode) ? rightNode : rightNode.name; + } + rightNode = rightNode.body; } - return typeNameOrNamespaceName; } } function escapedTextsEqual(a, b) { @@ -19404,6 +20696,9 @@ var ts; } return a.escapedText === b.escapedText; } + function parseChildPropertyTag() { + return parseChildParameterOrPropertyTag(1 /* Property */); + } function parseChildParameterOrPropertyTag(target, name) { var canParseTag = true; var seenAsterisk = false; @@ -19412,8 +20707,9 @@ var ts; case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); - if (child && child.kind === 287 /* JSDocParameterTag */ && - (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { + if (child && (child.kind === 296 /* JSDocParameterTag */ || child.kind === 302 /* JSDocPropertyTag */) && + target !== 4 /* CallbackParameter */ && + name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { return false; } return child; @@ -19445,78 +20741,67 @@ var ts; nextJSDocToken(); var tagName = parseJSDocIdentifierName(); skipWhitespace(); - if (!tagName) { - return false; - } var t; switch (tagName.escapedText) { case "type": - return target === 0 /* Property */ && parseTypeTag(atToken, tagName); + return target === 1 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - t = 0 /* Property */; + t = 1 /* Property */; break; case "arg": case "argument": case "param": - t = 1 /* Parameter */; + t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; default: return false; } - if (target !== t) { + if (!(target & t)) { return false; } - var tag = parseParameterOrPropertyTag(atToken, tagName, target); + var tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); tag.comment = parseTagComments(tag.end - tag.pos); return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.some(tags, ts.isJSDocTemplateTag)) { - parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); + // the template tag looks like '@template {Constraint} T,U,V' + var constraint; + if (token() === 17 /* OpenBraceToken */) { + constraint = parseJSDocTypeExpression(); } - // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); - while (true) { - var typeParameter = createNode(147 /* TypeParameter */); - var name = parseJSDocIdentifierNameWithOptionalBraces(); + do { + skipWhitespace(); + var typeParameter = createNode(148 /* TypeParameter */); + typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); skipWhitespace(); - if (!name) { - parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); - return undefined; - } - typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); - if (token() === 26 /* CommaToken */) { - nextJSDocToken(); - skipWhitespace(); - } - else { - break; - } + } while (parseOptionalJsdoc(26 /* CommaToken */)); + if (constraint) { + ts.first(typeParameters).constraint = constraint.type; } - var result = createNode(290 /* JSDocTemplateTag */, atToken.pos); + var result = createNode(300 /* JSDocTemplateTag */, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = createNodeArray(typeParameters, typeParametersPos); finishNode(result); return result; } - function parseJSDocIdentifierNameWithOptionalBraces() { - var parsedBrace = parseOptional(17 /* OpenBraceToken */); - var res = parseJSDocIdentifierName(); - if (parsedBrace) { - parseExpected(18 /* CloseBraceToken */); - } - return res; - } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } + function parseOptionalJsdoc(t) { + if (token() === t) { + nextJSDocToken(); + return true; + } + return false; + } function parseJSDocEntityName() { - var entity = parseJSDocIdentifierName(/*createIfMissing*/ true); + var entity = parseJSDocIdentifierName(); if (parseOptional(21 /* OpenBracketToken */)) { parseExpected(22 /* CloseBracketToken */); // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking. @@ -19524,7 +20809,7 @@ var ts; // but it's not worth it to enforce that restriction. } while (parseOptional(23 /* DotToken */)) { - var name = parseJSDocIdentifierName(/*createIfMissing*/ true); + var name = parseJSDocIdentifierName(); if (parseOptional(21 /* OpenBracketToken */)) { parseExpected(22 /* CloseBracketToken */); } @@ -19532,21 +20817,14 @@ var ts; } return entity; } - function parseJSDocIdentifierName(createIfMissing) { - if (createIfMissing === void 0) { createIfMissing = false; } + function parseJSDocIdentifierName(message) { if (!ts.tokenIsIdentifierOrKeyword(token())) { - if (createIfMissing) { - return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected); - } - else { - parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected); - return undefined; - } + return createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected); } var pos = scanner.getTokenPos(); var end = scanner.getTextPos(); var result = createNode(71 /* Identifier */, pos); - result.escapedText = ts.escapeLeadingUnderscores(content.substring(pos, end)); + result.escapedText = ts.escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); nextJSDocToken(); return result; @@ -19654,7 +20932,7 @@ var ts; if (ts.hasJSDocNodes(node)) { for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { var jsDocComment = _a[_i]; - forEachChild(jsDocComment, visitNode, visitArray); + visitNode(jsDocComment); } } checkNodePositions(node, aggressiveChecks); @@ -19750,10 +21028,17 @@ var ts; function checkNodePositions(node, aggressiveChecks) { if (aggressiveChecks) { var pos_2 = node.pos; - forEachChild(node, function (child) { + var visitNode_1 = function (child) { ts.Debug.assert(child.pos >= pos_2); pos_2 = child.end; - }); + }; + if (ts.hasJSDocNodes(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode_1(jsDocComment); + } + } + forEachChild(node, visitNode_1); ts.Debug.assert(pos_2 <= node.end); } } @@ -19778,6 +21063,12 @@ var ts; // Adjust the pos or end (or both) of the intersecting element accordingly. adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); forEachChild(child, visitNode, visitArray); + if (ts.hasJSDocNodes(child)) { + for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) { + var jsDocComment = _a[_i]; + visitNode(jsDocComment); + } + } checkNodePositions(child, aggressiveChecks); return; } @@ -19842,15 +21133,15 @@ var ts; var lastNodeEntirelyBeforePosition; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } } return bestResult; - function getLastChild(node) { + function getLastDescendant(node) { while (true) { - var lastChild = getLastChildWorker(node); + var lastChild = ts.getLastChild(node); if (lastChild) { node = lastChild; } @@ -19859,15 +21150,6 @@ var ts; } } } - function getLastChildWorker(node) { - var last; - forEachChild(node, function (child) { - if (ts.nodeIsPresent(child)) { - last = child; - } - }); - return last; - } function visit(child) { if (ts.nodeIsMissing(child)) { // Missing nodes are effectively invisible to us. We never even consider them @@ -20029,9 +21311,11 @@ var ts; InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; })(InvalidPosition || (InvalidPosition = {})); })(IncrementalParser || (IncrementalParser = {})); + /** @internal */ function isDeclarationFileName(fileName) { return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); } + ts.isDeclarationFileName = isDeclarationFileName; /*@internal*/ function processCommentPragmas(context, sourceText) { var triviaScanner = ts.createScanner(context.languageVersion, /*skipTrivia*/ false, 0 /* Standard */, sourceText); @@ -20055,7 +21339,7 @@ var ts; context.pragmas = ts.createMap(); for (var _i = 0, pragmas_1 = pragmas; _i < pragmas_1.length; _i++) { var pragma = pragmas_1[_i]; - if (context.pragmas.has(pragma.name)) { + if (context.pragmas.has(pragma.name)) { // TODO: GH#18217 var currentValue = context.pragmas.get(pragma.name); if (currentValue instanceof Array) { currentValue.push(pragma.args); @@ -20074,6 +21358,7 @@ var ts; context.checkJsDirective = undefined; context.referencedFiles = []; context.typeReferenceDirectives = []; + context.libReferenceDirectives = []; context.amdDependencies = []; context.hasNoDefaultLib = false; context.pragmas.forEach(function (entryOrList, key) { @@ -20083,13 +21368,18 @@ var ts; case "reference": { var referencedFiles_1 = context.referencedFiles; var typeReferenceDirectives_1 = context.typeReferenceDirectives; + var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + // TODO: GH#18217 if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } else if (arg.arguments.types) { typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); } + else if (arg.arguments.lib) { + libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + } else if (arg.arguments.path) { referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); } @@ -20100,10 +21390,7 @@ var ts; break; } case "amd-dependency": { - context.amdDependencies = ts.map(ts.toArray(entryOrList), function (_a) { - var _b = _a.arguments, name = _b.name, path = _b.path; - return ({ name: name, path: path }); - }); + context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); }); // TODO: GH#18217 break; } case "amd-module": { @@ -20126,7 +21413,7 @@ var ts; case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" ts.forEach(ts.toArray(entryOrList), function (entry) { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { // TODO: GH#18217 context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -20154,7 +21441,7 @@ var ts; var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im; function extractPragmas(pragmas, range, text) { - var tripleSlash = tripleSlashXMLCommentStartRegEx.exec(text); + var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks var pragma = ts.commentPragmas[name]; @@ -20191,14 +21478,16 @@ var ts; } return; } - var singleLine = singleLinePragmaRegEx.exec(text); + var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text); if (singleLine) { return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); } - var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) - var multiLineMatch; - while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { - addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) + var multiLineMatch = void 0; + while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { + addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); + } } } function addPragmaForMatch(pragmas, range, kind, match) { @@ -20235,3495 +21524,2292 @@ var ts; } return argMap; } -})(ts || (ts = {})); -/// -/// -/* @internal */ -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) { - return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; - } - ts.getModuleInstanceState = getModuleInstanceState; - function getModuleInstanceStateWorker(node) { - // A module is uninstantiated if it contains only - switch (node.kind) { - // 1. interface declarations, type alias declarations - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - return 0 /* NonInstantiated */; - // 2. const enum declarations - case 236 /* EnumDeclaration */: - if (ts.isConst(node)) { - return 2 /* ConstEnumOnly */; - } - break; - // 3. non-exported import declarations - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - if (!(ts.hasModifier(node, 1 /* Export */))) { - return 0 /* NonInstantiated */; - } - break; - // 4. other uninstantiated module declarations. - case 238 /* ModuleBlock */: { - var state_1 = 0 /* NonInstantiated */; - ts.forEachChild(node, function (n) { - var childState = getModuleInstanceStateWorker(n); - switch (childState) { - case 0 /* NonInstantiated */: - // child is non-instantiated - continue searching - return; - case 2 /* ConstEnumOnly */: - // child is const enum only - record state and continue searching - state_1 = 2 /* ConstEnumOnly */; - return; - case 1 /* Instantiated */: - // child is instantiated - record state and stop - state_1 = 1 /* Instantiated */; - return true; - default: - ts.Debug.assertNever(childState); - } - }); - return state_1; - } - case 237 /* ModuleDeclaration */: - return getModuleInstanceState(node); - case 71 /* Identifier */: - // Only jsdoc typedef definition can exist in jsdoc namespace, and it should - // be considered the same as type alias - if (node.isInJSDocNamespace) { - return 0 /* NonInstantiated */; - } - } - return 1 /* Instantiated */; - } - var ContainerFlags; - (function (ContainerFlags) { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - ContainerFlags[ContainerFlags["None"] = 0] = "None"; - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; - // The current node is the container of a control flow path. The current control flow should - // be saved and restored, and a new control flow initialized within the container. - 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"); - binder(file, options); - ts.performance.mark("afterBind"); - ts.performance.measure("Bind", "beforeBind", "afterBind"); - } - ts.bindSourceFile = bindSourceFile; - function createBinder() { - var file; - var options; - var languageVersion; - var parent; - var container; - var blockScopeContainer; - var lastContainer; - var seenThisKeyword; - // state used by control flow analysis - var currentFlow; - var currentBreakTarget; - var currentContinueTarget; - var currentReturnTarget; - var currentTrueTarget; - var currentFalseTarget; - var preSwitchCaseFlow; - var activeLabels; - var hasExplicitReturn; - // state used for emit helpers - var emitFlags; - // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places or if we hit a class/namespace - // or if compiler options contain alwaysStrict. - var inStrictMode; - var symbolCount = 0; - var Symbol; // tslint:disable-line variable-name - var classifiableNames; - var unreachableFlow = { flags: 1 /* Unreachable */ }; - var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; - // state used to aggregate transform flags during bind. - var subtreeTransformFlags = 0 /* None */; - var skipTransformFlagAggregation; - /** - * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) - * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) - * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. - */ - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { - return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); - } - function bindSourceFile(f, opts) { - file = f; - options = opts; - languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = ts.createUnderscoreEscapedMap(); - symbolCount = 0; - skipTransformFlagAggregation = file.isDeclarationFile; - Symbol = ts.objectAllocator.getSymbolConstructor(); - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = 0 /* None */; - subtreeTransformFlags = 0 /* None */; - } - return bindSourceFile; - function bindInStrictMode(file, opts) { - if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { - // bind in strict mode source files with alwaysStrict option - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - function createSymbol(flags, name) { - symbolCount++; - return new Symbol(flags, name); - } - function addDeclarationToSymbol(symbol, node, symbolFlags) { - symbol.flags |= symbolFlags; - node.symbol = symbol; - if (!symbol.declarations) { - symbol.declarations = [node]; - } - else { - symbol.declarations.push(node); - } - if (symbolFlags & 1952 /* HasExports */ && !symbol.exports) { - symbol.exports = ts.createSymbolTable(); - } - if (symbolFlags & 6240 /* HasMembers */ && !symbol.members) { - symbol.members = ts.createSymbolTable(); - } - if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === 237 /* ModuleDeclaration */)) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } - } - } - // Should not be called on a declaration with a computed property name, - // unless it is a well known Symbol. - function getDeclarationName(node) { - if (node.kind === 247 /* ExportAssignment */) { - return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; - } - var name = ts.getNameOfDeclaration(node); - if (name) { - if (ts.isAmbientModule(node)) { - var moduleName = ts.getTextOfIdentifierOrLiteral(name); - return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); - } - if (name.kind === 146 /* ComputedPropertyName */) { - var nameExpression = name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { - return ts.escapeLeadingUnderscores(nameExpression.text); - } - ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); - return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); - } - return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; - } - switch (node.kind) { - case 154 /* Constructor */: - return "__constructor" /* Constructor */; - case 162 /* FunctionType */: - case 157 /* CallSignature */: - return "__call" /* Call */; - case 163 /* ConstructorType */: - case 158 /* ConstructSignature */: - return "__new" /* New */; - case 159 /* IndexSignature */: - return "__index" /* Index */; - case 248 /* ExportDeclaration */: - return "__export" /* ExportStar */; - case 198 /* BinaryExpression */: - if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { - // module.exports = ... - return "export=" /* ExportEquals */; - } - ts.Debug.fail("Unknown binary declaration kind"); - break; - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - return (ts.hasModifier(node, 512 /* Default */) ? "default" /* Default */ : undefined); - case 280 /* JSDocFunctionType */: - return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); - case 148 /* Parameter */: - // Parameters with names are handled at the top of this function. Parameters - // without names can only come from JSDocFunctionTypes. - ts.Debug.assert(node.parent.kind === 280 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); - var functionType = node.parent; - var index = functionType.parameters.indexOf(node); - return "arg" + index; - case 291 /* JSDocTypedefTag */: - var name_2 = ts.getNameOfJSDocTypedef(node); - return typeof name_2 !== "undefined" ? name_2.escapedText : undefined; - } - } - function getDisplayName(node) { - return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(getDeclarationName(node)); - } - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { - ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = ts.hasModifier(node, 512 /* Default */); - // The exported symbol for an export default function/class node is always named "default" - var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); - var symbol; - if (name === undefined) { - symbol = createSymbol(0 /* None */, "__missing" /* Missing */); - } - else { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // - // If we created a new symbol, either because we didn't have a symbol with this name - // in the symbol table, or we conflicted with an existing symbol, then just add this - // node as the sole declaration of the new symbol. - // - // Otherwise, we'll be merging into a compatible existing symbol (for example when - // you have multiple 'vars' with the same name in the same container). In this case - // just add this node into the declarations list of the symbol. - symbol = symbolTable.get(name); - if (includes & 2885600 /* Classifiable */) { - classifiableNames.set(name, true); - } - if (!symbol) { - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - if (isReplaceableByMethod) - symbol.isReplaceableByMethod = true; - } - else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { - // A symbol already exists, so don't add this as a declaration. - return symbol; - } - else if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - } - else { - if (ts.isNamedDeclaration(node)) { - node.name.parent = node; - } - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - var message_1 = symbol.flags & 2 /* BlockScopedVariable */ - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : ts.Diagnostics.Duplicate_identifier_0; - if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { - message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; - } - if (symbol.declarations && symbol.declarations.length) { - // If the current node is a default export of some sort, then check if - // there are any other default exports that we need to error on. - // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. - if (isDefaultExport) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. - // Error on multiple export default in the following case: - // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default - // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === 247 /* ExportAssignment */ && !node.isExportEquals))) { - message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); - symbol = createSymbol(0 /* None */, name); - } - } - } - addDeclarationToSymbol(symbol, node, includes); - if (symbol.parent) { - ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); - } - else { - symbol.parent = parent; - } - return symbol; - } - function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; - if (symbolFlags & 2097152 /* Alias */) { - if (node.kind === 250 /* ExportSpecifier */ || (node.kind === 241 /* ImportEqualsDeclaration */ && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, - // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge - // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation - // and this case is specially handled. Module augmentations should only be merged with original module definition - // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (node.kind === 291 /* JSDocTypedefTag */) - ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. - var isJSDocTypedefInJSDocNamespace = ts.isJSDocTypedefTag(node) && node.name && node.name.kind === 71 /* Identifier */ && node.name.isInJSDocNamespace; - if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || isJSDocTypedefInJSDocNamespace) { - var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; - var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - } - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name - // used for a container is unique. - function bindContainer(node, containerFlags) { - // Before we recurse into a node's children, we first save the existing parent, container - // and block-container. Then after we pop out of processing the children, we restore - // these saved values. - var saveContainer = container; - var savedBlockScopeContainer = blockScopeContainer; - // Depending on what kind of node this is, we may have to adjust the current container - // and block-container. If the current node is a container, then it is automatically - // considered the current block-container as well. Also, for containers that we know - // may contain locals, we proactively initialize the .locals field. We do this because - // it's highly likely that the .locals will be needed to place some child in (for example, - // a parameter, or variable declaration). - // - // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped - // variable in them. We don't want to end up allocating an object for every 'block' we - // run into when most of them won't be necessary. - // - // Finally, if this is a block-container, then we clear out any existing .locals object - // it may contain within it. This happens in incremental scenarios. Because we can be - // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidentally move any stale data forward from - // a previous compilation. - if (containerFlags & 1 /* IsContainer */) { - container = blockScopeContainer = node; - if (containerFlags & 32 /* HasLocals */) { - container.locals = ts.createSymbolTable(); - } - addToContainerChain(container); - } - else if (containerFlags & 2 /* IsBlockScopedContainer */) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & 4 /* IsControlFlowContainer */) { - var saveCurrentFlow = currentFlow; - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - var saveReturnTarget = currentReturnTarget; - var saveActiveLabels = activeLabels; - var saveHasExplicitReturn = hasExplicitReturn; - var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && !!ts.getImmediatelyInvokedFunctionExpression(node); - // A non-async IIFE is considered part of the containing control flow. Return statements behave - // similarly to break statements that exit to a label just past the statement body. - if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { - currentFlow.container = node; - } - } - // We create a return control flow graph for IIFEs and constructors. For constructors - // we use the return control flow graph in strict property intialization checks. - currentReturnTarget = isIIFE || node.kind === 154 /* Constructor */ ? createBranchLabel() : undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - // Reset all reachability check related flags on node (for incremental scenarios) - node.flags &= ~1408 /* ReachabilityAndEmitFlags */; - if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { - node.flags |= 128 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 256 /* HasExplicitReturn */; - } - if (node.kind === 272 /* SourceFile */) { - node.flags |= emitFlags; - } - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - if (node.kind === 154 /* Constructor */) { - node.returnFlowNode = currentFlow; - } - } - if (!isIIFE) { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & 64 /* IsInterface */) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - function bindChildren(node) { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & 536870912 /* HasComputedFlags */) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - function bindEach(nodes) { - if (nodes === undefined) { - return; - } - if (skipTransformFlagAggregation) { - ts.forEach(nodes, bind); - } - else { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0 /* None */; - var nodeArrayFlags = 0 /* None */; - for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { - var node = nodes_2[_i]; - bind(node); - nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; - } - nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - } - function bindEachChild(node) { - ts.forEachChild(node, bind, bindEach); - } - function bindChildrenWorker(node) { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (ts.hasJSDocNodes(node)) { - if (ts.isInJavaScriptFile(node)) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var j = _a[_i]; - bind(j); - } - } - else { - for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { - var j = _c[_b]; - setParentPointers(node, j); - } - } - } - if (checkUnreachable(node)) { - bindEachChild(node); - return; - } - switch (node.kind) { - case 217 /* WhileStatement */: - bindWhileStatement(node); - break; - case 216 /* DoStatement */: - bindDoStatement(node); - break; - case 218 /* ForStatement */: - bindForStatement(node); - break; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - bindForInOrForOfStatement(node); - break; - case 215 /* IfStatement */: - bindIfStatement(node); - break; - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: - bindReturnOrThrow(node); - break; - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: - bindBreakOrContinueStatement(node); - break; - case 228 /* TryStatement */: - bindTryStatement(node); - break; - case 225 /* SwitchStatement */: - bindSwitchStatement(node); - break; - case 239 /* CaseBlock */: - bindCaseBlock(node); - break; - case 264 /* CaseClause */: - bindCaseClause(node); - break; - case 226 /* LabeledStatement */: - bindLabeledStatement(node); - break; - case 196 /* PrefixUnaryExpression */: - bindPrefixUnaryExpressionFlow(node); - break; - case 197 /* PostfixUnaryExpression */: - bindPostfixUnaryExpressionFlow(node); - break; - case 198 /* BinaryExpression */: - bindBinaryExpressionFlow(node); - break; - case 192 /* DeleteExpression */: - bindDeleteExpressionFlow(node); - break; - case 199 /* ConditionalExpression */: - bindConditionalExpressionFlow(node); - break; - case 230 /* VariableDeclaration */: - bindVariableDeclarationFlow(node); - break; - case 185 /* CallExpression */: - bindCallExpressionFlow(node); - break; - case 282 /* JSDocComment */: - bindJSDocComment(node); - break; - case 291 /* JSDocTypedefTag */: - bindJSDocTypedefTag(node); - break; - default: - bindEachChild(node); - break; - } - } - function isNarrowingExpression(expr) { - switch (expr.kind) { - case 71 /* Identifier */: - case 99 /* ThisKeyword */: - case 183 /* PropertyAccessExpression */: - return isNarrowableReference(expr); - case 185 /* CallExpression */: - return hasNarrowableArgument(expr); - case 189 /* ParenthesizedExpression */: - return isNarrowingExpression(expr.expression); - case 198 /* BinaryExpression */: - return isNarrowingBinaryExpression(expr); - case 196 /* PrefixUnaryExpression */: - return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); - } + /** @internal */ + function tagNamesAreEquivalent(lhs, rhs) { + if (lhs.kind !== rhs.kind) { return false; } - function isNarrowableReference(expr) { - return expr.kind === 71 /* Identifier */ || - expr.kind === 99 /* ThisKeyword */ || - expr.kind === 97 /* SuperKeyword */ || - expr.kind === 183 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + if (lhs.kind === 71 /* Identifier */) { + return lhs.escapedText === rhs.escapedText; } - function hasNarrowableArgument(expr) { - if (expr.arguments) { - for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { - var argument = _a[_i]; - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === 183 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { - return true; - } - return false; - } - function isNarrowingTypeofOperands(expr1, expr2) { - return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); - } - function isNarrowableInOperands(left, right) { - return ts.isStringLiteralLike(left) && isNarrowingExpression(right); - } - function isNarrowingBinaryExpression(expr) { - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableReference(expr.left); - case 32 /* EqualsEqualsToken */: - case 33 /* ExclamationEqualsToken */: - case 34 /* EqualsEqualsEqualsToken */: - case 35 /* ExclamationEqualsEqualsToken */: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case 93 /* InstanceOfKeyword */: - return isNarrowableOperand(expr.left); - case 92 /* InKeyword */: - return isNarrowableInOperands(expr.left, expr.right); - case 26 /* CommaToken */: - return isNarrowingExpression(expr.right); - } - return false; - } - function isNarrowableOperand(expr) { - switch (expr.kind) { - case 189 /* ParenthesizedExpression */: - return isNarrowableOperand(expr.expression); - case 198 /* BinaryExpression */: - switch (expr.operatorToken.kind) { - case 58 /* EqualsToken */: - return isNarrowableOperand(expr.left); - case 26 /* CommaToken */: - return isNarrowableOperand(expr.right); - } - } - return isNarrowableReference(expr); - } - function createBranchLabel() { - return { - flags: 4 /* BranchLabel */, - antecedents: undefined - }; - } - function createLoopLabel() { - return { - flags: 8 /* LoopLabel */, - antecedents: undefined - }; - } - function setFlowNodeReferenced(flow) { - // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; - } - function addAntecedent(label, antecedent) { - if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - function createFlowCondition(flags, antecedent, expression) { - if (antecedent.flags & 1 /* Unreachable */) { - return antecedent; - } - if (!expression) { - return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; - } - if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || - expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(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 }; - } - function createFlowAssignment(antecedent, node) { - setFlowNodeReferenced(antecedent); - return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; - } - function createFlowArrayMutation(antecedent, node) { - setFlowNodeReferenced(antecedent); - var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; - return res; - } - function finishFlowLabel(flow) { - var antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - function isStatementCondition(node) { - var parent = node.parent; - switch (parent.kind) { - case 215 /* IfStatement */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: - return parent.expression === node; - case 218 /* ForStatement */: - case 199 /* ConditionalExpression */: - return parent.condition === node; - } - return false; - } - function isLogicalExpression(node) { - while (true) { - if (node.kind === 189 /* ParenthesizedExpression */) { - node = node.expression; - } - else if (node.kind === 196 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { - node = node.operand; - } - else { - return node.kind === 198 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || - node.operatorToken.kind === 54 /* BarBarToken */); - } - } - } - function isTopLevelLogicalExpression(node) { - while (node.parent.kind === 189 /* ParenthesizedExpression */ || - node.parent.kind === 196 /* PrefixUnaryExpression */ && - node.parent.operator === 51 /* ExclamationToken */) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - function bindCondition(node, trueTarget, falseTarget) { - var saveTrueTarget = currentTrueTarget; - var saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); - } - } - function bindIterativeStatement(node, breakTarget, continueTarget) { - var saveBreakTarget = currentBreakTarget; - var saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - function bindWhileStatement(node) { - var preWhileLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - function bindDoStatement(node) { - var preDoLabel = createLoopLabel(); - var enclosingLabeledStatement = node.parent.kind === 226 /* LabeledStatement */ - ? ts.lastOrUndefined(activeLabels) - : undefined; - // if do statement is wrapped in labeled statement then target labels for break/continue with or without - // label should be the same - var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); - var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - function bindForStatement(node) { - var preLoopLabel = createLoopLabel(); - var preBodyLabel = createBranchLabel(); - var postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindForInOrForOfStatement(node) { - var preLoopLabel = createLoopLabel(); - var postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - if (node.kind === 220 /* ForOfStatement */) { - bind(node.awaitModifier); - } - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== 231 /* VariableDeclarationList */) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - function bindIfStatement(node) { - var thenLabel = createBranchLabel(); - var elseLabel = createBranchLabel(); - var postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - function bindReturnOrThrow(node) { - bind(node.expression); - if (node.kind === 223 /* ReturnStatement */) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - function findActiveLabel(name) { - if (activeLabels) { - for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { - var label = activeLabels_1[_i]; - if (label.name === name) { - return label; - } - } - } - return undefined; - } - function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { - var flowLabel = node.kind === 222 /* BreakStatement */ ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - function bindBreakOrContinueStatement(node) { - bind(node.label); - if (node.label) { - var activeLabel = findActiveLabel(node.label.escapedText); - if (activeLabel) { - activeLabel.referenced = true; - bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - function bindTryStatement(node) { - var preFinallyLabel = createBranchLabel(); - var preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! - bind(node.tryBlock); - addAntecedent(preFinallyLabel, currentFlow); - var flowAfterTry = currentFlow; - var flowAfterCatch = unreachableFlow; - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(preFinallyLabel, currentFlow); - flowAfterCatch = currentFlow; - } - if (node.finallyBlock) { - // in finally flow is combined from pre-try/flow from try/flow from catch - // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - // also for finally blocks we inject two extra edges into the flow graph. - // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it - // second -> edge that represents post-finally flow. - // these edges are used in following scenario: - // let a; (1) - // try { a = someOperation(); (2)} - // finally { (3) console.log(a) } (4) - // (5) a - // flow graph for this case looks roughly like this (arrows show ): - // (1-pre-try-flow) <--.. <-- (2-post-try-flow) - // ^ ^ - // |*****(3-pre-finally-label) -----| - // ^ - // |-- ... <-- (4-post-finally-label) <--- (5) - // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account - // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) - // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable - // Simply speaking code inside finally block is treated as reachable as pre-try-flow - // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. - // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from - // final flows of these blocks without taking pre-try flow into account. - // - // extra edges that we inject allows to control this behavior - // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; - addAntecedent(preFinallyLabel, preFinallyFlow); - currentFlow = finishFlowLabel(preFinallyLabel); - bind(node.finallyBlock); - // if flow after finally is unreachable - keep it - // otherwise check if flows after try and after catch are unreachable - // if yes - convert current flow to unreachable - // i.e. - // try { return "1" } finally { console.log(1); } - // console.log(2); // this line should be unreachable even if flow falls out of finally block - if (!(currentFlow.flags & 1 /* Unreachable */)) { - if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { - currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow - ? reportedUnreachableFlow - : unreachableFlow; - } - } - if (!(currentFlow.flags & 1 /* Unreachable */)) { - var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; - preFinallyFlow.lock = afterFinallyFlow; - currentFlow = afterFinallyFlow; - } - } - else { - currentFlow = finishFlowLabel(preFinallyLabel); - } - } - function bindSwitchStatement(node) { - var postSwitchLabel = createBranchLabel(); - bind(node.expression); - var saveBreakTarget = currentBreakTarget; - var savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 265 /* DefaultClause */; }); - // We mark a switch statement as possibly exhaustive if it has no default clause and if all - // case clauses have unreachable end points (e.g. they all return). - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - function bindCaseBlock(node) { - var savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - var clauses = node.clauses; - var fallthroughFlow = unreachableFlow; - for (var i = 0; i < clauses.length; i++) { - var clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - var preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - var clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); - } - } - clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; - subtreeTransformFlags |= savedSubtreeTransformFlags; - } - function bindCaseClause(node) { - var saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - bindEach(node.statements); - } - function pushActiveLabel(name, breakTarget, continueTarget) { - var activeLabel = { - name: name, - breakTarget: breakTarget, - continueTarget: continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - function popActiveLabel() { - activeLabels.pop(); - } - function bindLabeledStatement(node) { - var preStatementLabel = createLoopLabel(); - var postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, ts.Diagnostics.Unused_label)); - } - if (!node.statement || node.statement.kind !== 216 /* DoStatement */) { - // do statement sets current flow inside bindDoStatement - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - } - function bindDestructuringTargetFlow(node) { - if (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { - bindAssignmentTargetFlow(node.left); - } - else { - bindAssignmentTargetFlow(node); - } - } - function bindAssignmentTargetFlow(node) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === 181 /* ArrayLiteralExpression */) { - for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { - var e = _a[_i]; - if (e.kind === 202 /* SpreadElement */) { - bindAssignmentTargetFlow(e.expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === 182 /* ObjectLiteralExpression */) { - for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { - var p = _c[_b]; - if (p.kind === 268 /* PropertyAssignment */) { - bindDestructuringTargetFlow(p.initializer); - } - else if (p.kind === 269 /* ShorthandPropertyAssignment */) { - bindAssignmentTargetFlow(p.name); - } - else if (p.kind === 270 /* SpreadAssignment */) { - bindAssignmentTargetFlow(p.expression); - } - } - } - } - function bindLogicalExpression(node, trueTarget, falseTarget) { - var preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - function bindPrefixUnaryExpressionFlow(node) { - if (node.operator === 51 /* ExclamationToken */) { - var saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - bindEachChild(node); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - } - function bindPostfixUnaryExpressionFlow(node) { - bindEachChild(node); - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - bindAssignmentTargetFlow(node.operand); - } - } - function bindBinaryExpressionFlow(node) { - var operator = node.operatorToken.kind; - if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { - if (isTopLevelLogicalExpression(node)) { - var postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - bindEachChild(node); - if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (operator === 58 /* EqualsToken */ && node.left.kind === 184 /* ElementAccessExpression */) { - var elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - function bindDeleteExpressionFlow(node) { - bindEachChild(node); - if (node.expression.kind === 183 /* PropertyAccessExpression */) { - bindAssignmentTargetFlow(node.expression); - } - } - function bindConditionalExpressionFlow(node) { - var trueLabel = createBranchLabel(); - var falseLabel = createBranchLabel(); - var postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.questionToken); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.colonToken); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - function bindInitializedVariableFlow(node) { - var name = !ts.isOmittedExpression(node) ? node.name : undefined; - if (ts.isBindingPattern(name)) { - for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { - var child = _a[_i]; - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - function bindVariableDeclarationFlow(node) { - bindEachChild(node); - if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { - bindInitializedVariableFlow(node); - } - } - function bindJSDocComment(node) { - ts.forEachChild(node, function (n) { - if (n.kind !== 291 /* JSDocTypedefTag */) { - bind(n); - } - }); - } - function bindJSDocTypedefTag(node) { - ts.forEachChild(node, function (n) { - // if the node has a fullName "A.B.C", that means symbol "C" was already bound - // when we visit "fullName"; so when we visit the name "C" as the next child of - // the jsDocTypedefTag, we should skip binding it. - if (node.fullName && n === node.name && node.fullName.kind !== 71 /* Identifier */) { - return; - } - bind(n); - }); - } - function bindCallExpressionFlow(node) { - // If the target of the call expression is a function expression or arrow function we have - // an immediately invoked function expression (IIFE). Initialize the flowNode property to - // the current control flow (which includes evaluation of the IIFE arguments). - var expr = node.expression; - while (expr.kind === 189 /* ParenthesizedExpression */) { - expr = expr.expression; - } - if (expr.kind === 190 /* FunctionExpression */ || expr.kind === 191 /* ArrowFunction */) { - bindEach(node.typeArguments); - bindEach(node.arguments); - bind(node.expression); - } - else { - bindEachChild(node); - } - if (node.expression.kind === 183 /* PropertyAccessExpression */) { - var propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - function getContainerFlags(node) { - switch (node.kind) { - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 182 /* ObjectLiteralExpression */: - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 261 /* JsxAttributes */: - return 1 /* IsContainer */; - case 234 /* InterfaceDeclaration */: - return 1 /* IsContainer */ | 64 /* IsInterface */; - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 176 /* MappedType */: - return 1 /* IsContainer */ | 32 /* HasLocals */; - case 272 /* SourceFile */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; - case 153 /* MethodDeclaration */: - if (ts.isObjectLiteralOrClassExpressionMethod(node)) { - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; - } - // falls through - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 157 /* CallSignature */: - case 280 /* JSDocFunctionType */: - case 162 /* FunctionType */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 163 /* ConstructorType */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; - case 238 /* ModuleBlock */: - return 4 /* IsControlFlowContainer */; - case 151 /* PropertyDeclaration */: - return node.initializer ? 4 /* IsControlFlowContainer */ : 0; - case 267 /* CatchClause */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 239 /* CaseBlock */: - return 2 /* IsBlockScopedContainer */; - case 211 /* Block */: - // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Otherwise 'x' - // would not appear to be a redeclaration of a block scoped local in the following - // example: - // - // function foo() { - // var x; - // let x; - // } - // - // If we placed 'var x' into the function locals and 'let x' into the locals of - // the block, then there would be no collision. - // - // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision - // conflict. - return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; - } - return 0 /* None */; - } - function addToContainerChain(next) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - lastContainer = next; - } - function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { - switch (container.kind) { - // Modules, source files, and classes need specialized handling for how their - // members are declared (for example, a member of a class will go into a specific - // symbol table depending on if it is static or not). We defer to specialized - // handlers to take care of declaring these child members. - case 237 /* ModuleDeclaration */: - return declareModuleMember(node, symbolFlags, symbolExcludes); - case 272 /* SourceFile */: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - return declareClassMember(node, symbolFlags, symbolExcludes); - case 236 /* EnumDeclaration */: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 182 /* ObjectLiteralExpression */: - case 234 /* InterfaceDeclaration */: - case 261 /* JsxAttributes */: - // Interface/Object-types always have their children added to the 'members' of - // their container. They are only accessible through an instance of their - // container, and are never in scope otherwise (even inside the body of the - // object / type / interface declaring them). An exception is type parameters, - // which are in scope without qualification (similar to 'locals'). - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* JSDocFunctionType */: - case 235 /* TypeAliasDeclaration */: - case 176 /* MappedType */: - // All the children of these container types are never visible through another - // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, - // they're only accessed 'lexically' (i.e. from code that exists underneath - // their container in the tree). To accomplish this, we simply add their declared - // symbol to the 'locals' of the container. These symbols can then be found as - // the type checker walks up the containers, checking them for matching names. - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function declareClassMember(node, symbolFlags, symbolExcludes) { - return ts.hasModifier(node, 32 /* Static */) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - function declareSourceFileMember(node, symbolFlags, symbolExcludes) { - return ts.isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - function hasExportDeclarations(node) { - var body = node.kind === 272 /* SourceFile */ ? node : node.body; - if (body && (body.kind === 272 /* SourceFile */ || body.kind === 238 /* ModuleBlock */)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var stat = _a[_i]; - if (stat.kind === 248 /* ExportDeclaration */ || stat.kind === 247 /* ExportAssignment */) { - return true; - } - } - } - return false; - } - function setExportContextFlag(node) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (node.flags & 2097152 /* Ambient */ && !hasExportDeclarations(node)) { - node.flags |= 32 /* ExportContext */; - } - else { - node.flags &= ~32 /* ExportContext */; - } - } - function bindModuleDeclaration(node) { - setExportContextFlag(node); - if (ts.isAmbientModule(node)) { - if (ts.hasModifier(node, 1 /* Export */)) { - errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (ts.isModuleAugmentationExternal(node)) { - declareModuleSymbol(node); - } - else { - var pattern = void 0; - if (node.name.kind === 9 /* StringLiteral */) { - var text = node.name.text; - if (ts.hasZeroOrOneAsteriskCharacter(text)) { - pattern = ts.tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); - file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); - } - } - else { - var state = declareModuleSymbol(node); - if (state !== 0 /* NonInstantiated */) { - var symbol = node.symbol; - // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only - symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) - // Current must be `const enum` only - && state === 2 /* ConstEnumOnly */ - // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) - && symbol.constEnumOnlyModule !== false; - } - } - } - function declareModuleSymbol(node) { - var state = getModuleInstanceState(node); - var instantiated = state !== 0 /* NonInstantiated */; - declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); - return state; - } - function bindFunctionOrConstructorType(node) { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, 131072 /* Signature */); - var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); - addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); - typeLiteralSymbol.members = ts.createSymbolTable(); - 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++) { - var prop = _a[_i]; - if (prop.kind === 270 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { - continue; - } - var identifier = prop.name; - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - var currentKind = prop.kind === 268 /* PropertyAssignment */ || prop.kind === 269 /* ShorthandPropertyAssignment */ || prop.kind === 153 /* MethodDeclaration */ - ? 1 /* Property */ - : 2 /* Accessor */; - var existingKind = seen.get(identifier.escapedText); - if (!existingKind) { - seen.set(identifier.escapedText, currentKind); - continue; - } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span_1 = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_1.start, span_1.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); - } - function bindJsxAttributes(node) { - return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); - } - function bindJsxAttribute(node, symbolFlags, symbolExcludes) { - return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function bindAnonymousDeclaration(node, symbolFlags, name) { - var symbol = createSymbol(symbolFlags, name); - if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { - symbol.parent = container.symbol; - } - addDeclarationToSymbol(symbol, node, symbolFlags); - } - function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { - switch (blockScopeContainer.kind) { - case 237 /* ModuleDeclaration */: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case 272 /* SourceFile */: - if (ts.isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // falls through - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = ts.createSymbolTable(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); - } - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node) { - if (inStrictMode && - node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && - node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && - !ts.isIdentifierName(node) && - !(node.flags & 2097152 /* Ambient */)) { - // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); - } - } - } - function getStrictModeIdentifierMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - function checkStrictModeBinaryExpression(node) { - if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - function checkStrictModeCatchClause(node) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - function checkStrictModeDeleteExpression(node) { - // Grammar checking - if (inStrictMode && node.expression.kind === 71 /* Identifier */) { - // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its - // UnaryExpression is a direct reference to a variable, function argument, or function name - var span_2 = ts.getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_2.start, span_2.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - function isEvalOrArgumentsIdentifier(node) { - return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); - } - function checkStrictModeEvalOrArguments(contextNode, name) { - if (name && name.kind === 71 /* Identifier */) { - var identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var span_3 = ts.getErrorSpanForNode(file, name); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span_3.start, span_3.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); - } - } - } - function getStrictModeEvalOrArgumentsMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; - } - function checkStrictModeFunctionName(node) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - function getStrictModeBlockScopeFunctionDeclarationMessage(node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (ts.getContainingClass(node)) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - if (file.externalModuleIndicator) { - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - function checkStrictModeFunctionDeclaration(node) { - if (languageVersion < 2 /* ES2015 */) { - // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== 272 /* SourceFile */ && - blockScopeContainer.kind !== 237 /* ModuleDeclaration */ && - !ts.isFunctionLike(blockScopeContainer)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - var errorSpan = ts.getErrorSpanForNode(file, node); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - function checkStrictModePostfixUnaryExpression(node) { - // Grammar checking - // The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression - // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - function checkStrictModePrefixUnaryExpression(node) { - // Grammar checking - if (inStrictMode) { - if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - function checkStrictModeWithStatement(node) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - function errorOnFirstToken(node, message, arg0, arg1, arg2) { - var span = ts.getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - function bind(node) { - if (!node) { - return; - } - node.parent = parent; - var saveInStrictMode = inStrictMode; - // Even though in the AST the jsdoc @typedef node belongs to the current node, - // its symbol might be in the same scope with the current node's symbol. Consider: - // - // /** @typedef {string | number} MyType */ - // function foo(); - // - // Here the current node is "foo", which is a container, but the scope of "MyType" should - // not be inside "foo". Therefore we always bind @typedef before bind the parent node, - // and skip binding this tag later when binding all the other jsdoc tags. - if (ts.isInJavaScriptFile(node)) - bindJSDocTypedefTagIfAny(node); - // First we bind declaration nodes to a symbol if possible. We'll both create a symbol - // and then potentially add the symbol to an appropriate symbol table. Possible - // destination symbol tables are: - // - // 1) The 'exports' table of the current container's symbol. - // 2) The 'members' table of the current container's symbol. - // 3) The 'locals' table of the current container. - // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols - // (like TypeLiterals for example) will not be put in any table. - bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain - // symbols we do specialized work when we recurse. For example, we'll keep track of - // the current 'container' node when it changes. This helps us know which symbol table - // a local should go into for example. Since terminal nodes are known not to have - // children, as an optimization we don't process those. - if (node.kind > 144 /* LastToken */) { - var saveParent = parent; - parent = node; - var containerFlags = getContainerFlags(node); - if (containerFlags === 0 /* None */) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - function bindJSDocTypedefTagIfAny(node) { - if (!ts.hasJSDocNodes(node)) { - return; - } - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var jsDoc = _a[_i]; - if (!jsDoc.tags) { - continue; - } - for (var _b = 0, _c = jsDoc.tags; _b < _c.length; _b++) { - var tag = _c[_b]; - if (tag.kind === 291 /* JSDocTypedefTag */) { - var savedParent = parent; - parent = jsDoc; - bind(tag); - parent = savedParent; - } - } - } - } - function updateStrictModeStatementList(statements) { - if (!inStrictMode) { - for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { - var statement = statements_1[_i]; - if (!ts.isPrologueDirective(statement)) { - return; - } - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node) { - var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - function bindWorker(node) { - switch (node.kind) { - /* Strict mode checks */ - case 71 /* Identifier */: - // for typedef type names with namespaces, bind the new jsdoc type symbol here - // because it requires all containing namespaces to be in effect, namely the - // current "blockScopeContainer" needs to be set to its immediate namespace parent. - if (node.isInJSDocNamespace) { - var parentNode = node.parent; - while (parentNode && parentNode.kind !== 291 /* JSDocTypedefTag */) { - parentNode = parentNode.parent; - } - bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - break; - } - // falls through - case 99 /* ThisKeyword */: - if (currentFlow && (ts.isExpression(node) || parent.kind === 269 /* ShorthandPropertyAssignment */)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case 183 /* PropertyAccessExpression */: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - if (ts.isSpecialPropertyDeclaration(node)) { - bindSpecialPropertyDeclaration(node); - } - break; - case 198 /* BinaryExpression */: - var specialKind = ts.getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case 1 /* ExportsProperty */: - bindExportsPropertyAssignment(node); - break; - case 2 /* ModuleExports */: - bindModuleExportsAssignment(node); - break; - case 3 /* PrototypeProperty */: - bindPrototypePropertyAssignment(node.left, node); - break; - case 6 /* Prototype */: - bindPrototypeAssignment(node); - break; - case 4 /* ThisProperty */: - bindThisPropertyAssignment(node); - break; - case 5 /* Property */: - bindSpecialPropertyAssignment(node); - break; - case 0 /* None */: - // Nothing to do - break; - default: - ts.Debug.fail("Unknown special property assignment kind"); - } - return checkStrictModeBinaryExpression(node); - case 267 /* CatchClause */: - return checkStrictModeCatchClause(node); - case 192 /* DeleteExpression */: - return checkStrictModeDeleteExpression(node); - case 8 /* NumericLiteral */: - return checkStrictModeNumericLiteral(node); - case 197 /* PostfixUnaryExpression */: - return checkStrictModePostfixUnaryExpression(node); - case 196 /* PrefixUnaryExpression */: - return checkStrictModePrefixUnaryExpression(node); - case 224 /* WithStatement */: - return checkStrictModeWithStatement(node); - case 173 /* ThisType */: - seenThisKeyword = true; - return; - case 160 /* TypePredicate */: - break; // Binding the children will handle everything - case 147 /* TypeParameter */: - return bindTypeParameter(node); - case 148 /* Parameter */: - return bindParameter(node); - case 230 /* VariableDeclaration */: - return bindVariableDeclarationOrBindingElement(node); - case 180 /* BindingElement */: - node.flowNode = currentFlow; - return bindVariableDeclarationOrBindingElement(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return bindPropertyWorker(node); - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); - case 271 /* EnumMember */: - return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); - case 232 /* FunctionDeclaration */: - return bindFunctionDeclaration(node); - case 154 /* Constructor */: - return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); - case 155 /* GetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); - case 156 /* SetAccessor */: - return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); - case 162 /* FunctionType */: - case 280 /* JSDocFunctionType */: - case 163 /* ConstructorType */: - return bindFunctionOrConstructorType(node); - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 176 /* MappedType */: - return bindAnonymousTypeWorker(node); - case 182 /* ObjectLiteralExpression */: - return bindObjectLiteralExpression(node); - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return bindFunctionExpression(node); - case 185 /* CallExpression */: - if (ts.isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - // Members of classes, interfaces, and modules - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return bindClassLikeDeclaration(node); - case 234 /* InterfaceDeclaration */: - return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); - case 235 /* TypeAliasDeclaration */: - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - case 236 /* EnumDeclaration */: - return bindEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return bindModuleDeclaration(node); - // Jsx-attributes - case 261 /* JsxAttributes */: - return bindJsxAttributes(node); - case 260 /* JsxAttribute */: - return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); - // Imports and exports - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: - return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - case 240 /* NamespaceExportDeclaration */: - return bindNamespaceExportDeclaration(node); - case 243 /* ImportClause */: - return bindImportClause(node); - case 248 /* ExportDeclaration */: - return bindExportDeclaration(node); - case 247 /* ExportAssignment */: - return bindExportAssignment(node); - case 272 /* SourceFile */: - updateStrictModeStatementList(node.statements); - return bindSourceFileIfExternalModule(); - case 211 /* Block */: - if (!ts.isFunctionLike(node.parent)) { - return; - } - // falls through - case 238 /* ModuleBlock */: - return updateStrictModeStatementList(node.statements); - case 287 /* JSDocParameterTag */: - if (node.parent.kind !== 283 /* JSDocTypeLiteral */) { - break; - } - // falls through - case 292 /* JSDocPropertyTag */: - var propTag = node; - var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 279 /* JSDocOptionalType */ ? - 4 /* Property */ | 16777216 /* Optional */ : - 4 /* Property */; - return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); - case 291 /* JSDocTypedefTag */: { - var fullName = node.fullName; - if (!fullName || fullName.kind === 71 /* Identifier */) { - return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); - } - break; - } - } - } - function bindPropertyWorker(node) { - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - function bindAnonymousTypeWorker(node) { - return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); - } - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (ts.isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); - } - function bindExportAssignment(node) { - if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); - } - else { - var flags = node.kind === 247 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) - // An export default clause with an EntityNameExpression exports all meanings of that identifier - ? 2097152 /* Alias */ - // An export default clause with any other expression exports a value - : 4 /* Property */; - // If there is an `export default x;` alias declaration, can't `export default` anything else. - // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); - } - } - function bindNamespaceExportDeclaration(node) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); - } - if (node.parent.kind !== 272 /* SourceFile */) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - var parent_1 = node.parent; - if (!ts.isExternalModule(parent_1)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - if (!parent_1.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); - declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - } - function bindExportDeclaration(node) { - if (!container.symbol || !container.symbol.exports) { - // Export * in some sort of block construct - bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); - } - else if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); - } - } - function bindImportClause(node) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); - } - } - function setCommonJsModuleIndicator(node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - if (!file.externalModuleIndicator) { - bindSourceFileAsExternalModule(); - } - } - } - function bindExportsPropertyAssignment(node) { - // When we create a property via 'exports.foo = bar', the 'exports.foo' property access - // expression is the declaration - setCommonJsModuleIndicator(node); - var lhs = node.left; - var symbol = forEachIdentifierInEntityName(lhs.expression, function (id, original) { - if (!original) { - return undefined; - } - var s = ts.getJSInitializerSymbol(original); - addDeclarationToSymbol(s, id, 1536 /* Module */ | 67108864 /* JSContainer */); - return s; - }); - if (symbol) { - declareSymbol(symbol.exports, symbol, lhs, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */); - } - } - function bindModuleExportsAssignment(node) { - // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' - // is still pointing to 'module.exports'. - // We do not want to consider this as 'export=' since a module can have only one of these. - // Similarly we do not want to treat 'module.exports = exports' as an 'export='. - var assignedExpression = ts.getRightMostAssignedExpression(node.right); - if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { - // Mark it as a module in case there are no other exports in the file - setCommonJsModuleIndicator(node); - return; - } - // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */, 0 /* None */); - } - function bindThisPropertyAssignment(node) { - ts.Debug.assert(ts.isInJavaScriptFile(node)); - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - switch (container.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - // Declare a 'member' if the container is an ES5 class or ES6 constructor - container.symbol.members = container.symbol.members || ts.createSymbolTable(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); - break; - case 154 /* Constructor */: - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - var containingClass = container.parent; - var symbolTable = ts.hasModifier(container, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; - declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); - break; - } - } - function bindSpecialPropertyDeclaration(node) { - if (node.expression.kind === 99 /* ThisKeyword */) { - bindThisPropertyAssignment(node); - } - else if (ts.isEntityNameExpression(node) && node.parent.parent.kind === 272 /* SourceFile */) { - if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.escapedText === "prototype") { - bindPrototypePropertyAssignment(node, node.parent); - } - else { - bindStaticPropertyAssignment(node); - } - } - } - /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ - function bindPrototypeAssignment(node) { - node.left.parent = node; - node.right.parent = node; - var lhs = node.left; - bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); - } - /** - * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. - * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. - */ - function bindPrototypePropertyAssignment(lhs, parent) { - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - var classPrototype = lhs.expression; - var constructorFunction = classPrototype.expression; - // Fix up parent pointers since we're going to use these nodes before we bind into them - lhs.parent = parent; - constructorFunction.parent = classPrototype; - classPrototype.parent = lhs; - bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); - } - function bindSpecialPropertyAssignment(node) { - var lhs = node.left; - // Fix up parent pointers since we're going to use these nodes before we bind into them - node.left.parent = node; - node.right.parent = node; - if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { - // This can be an alias for the 'exports' or 'module.exports' names, e.g. - // var util = module.exports; - // util.property = function ... - bindExportsPropertyAssignment(node); - } - else { - bindStaticPropertyAssignment(lhs); - } - } - /** - * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. - * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; - */ - function bindStaticPropertyAssignment(node) { - node.expression.parent = node; - bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); - } - function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { - var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(name)); - var isToplevelNamespaceableInitializer; - if (ts.isBinaryExpression(propertyAccess.parent)) { - var isPrototypeAssignment = ts.isPropertyAccessExpression(propertyAccess.parent.left) && propertyAccess.parent.left.name.escapedText === "prototype"; - isToplevelNamespaceableInitializer = propertyAccess.parent.parent.parent.kind === 272 /* SourceFile */ && - !!ts.getJavascriptInitializer(propertyAccess.parent.right, isPrototypeAssignment); - } - else { - isToplevelNamespaceableInitializer = propertyAccess.parent.parent.kind === 272 /* SourceFile */; - } - if (!isPrototypeProperty && (!symbol || !(symbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { - // make symbols or add declarations for intermediate containers - var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; - var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; - forEachIdentifierInEntityName(propertyAccess.expression, function (id, original) { - if (original) { - // Note: add declaration to original symbol, not the special-syntax's symbol, so that namespaces work for type lookup - addDeclarationToSymbol(original, id, flags_1); - return original; - } - else { - return symbol = declareSymbol(symbol ? symbol.exports : container.locals, symbol, id, flags_1, excludeFlags_1); - } - }); - } - if (!symbol || !(symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */ | 4096 /* ObjectLiteral */))) { - return; - } - // Set up the members collection if it doesn't exist already - var symbolTable = isPrototypeProperty ? - (symbol.members || (symbol.members = ts.createSymbolTable())) : - (symbol.exports || (symbol.exports = ts.createSymbolTable())); - // Declare the method/property - var symbolFlags = 4 /* Property */ | (isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); - var symbolExcludes = 0 /* PropertyExcludes */ & ~(isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0); - declareSymbol(symbolTable, symbol, propertyAccess, symbolFlags, symbolExcludes); - } - function lookupSymbolForPropertyAccess(node) { - if (ts.isIdentifier(node)) { - return lookupSymbolForNameWorker(container, node.escapedText); - } - else { - var symbol = ts.getJSInitializerSymbol(lookupSymbolForPropertyAccess(node.expression)); - return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); - } - } - function forEachIdentifierInEntityName(e, action) { - if (isExportsOrModuleExportsOrAlias(file, e)) { - return file.symbol; - } - else if (ts.isIdentifier(e)) { - return action(e, lookupSymbolForPropertyAccess(e)); - } - else { - var s = ts.getJSInitializerSymbol(forEachIdentifierInEntityName(e.expression, action)); - ts.Debug.assert(!!s && !!s.exports); - return action(e.name, s.exports.get(e.name.escapedText)); - } - } - function bindCallExpression(node) { - // We're only inspecting call expressions to detect CommonJS modules, so we can skip - // this check if we've already seen the module indicator - if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) { - setCommonJsModuleIndicator(node); - } - } - function bindClassLikeDeclaration(node) { - if (node.kind === 233 /* ClassDeclaration */) { - bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); - } - else { - var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; - bindAnonymousDeclaration(node, 32 /* Class */, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames.set(node.name.escapedText, true); - } - } - var symbol = node.symbol; - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); - var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); - if (symbolExport) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); - } - symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); - prototypeSymbol.parent = symbol; - } - function bindEnumDeclaration(node) { - return ts.isConst(node) - ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) - : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); - } - function bindVariableDeclarationOrBindingElement(node) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - if (!ts.isBindingPattern(node.name)) { - if (ts.isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (ts.isParameterDeclaration(node)) { - // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration - // because its parent chain has already been set up, since parents are set before descending into children. - // - // If node is a binding element in parameter declaration, we need to use ParameterExcludes. - // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration - // For example: - // function foo([a,a]) {} // Duplicate Identifier error - // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter - // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); - } - } - } - function bindParameter(node) { - if (inStrictMode && !(node.flags & 2097152 /* Ambient */)) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) - checkStrictModeEvalOrArguments(node, node.name); - } - if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); - } - // If this is a property-parameter, then also declare the property symbol into the - // containing class. - if (ts.isParameterPropertyDeclaration(node)) { - var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); - } - } - function bindFunctionDeclaration(node) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); - } - else { - declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); - } - } - function bindFunctionExpression(node) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */)) { - if (ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; - return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); - } - function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { - if (!file.isDeclarationFile && !(node.flags & 2097152 /* Ambient */) && ts.isAsyncFunction(node)) { - emitFlags |= 1024 /* HasAsyncFunctions */; - } - if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - return ts.hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - function getInferTypeContainer(node) { - while (node) { - var parent_2 = node.parent; - if (parent_2 && parent_2.kind === 170 /* ConditionalType */ && parent_2.extendsType === node) { - return parent_2; - } - node = parent_2; - } - return undefined; - } - function bindTypeParameter(node) { - if (node.parent.kind === 171 /* InferType */) { - var container_1 = getInferTypeContainer(node.parent); - if (container_1) { - if (!container_1.locals) { - container_1.locals = ts.createSymbolTable(); - } - declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); - } - else { - bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); - } - } - else { - declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); - } - } - // reachability checks - function shouldReportErrorOnModuleDeclaration(node) { - var instanceState = getModuleInstanceState(node); - return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); - } - function checkUnreachable(node) { - if (!(currentFlow.flags & 1 /* Unreachable */)) { - return false; - } - if (currentFlow === unreachableFlow) { - var reportError = - // report error on all statements except empty ones - (ts.isStatementButNotDeclaration(node) && node.kind !== 213 /* EmptyStatement */) || - // report error on class declarations - node.kind === 233 /* ClassDeclaration */ || - // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === 237 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (node.kind === 236 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); - if (reportError) { - currentFlow = reportedUnreachableFlow; - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - var reportUnreachableCode = !options.allowUnreachableCode && - !(node.flags & 2097152 /* Ambient */) && - (node.kind !== 212 /* VariableStatement */ || - ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */ || - ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); - if (reportUnreachableCode) { - errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); - } - } - } + if (lhs.kind === 99 /* ThisKeyword */) { return true; } + // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only + // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression + // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element + return lhs.name.escapedText === rhs.name.escapedText && + tagNamesAreEquivalent(lhs.expression, rhs.expression); } - /* @internal */ - function isExportsOrModuleExportsOrAlias(sourceFile, node) { - return ts.isExportsIdentifier(node) || - ts.isModuleExportsPropertyAccessExpression(node) || - ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); - } - ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; - function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { - var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); - return symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && - symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); - } - function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { - return isExportsOrModuleExportsOrAlias(sourceFile, node) || - (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); - } - function lookupSymbolForNameWorker(container, name) { - var local = container.locals && container.locals.get(name); - if (local) { - return local.exportSymbol || local; - } - return container.symbol && container.symbol.exports && container.symbol.exports.get(name); - } - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - function computeTransformFlagsForNode(node, subtreeFlags) { - var kind = node.kind; - switch (kind) { - case 185 /* CallExpression */: - return computeCallExpression(node, subtreeFlags); - case 186 /* NewExpression */: - return computeNewExpression(node, subtreeFlags); - case 237 /* ModuleDeclaration */: - return computeModuleDeclaration(node, subtreeFlags); - case 189 /* ParenthesizedExpression */: - return computeParenthesizedExpression(node, subtreeFlags); - case 198 /* BinaryExpression */: - return computeBinaryExpression(node, subtreeFlags); - case 214 /* ExpressionStatement */: - return computeExpressionStatement(node, subtreeFlags); - case 148 /* Parameter */: - return computeParameter(node, subtreeFlags); - case 191 /* ArrowFunction */: - return computeArrowFunction(node, subtreeFlags); - case 190 /* FunctionExpression */: - return computeFunctionExpression(node, subtreeFlags); - case 232 /* FunctionDeclaration */: - return computeFunctionDeclaration(node, subtreeFlags); - case 230 /* VariableDeclaration */: - return computeVariableDeclaration(node, subtreeFlags); - case 231 /* VariableDeclarationList */: - return computeVariableDeclarationList(node, subtreeFlags); - case 212 /* VariableStatement */: - return computeVariableStatement(node, subtreeFlags); - case 226 /* LabeledStatement */: - return computeLabeledStatement(node, subtreeFlags); - case 233 /* ClassDeclaration */: - return computeClassDeclaration(node, subtreeFlags); - case 203 /* ClassExpression */: - return computeClassExpression(node, subtreeFlags); - case 266 /* HeritageClause */: - return computeHeritageClause(node, subtreeFlags); - case 267 /* CatchClause */: - return computeCatchClause(node, subtreeFlags); - case 205 /* ExpressionWithTypeArguments */: - return computeExpressionWithTypeArguments(node, subtreeFlags); - case 154 /* Constructor */: - return computeConstructor(node, subtreeFlags); - case 151 /* PropertyDeclaration */: - return computePropertyDeclaration(node, subtreeFlags); - case 153 /* MethodDeclaration */: - return computeMethod(node, subtreeFlags); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return computeAccessor(node, subtreeFlags); - case 241 /* ImportEqualsDeclaration */: - return computeImportEquals(node, subtreeFlags); - case 183 /* PropertyAccessExpression */: - return computePropertyAccess(node, subtreeFlags); - case 184 /* ElementAccessExpression */: - return computeElementAccess(node, subtreeFlags); - default: - return computeOther(node, kind, subtreeFlags); - } - } - ts.computeTransformFlagsForNode = computeTransformFlagsForNode; - function computeCallExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */ - || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { - // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 268435456 /* ContainsSuper */) { - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - if (expression.kind === 91 /* ImportKeyword */) { - transformFlags |= 67108864 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeNewExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadElementExpression then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; - } - function computeBinaryExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var operatorTokenKind = node.operatorToken.kind; - var leftKind = node.left.kind; - if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 182 /* ObjectLiteralExpression */) { - // Destructuring object assignments with are ES2015 syntax - // and possibly ESNext if they contain rest - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 181 /* ArrayLiteralExpression */) { - // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; - } - else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ - || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { - // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeParameter(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var name = node.name; - var initializer = node.initializer; - var dotDotDotToken = node.dotDotDotToken; - // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript - // syntax. - if (node.questionToken - || node.type - || subtreeFlags & 4096 /* ContainsDecorators */ - || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; - } - // parameters with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a parameter has an initializer, a binding pattern or a dotDotDot token, then - // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* ParameterExcludes */; - } - function computeParenthesizedExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (expressionKind === 206 /* AsExpression */ - || expressionKind === 188 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; - } - function computeClassDeclaration(node, subtreeFlags) { - var transformFlags; - if (ts.hasModifier(node, 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - // An exported declaration may be TypeScript syntax, but is handled by the visitor - // for a namespace declaration. - if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; - } - function computeClassExpression(node, subtreeFlags) { - // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ - || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~942011713 /* ClassExcludes */; - } - function computeHeritageClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - switch (node.token) { - case 85 /* ExtendsKeyword */: - // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 108 /* ImplementsKeyword */: - // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - default: - ts.Debug.fail("Unexpected token for heritage clause"); - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeCatchClause(node, subtreeFlags) { - var transformFlags = subtreeFlags; - if (!node.variableDeclaration) { - transformFlags |= 8 /* AssertESNext */; - } - else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~940574017 /* CatchClauseExcludes */; - } - function computeExpressionWithTypeArguments(node, subtreeFlags) { - // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the - // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // If an ExpressionWithTypeArguments contains type arguments, then it - // is TypeScript syntax. - if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeConstructor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers and overloads are TypeScript syntax - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* ConstructorExcludes */; - } - function computeMethod(node, subtreeFlags) { - // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and - // overloads are TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type - || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // An async method declaration is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; - } - function computeAccessor(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // Decorators, TypeScript-specific modifiers, type annotations, and overloads are - // TypeScript syntax. - if (node.decorators - || ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.type - || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly - || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; - } - function computePropertyDeclaration(node, subtreeFlags) { - // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; - // If the PropertyDeclaration has an initializer, we need to inform its ancestor - // so that it handle the transformation. - if (node.initializer) { - transformFlags |= 8192 /* ContainsPropertyInitializer */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeFunctionDeclaration(node, subtreeFlags) { - var transformFlags; - var modifierFlags = ts.getModifierFlags(node); - var body = node.body; - if (!body || (modifierFlags & 2 /* Ambient */)) { - // An ambient declaration is TypeScript syntax. - // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (modifierFlags & 2270 /* TypeScriptModifier */ - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function declaration is ES2017 syntax. - if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function declarations with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionDeclaration is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; - } - function computeFunctionExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async function expression is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; - } - // function expressions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a FunctionExpression is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003935041 /* FunctionExcludes */; - } - function computeArrowFunction(node, subtreeFlags) { - // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) - || node.typeParameters - || node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - // An async arrow function is ES2017 syntax. - if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; - } - // arrow functions with object rest destructuring are ES Next syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - transformFlags |= 32768 /* ContainsCapturedLexicalThis */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; - } - function computePropertyAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If a PropertyAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 134217728 /* Super */) { - transformFlags ^= 134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; - } - function computeElementAccess(node, subtreeFlags) { - var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing - // If an ElementAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 134217728 /* Super */) { - transformFlags &= ~134217728 /* Super */; - transformFlags |= 268435456 /* ContainsSuper */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~671089985 /* PropertyAccessExcludes */; - } - function computeVariableDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - // A VariableDeclaration containing ObjectRest is ESNext syntax - if (subtreeFlags & 1048576 /* ContainsObjectRest */) { - transformFlags |= 8 /* AssertESNext */; - } - // Type annotations are TypeScript syntax. - if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeVariableStatement(node, subtreeFlags) { - var transformFlags; - var declarationListTransformFlags = node.declarationList.transformFlags; - // An ambient declaration is TypeScript syntax. - if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; - } - else { - transformFlags = subtreeFlags; - if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeLabeledStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ - && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeImportEquals(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // An ImportEqualsDeclaration with a namespace reference is TypeScript. - if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeExpressionStatement(node, subtreeFlags) { - var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~939525441 /* NodeExcludes */; - } - function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; - var modifierFlags = ts.getModifierFlags(node); - if ((modifierFlags & 2 /* Ambient */) === 0) { - transformFlags |= subtreeFlags; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~977327425 /* ModuleExcludes */; - } - function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; - } - // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. - if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; - } - function computeOther(node, kind, subtreeFlags) { - // Mark transformations needed for each node - var transformFlags = subtreeFlags; - var excludeFlags = 939525441 /* NodeExcludes */; - switch (kind) { - case 120 /* AsyncKeyword */: - case 195 /* AwaitExpression */: - // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) - transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; - break; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 295 /* PartiallyEmittedExpression */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; - break; - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 117 /* AbstractKeyword */: - case 124 /* DeclareKeyword */: - case 76 /* ConstKeyword */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 207 /* NonNullExpression */: - case 132 /* ReadonlyKeyword */: - // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - break; - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: - case 10 /* JsxText */: - case 256 /* JsxClosingElement */: - case 257 /* JsxFragment */: - case 258 /* JsxOpeningFragment */: - case 259 /* JsxClosingFragment */: - case 260 /* JsxAttribute */: - case 261 /* JsxAttributes */: - case 262 /* JsxSpreadAttribute */: - case 263 /* JsxExpression */: - // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; - break; - case 13 /* NoSubstitutionTemplateLiteral */: - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - case 200 /* TemplateExpression */: - case 187 /* TaggedTemplateExpression */: - case 269 /* ShorthandPropertyAssignment */: - case 115 /* StaticKeyword */: - case 208 /* MetaProperty */: - // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; - break; - case 9 /* StringLiteral */: - if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 8 /* NumericLiteral */: - if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 220 /* ForOfStatement */: - // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). - if (node.awaitModifier) { - transformFlags |= 8 /* AssertESNext */; - } - transformFlags |= 192 /* AssertES2015 */; - break; - case 201 /* YieldExpression */: - // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async - // generator). - transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; - break; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 135 /* ObjectKeyword */: - case 137 /* StringKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 147 /* TypeParameter */: - case 150 /* PropertySignature */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 160 /* TypePredicate */: - case 161 /* TypeReference */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 164 /* TypeQuery */: - case 165 /* TypeLiteral */: - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 170 /* ConditionalType */: - case 171 /* InferType */: - case 172 /* ParenthesizedType */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 173 /* ThisType */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 177 /* LiteralType */: - case 240 /* NamespaceExportDeclaration */: - // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; - break; - case 146 /* ComputedPropertyName */: - // Even though computed property names are ES6, we don't treat them as such. - // This is so that they can flow through PropertyName transforms unaffected. - // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 2097152 /* ContainsComputedPropertyName */; - if (subtreeFlags & 16384 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; - } - break; - case 202 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; - break; - case 270 /* SpreadAssignment */: - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; - break; - case 97 /* SuperKeyword */: - // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` - break; - case 99 /* ThisKeyword */: - // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 16384 /* ContainsLexicalThis */; - break; - case 178 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - if (subtreeFlags & 524288 /* ContainsRest */) { - transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; - } - excludeFlags = 940049729 /* BindingPatternExcludes */; - break; - case 179 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 940049729 /* BindingPatternExcludes */; - break; - case 180 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; - if (node.dotDotDotToken) { - transformFlags |= 524288 /* ContainsRest */; - } - break; - case 149 /* Decorator */: - // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; - break; - case 182 /* ObjectLiteralExpression */: - excludeFlags = 942740801 /* ObjectLiteralExcludes */; - if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { - // If an ObjectLiteralExpression contains a ComputedPropertyName, then it - // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; - } - if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 16384 /* ContainsLexicalThis */; - } - if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { - // If an ObjectLiteralExpression contains a spread element, then it - // is an ES next node. - transformFlags |= 8 /* AssertESNext */; - } - break; - case 181 /* ArrayLiteralExpression */: - case 186 /* NewExpression */: - excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 524288 /* ContainsSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 272 /* SourceFile */: - if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } - break; - case 223 /* ReturnStatement */: - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: - transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; - break; - } - node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~excludeFlags; - } - /** - * Gets the transform flags to exclude when unioning the transform flags of a subtree. - * - * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. - * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather - * than calling this function. - */ - /* @internal */ - function getTransformFlagsSubtreeExclusions(kind) { - if (kind >= 160 /* FirstTypeNode */ && kind <= 177 /* LastTypeNode */) { - return -3 /* TypeExcludes */; - } - switch (kind) { - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 181 /* ArrayLiteralExpression */: - return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; - case 237 /* ModuleDeclaration */: - return 977327425 /* ModuleExcludes */; - case 148 /* Parameter */: - return 939525441 /* ParameterExcludes */; - case 191 /* ArrowFunction */: - return 1003902273 /* ArrowFunctionExcludes */; - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - return 1003935041 /* FunctionExcludes */; - case 231 /* VariableDeclarationList */: - return 948962625 /* VariableDeclarationListExcludes */; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - return 942011713 /* ClassExcludes */; - case 154 /* Constructor */: - return 1003668801 /* ConstructorExcludes */; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return 1003668801 /* MethodOrAccessorExcludes */; - case 119 /* AnyKeyword */: - case 134 /* NumberKeyword */: - case 131 /* NeverKeyword */: - case 137 /* StringKeyword */: - case 135 /* ObjectKeyword */: - case 122 /* BooleanKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 147 /* TypeParameter */: - case 150 /* PropertySignature */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; - case 182 /* ObjectLiteralExpression */: - return 942740801 /* ObjectLiteralExcludes */; - case 267 /* CatchClause */: - return 940574017 /* CatchClauseExcludes */; - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: - return 940049729 /* BindingPatternExcludes */; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 295 /* PartiallyEmittedExpression */: - case 189 /* ParenthesizedExpression */: - case 97 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: - return 671089985 /* PropertyAccessExcludes */; - default: - return 939525441 /* NodeExcludes */; - } - } - ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; - /** - * "Binds" JSDoc nodes in TypeScript code. - * Since we will never create symbols for JSDoc, we just set parent pointers instead. - */ - function setParentPointers(parent, child) { - child.parent = parent; - ts.forEachChild(child, function (childsChild) { return setParentPointers(child, childsChild); }); - } + ts.tagNamesAreEquivalent = tagNamesAreEquivalent; })(ts || (ts = {})); -/** @internal */ var ts; (function (ts) { - function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier) { - return getSymbolWalker; - function getSymbolWalker(accept) { - if (accept === void 0) { accept = function () { return true; }; } - var visitedTypes = []; // Sparse array from id to type - var visitedSymbols = []; // Sparse array from id to symbol + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; + // NOTE: The order here is important to default lib ordering as entries will have the same + // order in the generated program (see `getDefaultLibPriority` in program.ts). This + // order also affects overload resolution when a type declared in one lib is + // augmented in another lib. + var libEntries = [ + // JavaScript only + ["es5", "lib.es5.d.ts"], + ["es6", "lib.es2015.d.ts"], + ["es2015", "lib.es2015.d.ts"], + ["es7", "lib.es2016.d.ts"], + ["es2016", "lib.es2016.d.ts"], + ["es2017", "lib.es2017.d.ts"], + ["es2018", "lib.es2018.d.ts"], + ["esnext", "lib.esnext.d.ts"], + // Host only + ["dom", "lib.dom.d.ts"], + ["dom.iterable", "lib.dom.iterable.d.ts"], + ["webworker", "lib.webworker.d.ts"], + ["webworker.importscripts", "lib.webworker.importscripts.d.ts"], + ["scripthost", "lib.scripthost.d.ts"], + // ES2015 Or ESNext By-feature options + ["es2015.core", "lib.es2015.core.d.ts"], + ["es2015.collection", "lib.es2015.collection.d.ts"], + ["es2015.generator", "lib.es2015.generator.d.ts"], + ["es2015.iterable", "lib.es2015.iterable.d.ts"], + ["es2015.promise", "lib.es2015.promise.d.ts"], + ["es2015.proxy", "lib.es2015.proxy.d.ts"], + ["es2015.reflect", "lib.es2015.reflect.d.ts"], + ["es2015.symbol", "lib.es2015.symbol.d.ts"], + ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], + ["es2016.array.include", "lib.es2016.array.include.d.ts"], + ["es2017.object", "lib.es2017.object.d.ts"], + ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], + ["es2017.string", "lib.es2017.string.d.ts"], + ["es2017.intl", "lib.es2017.intl.d.ts"], + ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"], + ["es2018.intl", "lib.es2018.intl.d.ts"], + ["es2018.promise", "lib.es2018.promise.d.ts"], + ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.esnext.symbol.d.ts"], + ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"] + ]; + /** + * An array of supported "lib" reference file names used to determine the order for inclusion + * when referenced, as well as for spelling suggestions. This ensures the correct ordering for + * overload resolution when a type declared in one lib is extended by another. + */ + /* @internal */ + ts.libs = libEntries.map(function (entry) { return entry[0]; }); + /** + * A map of lib names to lib files. This map is used both for parsing the "lib" command line + * option as well as for resolving lib reference directives. + */ + /* @internal */ + ts.libMap = ts.createMapFromEntries(libEntries); + /* @internal */ + ts.optionDeclarations = [ + // CommandLine only options + { + name: "help", + shortName: "h", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_this_message, + }, + { + name: "help", + shortName: "?", + type: "boolean" + }, + { + name: "all", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Show_all_compiler_options, + }, + { + name: "version", + shortName: "v", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Print_the_compiler_s_version, + }, + { + name: "init", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, + }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + paramType: ts.Diagnostics.FILE_OR_DIRECTORY, + description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, + }, + { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date + }, + { + name: "pretty", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental + }, + { + name: "preserveWatchOutput", + type: "boolean", + showInSimplifiedHelpView: false, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + }, + { + name: "watch", + shortName: "w", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Command_line_Options, + description: ts.Diagnostics.Watch_input_files, + }, + // Basic + { + name: "target", + shortName: "t", + type: ts.createMapFromTemplate({ + es3: 0 /* ES3 */, + es5: 1 /* ES5 */, + es6: 2 /* ES2015 */, + es2015: 2 /* ES2015 */, + es2016: 3 /* ES2016 */, + es2017: 4 /* ES2017 */, + es2018: 5 /* ES2018 */, + esnext: 6 /* ESNext */, + }), + paramType: ts.Diagnostics.VERSION, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + }, + { + name: "module", + shortName: "m", + type: ts.createMapFromTemplate({ + none: ts.ModuleKind.None, + commonjs: ts.ModuleKind.CommonJS, + amd: ts.ModuleKind.AMD, + system: ts.ModuleKind.System, + umd: ts.ModuleKind.UMD, + es6: ts.ModuleKind.ES2015, + es2015: ts.ModuleKind.ES2015, + esnext: ts.ModuleKind.ESNext + }), + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, + }, + { + name: "lib", + type: "list", + element: { + name: "lib", + type: ts.libMap + }, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation + }, + { + name: "allowJs", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Allow_javascript_files_to_be_compiled + }, + { + name: "checkJs", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Report_errors_in_js_files + }, + { + name: "jsx", + type: ts.createMapFromTemplate({ + "preserve": 1 /* Preserve */, + "react-native": 3 /* ReactNative */, + "react": 2 /* React */ + }), + paramType: ts.Diagnostics.KIND, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, + }, + { + name: "declaration", + shortName: "d", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_d_ts_file, + }, + { + name: "declarationMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file, + }, + { + name: "emitDeclarationOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Only_emit_d_ts_declaration_files, + }, + { + name: "sourceMap", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Generates_corresponding_map_file, + }, + { + name: "outFile", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.FILE, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, + }, + { + name: "outDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Redirect_output_structure_to_the_directory, + }, + { + name: "rootDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, + }, + { + name: "composite", + type: "boolean", + isTSConfigOnly: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Enable_project_compilation, + }, + { + name: "removeComments", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_comments_to_output, + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Do_not_emit_outputs, + }, + { + name: "importHelpers", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "downlevelIteration", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 + }, + { + name: "isolatedModules", + type: "boolean", + category: ts.Diagnostics.Basic_Options, + description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule + }, + // Strict Type Checks + { + name: "strict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_all_strict_type_checking_options + }, + { + name: "noImplicitAny", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, + }, + { + name: "strictNullChecks", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_null_checks + }, + { + name: "strictFunctionTypes", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_function_types + }, + { + name: "strictPropertyInitialization", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes + }, + { + name: "noImplicitThis", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, + }, + { + name: "alwaysStrict", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Strict_Type_Checking_Options, + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file + }, + // Additional Checks + { + name: "noUnusedLocals", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_locals, + }, + { + name: "noUnusedParameters", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_on_unused_parameters, + }, + { + name: "noImplicitReturns", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Additional_Checks, + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + // Module Resolution + { + name: "moduleResolution", + type: ts.createMapFromTemplate({ + node: ts.ModuleResolutionKind.NodeJs, + classic: ts.ModuleResolutionKind.Classic, + }), + paramType: ts.Diagnostics.STRATEGY, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, + }, + { + name: "baseUrl", + type: "string", + isFilePath: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "paths", + type: "object", + isTSConfigOnly: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl + }, + { + // this option can only be specified in tsconfig.json + // use type = object to copy the value as-is + name: "rootDirs", + type: "list", + isTSConfigOnly: true, + element: { + name: "rootDirs", + type: "string", + isFilePath: true + }, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime + }, + { + name: "typeRoots", + type: "list", + element: { + name: "typeRoots", + type: "string", + isFilePath: true + }, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from + }, + { + name: "types", + type: "list", + element: { + name: "types", + type: "string" + }, + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation + }, + { + name: "allowSyntheticDefaultImports", + type: "boolean", + 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: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, + { + 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", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, + }, + { + name: "mapRoot", + type: "string", + paramType: ts.Diagnostics.LOCATION, + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, + }, + { + name: "inlineSourceMap", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file + }, + { + name: "inlineSources", + type: "boolean", + category: ts.Diagnostics.Source_Map_Options, + description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set + }, + // Experimental + { + name: "experimentalDecorators", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators + }, + { + name: "emitDecoratorMetadata", + type: "boolean", + category: ts.Diagnostics.Experimental_Options, + description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators + }, + // Advanced + { + name: "jsxFactory", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h + }, + { + name: "diagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_diagnostic_information + }, + { + name: "extendedDiagnostics", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Show_verbose_diagnostic_information + }, + { + name: "traceResolution", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process + }, + { + name: "resolveJsonModule", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Include_modules_imported_with_json_extension + }, + { + name: "listFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, + { + name: "out", + type: "string", + isFilePath: false, + // for correct behaviour, please use outFile + category: ts.Diagnostics.Advanced_Options, + paramType: ts.Diagnostics.FILE, + description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, + }, + { + name: "reactNamespace", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit + }, + { + name: "skipDefaultLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files + }, + { + name: "charset", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_character_set_of_the_input_files + }, + { + name: "emitBOM", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files + }, + { + name: "locale", + type: "string", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us + }, + { + name: "newLine", + type: ts.createMapFromTemplate({ + crlf: 0 /* CarriageReturnLineFeed */, + lf: 1 /* LineFeed */ + }), + paramType: ts.Diagnostics.NEWLINE, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + }, + { + name: "noErrorTruncation", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_truncate_error_messages + }, + { + name: "noLib", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts + }, + { + name: "noResolve", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files + }, + { + name: "stripInternal", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, + }, + { + name: "disableSizeLimit", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects + }, + { + name: "noImplicitUseStrict", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output + }, + { + name: "noEmitHelpers", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output + }, + { + name: "noEmitOnError", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, + }, + { + name: "preserveConstEnums", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code + }, + { + name: "declarationDir", + type: "string", + isFilePath: true, + paramType: ts.Diagnostics.DIRECTORY, + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Output_directory_for_generated_declaration_files + }, + { + name: "skipLibCheck", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Skip_type_checking_of_declaration_files, + }, + { + name: "allowUnusedLabels", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "allowUnreachableCode", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, + { + name: "suppressExcessPropertyErrors", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, + }, + { + name: "suppressImplicitAnyIndexErrors", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, + }, + { + name: "forceConsistentCasingInFileNames", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file + }, + { + name: "maxNodeModuleJsDepth", + type: "number", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files + }, + { + name: "noStrictGenericChecks", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, + }, + { + name: "keyofStringsOnly", + type: "boolean", + category: ts.Diagnostics.Advanced_Options, + description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols, + }, + { + // A list of plugins to load in the language service + name: "plugins", + type: "list", + isTSConfigOnly: true, + element: { + name: "plugin", + type: "object" + }, + description: ts.Diagnostics.List_of_language_service_plugins + } + ]; + /* @internal */ + ts.typeAcquisitionDeclarations = [ + { + /* @deprecated typingOptions.enableAutoDiscovery + * Use typeAcquisition.enable instead. + */ + name: "enableAutoDiscovery", + type: "boolean", + }, + { + name: "enable", + type: "boolean", + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + } + ]; + /* @internal */ + ts.defaultInitCompilerOptions = { + module: ts.ModuleKind.CommonJS, + target: 1 /* ES5 */, + strict: true, + esModuleInterop: true + }; + var optionNameMapCache; + /* @internal */ + function convertEnableAutoDiscoveryToEnable(typeAcquisition) { + // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable + if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { return { - walkType: function (type) { - try { - visitType(type); - return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; - } - finally { - ts.clear(visitedTypes); - ts.clear(visitedSymbols); - } - }, - walkSymbol: function (symbol) { - try { - visitSymbol(symbol); - return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; - } - finally { - ts.clear(visitedTypes); - ts.clear(visitedSymbols); - } - }, + enable: typeAcquisition.enableAutoDiscovery, + include: typeAcquisition.include || [], + exclude: typeAcquisition.exclude || [] }; - function visitType(type) { - if (!type) { - return; + } + return typeAcquisition; + } + ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; + function getOptionNameMap() { + if (optionNameMapCache) { + return optionNameMapCache; + } + var optionNameMap = ts.createMap(); + var shortOptionNames = ts.createMap(); + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap.set(option.name.toLowerCase(), option); + if (option.shortName) { + shortOptionNames.set(option.shortName, option.name); + } + }); + optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; + return optionNameMapCache; + } + /* @internal */ + function createCompilerDiagnosticForInvalidCustomType(opt) { + return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); + } + ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; + function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { + var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); + return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); + } + /* @internal */ + function parseCustomTypeOption(opt, value, errors) { + return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); + } + ts.parseCustomTypeOption = parseCustomTypeOption; + /* @internal */ + function parseListTypeOption(opt, value, errors) { + if (value === void 0) { value = ""; } + value = trimString(value); + if (ts.startsWith(value, "-")) { + return undefined; + } + if (value === "") { + return []; + } + var values = value.split(","); + switch (opt.element.type) { + case "number": + return ts.map(values, parseInt); + case "string": + return ts.map(values, function (v) { return v || ""; }); + default: + return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }); + } + } + ts.parseListTypeOption = parseListTypeOption; + function parseCommandLine(commandLine, readFile) { + var options = {}; + var fileNames = []; + var projectReferences = undefined; + var errors = []; + parseStrings(commandLine); + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + errors: errors + }; + function parseStrings(args) { + var i = 0; + while (i < args.length) { + var s = args[i]; + i++; + if (s.charCodeAt(0) === 64 /* at */) { + parseResponseFile(s.slice(1)); } - if (visitedTypes[type.id]) { - return; - } - visitedTypes[type.id] = 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 & 65536 /* Object */) { - var objectType = type; - var objectFlags = objectType.objectFlags; - if (objectFlags & 4 /* Reference */) { - visitTypeReference(type); + else if (s.charCodeAt(0) === 45 /* minus */) { + var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); + if (opt) { + if (opt.isTSConfigOnly) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); + } + else { + // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). + if (!args[i] && opt.type !== "boolean") { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + } + switch (opt.type) { + case "number": + options[opt.name] = parseInt(args[i]); + i++; + break; + case "boolean": + // boolean flag has optional value true, false, others + var optValue = args[i]; + options[opt.name] = optValue !== "false"; + // consume next argument as boolean flag value + if (optValue === "false" || optValue === "true") { + i++; + } + break; + case "string": + options[opt.name] = args[i] || ""; + i++; + break; + case "list": + var result = parseListTypeOption(opt, args[i], errors); + options[opt.name] = result || []; + if (result) { + i++; + } + break; + // If not a primitive, the possible types are specified in what is effectively a map of options. + default: + options[opt.name] = parseCustomTypeOption(opt, args[i], errors); + i++; + break; + } + } } - if (objectFlags & 32 /* Mapped */) { - visitMappedType(type); - } - if (objectFlags & (1 /* Class */ | 2 /* Interface */)) { - visitInterfaceType(type); - } - if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) { - visitObjectType(objectType); + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); } } - if (type.flags & 32768 /* TypeParameter */) { - visitTypeParameter(type); - } - if (type.flags & 393216 /* UnionOrIntersection */) { - visitUnionOrIntersectionType(type); - } - if (type.flags & 524288 /* Index */) { - visitIndexType(type); - } - if (type.flags & 1048576 /* IndexedAccess */) { - visitIndexedAccessType(type); + else { + fileNames.push(s); } } - function visitTypeReference(type) { - visitType(type.target); - ts.forEach(type.typeArguments, visitType); + } + function parseResponseFile(fileName) { + var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); + if (!text) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + return; } - function visitTypeParameter(type) { - visitType(getConstraintFromTypeParameter(type)); - } - function visitUnionOrIntersectionType(type) { - ts.forEach(type.types, visitType); - } - 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) { - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - visitType(typePredicate.type); + var args = []; + var pos = 0; + while (true) { + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) + pos++; + if (pos >= text.length) + break; + var start = pos; + if (text.charCodeAt(start) === 34 /* doubleQuote */) { + pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) + pos++; + if (pos < text.length) { + args.push(text.substring(start + 1, pos)); + pos++; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); + } } - ts.forEach(signature.typeParameters, visitType); - 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); - ts.forEach(interfaceT.typeParameters, visitType); - ts.forEach(getBaseTypes(interfaceT), visitType); - 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); + else { + while (text.charCodeAt(pos) > 32 /* space */) + pos++; + args.push(text.substring(start, pos)); } } - function visitSymbol(symbol) { - if (!symbol) { - return; + parseStrings(args); + } + } + ts.parseCommandLine = parseCommandLine; + /** @internal */ + function getOptionFromName(optionName, allowShort) { + if (allowShort === void 0) { allowShort = false; } + optionName = optionName.toLowerCase(); + var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; + // Try to translate short option names to their full equivalents. + if (allowShort) { + var short = shortOptionNames.get(optionName); + if (short !== undefined) { + optionName = short; + } + } + return optionNameMap.get(optionName); + } + ts.getOptionFromName = getOptionFromName; + function getDiagnosticText(_message) { + var _args = []; + for (var _i = 1; _i < arguments.length; _i++) { + _args[_i - 1] = arguments[_i]; + } + var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); + return diagnostic.messageText; + } + /* @internal */ + function printVersion() { + ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); + } + ts.printVersion = printVersion; + /* @internal */ + function printHelp(optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(ts.sys.newLine + ts.sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); + output.push(padding + "tsc @args.txt" + ts.sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); + output.push(ts.sys.newLine); + output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); } - var symbolId = ts.getSymbolId(symbol); - if (visitedSymbols[symbolId]) { - return; + output.push(ts.sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + ts.sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + ts.printHelp = printHelp; + /** + * Reads the config file, reports errors if any and exits if the config file cannot be found + */ + function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { + var configFileText; + try { + configFileText = host.readFile(configFileName); + } + catch (e) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + if (!configFileText) { + var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; + } + var result = ts.parseJsonText(configFileName, configFileText); + var cwd = host.getCurrentDirectory(); + return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + } + ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; + } + ts.readConfigFile = readConfigFile; + /** + * Parse the text of the tsconfig.json file + * @param fileName The path to the config file + * @param jsonText The text of the config file + */ + function parseConfigFileTextToJson(fileName, jsonText) { + var jsonSourceFile = ts.parseJsonText(fileName, jsonText); + return { + config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), + error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined + }; + } + ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Read tsconfig.json file + * @param fileName The path to the config file + */ + function readJsonConfigFile(fileName, readFile) { + var textOrDiagnostic = tryReadFile(fileName, readFile); + return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; + } + ts.readJsonConfigFile = readJsonConfigFile; + function tryReadFile(fileName, readFile) { + var text; + try { + text = readFile(fileName); + } + catch (e) { + return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); + } + return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; + } + function commandLineOptionsToMap(options) { + return ts.arrayToMap(options, function (option) { return option.name; }); + } + var _tsconfigRootOptions; + function getTsconfigRootOptionsMap() { + if (_tsconfigRootOptions === undefined) { + _tsconfigRootOptions = { + name: undefined, + type: "object", + elementOptions: commandLineOptionsToMap([ + { + name: "compilerOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.optionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 + }, + { + name: "typingOptions", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "typeAcquisition", + type: "object", + elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), + extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 + }, + { + name: "extends", + type: "string" + }, + { + name: "references", + type: "list", + element: { + name: "references", + type: "object" + } + }, + { + name: "files", + type: "list", + element: { + name: "files", + type: "string" + } + }, + { + name: "include", + type: "list", + element: { + name: "include", + type: "string" + } + }, + { + name: "exclude", + type: "list", + element: { + name: "exclude", + type: "string" + } + }, + ts.compileOnSaveCommandLineOption + ]) + }; + } + return _tsconfigRootOptions; + } + /** + * Convert the json syntax tree into the json value + */ + function convertToObject(sourceFile, errors) { + return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + } + ts.convertToObject = convertToObject; + /** + * Convert the json syntax tree into the json value and report errors + * This returns the json value (apart from checking errors) only if returnValue provided is true. + * Otherwise it just checks the errors and returns undefined + */ + /*@internal*/ + function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) { + if (!sourceFile.statements.length) { + return returnValue ? {} : undefined; + } + return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions); + function isRootOptionMap(knownOptions) { + return knownRootOptions && knownRootOptions.elementOptions === knownOptions; + } + function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { + var result = returnValue ? {} : undefined; + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var element = _a[_i]; + if (element.kind !== 273 /* PropertyAssignment */) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); + continue; } - visitedSymbols[symbolId] = symbol; - if (!accept(symbol)) { + if (element.questionToken) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + } + if (!isDoubleQuotedString(element.name)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); + } + var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); + var option = knownOptions ? knownOptions.get(keyText) : undefined; + if (extraKeyDiagnosticMessage && !option) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); + } + var value = convertPropertyValueToJson(element.initializer, option); + if (typeof keyText !== "undefined") { + if (returnValue) { + result[keyText] = value; + } + // Notify key value set, if user asked for it + if (jsonConversionNotifier && + // Current callbacks are only on known parent option or if we are setting values in the root + (parentOption || isRootOptionMap(knownOptions))) { + var isValidOptionValue = isCompilerOptionsValue(option, value); + if (parentOption) { + if (isValidOptionValue) { + // Notify option set in the parent if its a valid option value + jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); + } + } + else if (isRootOptionMap(knownOptions)) { + if (isValidOptionValue) { + // Notify about the valid root key value being set + jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + else if (!option) { + // Notify about the unknown root key value being set + jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); + } + } + } + } + } + return result; + } + function convertArrayLiteralExpressionToJson(elements, elementOption) { + return (returnValue ? elements.map : elements.forEach).call(elements, function (element) { return convertPropertyValueToJson(element, elementOption); }); + } + function convertPropertyValueToJson(valueExpression, option) { + switch (valueExpression.kind) { + case 101 /* TrueKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); 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 === 164 /* TypeQuery */) { - var query = d.type; - var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); - visitSymbol(entity); + case 86 /* FalseKeyword */: + reportInvalidOptionValue(option && option.type !== "boolean"); + return false; + case 95 /* NullKeyword */: + reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for + return null; // tslint:disable-line:no-null-keyword + case 9 /* StringLiteral */: + if (!isDoubleQuotedString(valueExpression)) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); } - }); + reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); + var text = valueExpression.text; + if (option && !ts.isString(option.type)) { + var customOption = option; + // Validate custom option type + if (!customOption.type.has(text.toLowerCase())) { + errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); + } + } + return text; + case 8 /* NumericLiteral */: + reportInvalidOptionValue(option && option.type !== "number"); + return Number(valueExpression.text); + case 200 /* PrefixUnaryExpression */: + if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { + break; // not valid JSON syntax + } + reportInvalidOptionValue(option && option.type !== "number"); + return -Number(valueExpression.operand.text); + case 186 /* ObjectLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "object"); + var objectLiteralExpression = valueExpression; + // Currently having element option declaration in the tsconfig with type "object" + // determines if it needs onSetValidOptionKeyValueInParent callback or not + // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" + // that satifies it and need it to modify options set in them (for normalizing file paths) + // vs what we set in the json + // If need arises, we can modify this interface and callbacks as needed + if (option) { + var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; + return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); + } + else { + return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, + /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); + } + case 185 /* ArrayLiteralExpression */: + reportInvalidOptionValue(option && option.type !== "list"); + return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); + } + // Not in expected format + if (option) { + reportInvalidOptionValue(/*isError*/ true); + } + else { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); + } + return undefined; + function reportInvalidOptionValue(isError) { + if (isError) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); + } + } + } + function isDoubleQuotedString(node) { + return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); + } + } + ts.convertToObjectWorker = convertToObjectWorker; + function getCompilerOptionValueTypeString(option) { + return option.type === "list" ? + "Array" : + ts.isString(option.type) ? option.type : "string"; + } + function isCompilerOptionsValue(option, value) { + if (option) { + if (isNullOrUndefined(value)) + return true; // All options are undefinable/nullable + if (option.type === "list") { + return ts.isArray(value); + } + var expectedType = ts.isString(option.type) ? option.type : "string"; + return typeof value === expectedType; + } + return false; + } + /** + * Generate tsconfig configuration when running command line "--init" + * @param options commandlineOptions to be generated into tsconfig.json + * @param fileNames array of filenames to be generated into tsconfig.json + */ + /* @internal */ + function generateTSConfig(options, fileNames, newLine) { + var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); + var compilerOptionsMap = serializeCompilerOptions(compilerOptions); + return writeConfigurations(); + function getCustomTypeMapOfCommandLineOption(optionDefinition) { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + // this is of a type CommandLineOptionOfPrimitiveType + return undefined; + } + else if (optionDefinition.type === "list") { + return getCustomTypeMapOfCommandLineOption(optionDefinition.element); + } + else { + return optionDefinition.type; + } + } + function getNameOfCompilerOptionValue(value, customTypeMap) { + // There is a typeMap associated with this command-line option so use it to map value back to its name + return ts.forEachEntry(customTypeMap, function (mapValue, key) { + if (mapValue === value) { + return key; + } + }); + } + function serializeCompilerOptions(options) { + var result = ts.createMap(); + var optionsNameMap = getOptionNameMap().optionNameMap; + var _loop_3 = function (name) { + if (ts.hasProperty(options, name)) { + // tsconfig only options cannot be specified via command line, + // so we can assume that only types that can appear here string | number | boolean + if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { + return "continue"; + } + var value = options[name]; + var optionDefinition = optionsNameMap.get(name.toLowerCase()); + if (optionDefinition) { + var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); + if (!customTypeMap_1) { + // There is no map associated with this compiler option then use the value as-is + // This is the case if the value is expect to be string, number, boolean or list of string + result.set(name, value); + } + else { + if (optionDefinition.type === "list") { + result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217 + } + else { + // There is a typeMap associated with this command-line option so use it to map value back to its name + result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); + } + } + } + } + }; + for (var name in options) { + _loop_3(name); + } + return result; + } + function getDefaultValueForOption(option) { + switch (option.type) { + case "number": + return 1; + case "boolean": + return true; + case "string": + return option.isFilePath ? "./" : ""; + case "list": + return []; + case "object": + return {}; + default: + return option.type.keys().next().value; + } + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + function isAllowedOption(_a) { + var category = _a.category, name = _a.name; + // Skip options which do not have a category or have category `Command_line_Options` + // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line + return category !== undefined + && category !== ts.Diagnostics.Command_line_Options + && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name)); + } + function writeConfigurations() { + // Filter applicable options to place in the file + var categorizedOptions = ts.createMultiMap(); + for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { + var option = optionDeclarations_1[_i]; + var category = option.category; + if (isAllowedOption(option)) { + categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); + } + } + // Serialize all options and their descriptions + var marginLength = 0; + var seenKnownKeys = 0; + var nameColumn = []; + var descriptionColumn = []; + categorizedOptions.forEach(function (options, category) { + if (nameColumn.length !== 0) { + nameColumn.push(""); + descriptionColumn.push(""); + } + nameColumn.push("/* " + category + " */"); + descriptionColumn.push(""); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var option = options_1[_i]; + var optionName = void 0; + if (compilerOptionsMap.has(option.name)) { + optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); + } + else { + optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; + } + nameColumn.push(optionName); + descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); + marginLength = Math.max(optionName.length, marginLength); + } + }); + // Write the output + var tab = makePadding(2); + var result = []; + result.push("{"); + result.push(tab + "\"compilerOptions\": {"); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < nameColumn.length; i++) { + var optionName = nameColumn[i]; + var description = descriptionColumn[i]; + result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); + } + if (fileNames.length) { + result.push(tab + "},"); + result.push(tab + "\"files\": ["); + for (var i = 0; i < fileNames.length; i++) { + result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); + } + result.push(tab + "]"); + } + else { + result.push(tab + "}"); + } + result.push("}"); + return result.join(newLine); + } + } + ts.generateTSConfig = generateTSConfig; + /** + * Parse the contents of a config file (tsconfig.json). + * @param json The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + /** + * Parse the contents of a config file (tsconfig.json). + * @param jsonNode The contents of the config file to parse + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + */ + function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); + } + ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; + /*@internal*/ + function setConfigFileInOptions(options, configFile) { + if (configFile) { + Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); + } + } + ts.setConfigFileInOptions = setConfigFileInOptions; + function isNullOrUndefined(x) { + // tslint:disable-next-line:no-null-keyword + return x === undefined || x === null; + } + function directoryOfCombinedPath(fileName, basePath) { + // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical + // until consistient casing errors are reported + return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); + } + /** + * Parse the contents of a config file from json or json source file (tsconfig.json). + * @param json The contents of the config file to parse + * @param sourceFile sourceFile corresponding to the Json + * @param host Instance of ParseConfigHost used to enumerate files in folder. + * @param basePath A root directory to resolve relative path entries in the config + * file to. e.g. outDir + * @param resolutionStack Only present for backwards-compatibility. Should be empty. + */ + function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { + if (existingOptions === void 0) { existingOptions = {}; } + if (resolutionStack === void 0) { resolutionStack = []; } + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); + var errors = []; + var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); + var raw = parsedConfig.raw; + var options = ts.extend(existingOptions, parsedConfig.options || {}); + options.configFilePath = configFileName && ts.normalizeSlashes(configFileName); + setConfigFileInOptions(options, sourceFile); + var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec, projectReferences = _a.projectReferences; + return { + options: options, + fileNames: fileNames, + projectReferences: projectReferences, + typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), + raw: raw, + errors: errors, + wildcardDirectories: wildcardDirectories, + compileOnSave: !!raw.compileOnSave, + configFileSpecs: spec + }; + function getFileNames() { + var filesSpecs; + if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { + if (ts.isArray(raw.files)) { + filesSpecs = raw.files; + if (filesSpecs.length === 0) { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); + } + } + var includeSpecs; + if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { + if (ts.isArray(raw.include)) { + includeSpecs = raw.include; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); + } + } + var excludeSpecs; + if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { + if (ts.isArray(raw.exclude)) { + excludeSpecs = raw.exclude; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); + } + } + else if (raw.compilerOptions) { + var outDir = raw.compilerOptions.outDir; + var declarationDir = raw.compilerOptions.declarationDir; + if (outDir || declarationDir) { + excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; }); + } + } + if (filesSpecs === undefined && includeSpecs === undefined) { + includeSpecs = ["**/*"]; + } + var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); + if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0 && !ts.hasProperty(raw, "references")) { + errors.push(getErrorForNoInputFiles(result.spec, configFileName)); + } + if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { + if (ts.isArray(raw.references)) { + var references = []; + for (var _i = 0, _a = raw.references; _i < _a.length; _i++) { + var ref = _a[_i]; + if (typeof ref.path !== "string") { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); + } + else { + references.push({ + path: ts.getNormalizedAbsolutePath(ref.path, basePath), + originalPath: ref.path, + prepend: ref.prepend, + circular: ref.circular + }); + } + } + result.projectReferences = references; + } + else { + createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); + } + } + return result; + } + function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { + if (!sourceFile) { + errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); } } } - ts.createGetSymbolWalker = createGetSymbolWalker; + /*@internal*/ + function isErrorNoInputFiles(error) { + return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; + } + ts.isErrorNoInputFiles = isErrorNoInputFiles; + /*@internal*/ + function getErrorForNoInputFiles(_a, configFileName) { + var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; + return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); + } + ts.getErrorForNoInputFiles = getErrorForNoInputFiles; + function isSuccessfulParsedTsconfig(value) { + return !!value.options; + } + /** + * This *just* extracts options/include/exclude/files out of a config file. + * It does *not* resolve the included files. + */ + function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { + basePath = ts.normalizeSlashes(basePath); + var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); + if (resolutionStack.indexOf(resolvedPath) >= 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); + return { raw: json || convertToObject(sourceFile, errors) }; + } + var ownConfig = json ? + parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : + parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); + if (ownConfig.extendedConfigPath) { + // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. + resolutionStack = resolutionStack.concat([resolvedPath]); + var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); + if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { + var baseRaw_1 = extendedConfig.raw; + var raw_1 = ownConfig.raw; + var setPropertyInRawIfNotUndefined = function (propertyName) { + var value = raw_1[propertyName] || baseRaw_1[propertyName]; + if (value) { + raw_1[propertyName] = value; + } + }; + setPropertyInRawIfNotUndefined("include"); + setPropertyInRawIfNotUndefined("exclude"); + setPropertyInRawIfNotUndefined("files"); + if (raw_1.compileOnSave === undefined) { + raw_1.compileOnSave = baseRaw_1.compileOnSave; + } + ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); + // TODO extend type typeAcquisition + } + } + return ownConfig; + } + function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { + if (ts.hasProperty(json, "excludes")) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); + // typingOptions has been deprecated and is only supported for backward compatibility purposes. + // It should be removed in future releases - use typeAcquisition instead. + var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); + json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); + var extendedConfigPath; + if (json.extends) { + if (!ts.isString(json.extends)) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); + } + else { + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { + var options = getDefaultCompilerOptions(configFileName); + var typeAcquisition, typingOptionstypeAcquisition; + var extendedConfigPath; + var optionsIterator = { + onSetValidOptionKeyValueInParent: function (parentOption, option, value) { + ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); + var currentOption = parentOption === "compilerOptions" ? + options : + parentOption === "typeAcquisition" ? + (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : + (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); + currentOption[option.name] = normalizeOptionValue(option, basePath, value); + }, + onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { + switch (key) { + case "extends": + var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; + extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + }); + return; + case "files": + if (value.length === 0) { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + } + return; + } + }, + onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { + if (key === "excludes") { + errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + } + }; + var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + if (!typeAcquisition) { + if (typingOptionstypeAcquisition) { + typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? + { + enable: typingOptionstypeAcquisition.enableAutoDiscovery, + include: typingOptionstypeAcquisition.include, + exclude: typingOptionstypeAcquisition.exclude + } : + typingOptionstypeAcquisition; + } + else { + typeAcquisition = getDefaultTypeAcquisition(configFileName); + } + } + return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; + } + function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { + extendedConfig = ts.normalizeSlashes(extendedConfig); + // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) + if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { + errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); + return undefined; + } + var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); + if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { + extendedConfigPath = extendedConfigPath + ".json"; + if (!host.fileExists(extendedConfigPath)) { + errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + return undefined; + } + } + return extendedConfigPath; + } + function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { + var _a; + var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); + if (sourceFile) { + (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); + } + if (extendedResult.parseDiagnostics.length) { + errors.push.apply(errors, extendedResult.parseDiagnostics); + return undefined; + } + var extendedDirname = ts.getDirectoryPath(extendedConfigPath); + var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); + if (sourceFile) { + (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); + } + if (isSuccessfulParsedTsconfig(extendedConfig)) { + // Update the paths to reflect base path + var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); + var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; + var mapPropertiesInRawIfNotUndefined = function (propertyName) { + if (raw_2[propertyName]) { + raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); + } + }; + var raw_2 = extendedConfig.raw; + mapPropertiesInRawIfNotUndefined("include"); + mapPropertiesInRawIfNotUndefined("exclude"); + mapPropertiesInRawIfNotUndefined("files"); + } + return extendedConfig; + } + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); + return typeof result === "boolean" && result; + } + function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; + function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { + var errors = []; + var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); + return { options: options, errors: errors }; + } + ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; + function getDefaultCompilerOptions(configFileName) { + var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } + : {}; + return options; + } + function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultCompilerOptions(configFileName); + convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); + if (configFileName) { + options.configFilePath = ts.normalizeSlashes(configFileName); + } + return options; + } + function getDefaultTypeAcquisition(configFileName) { + return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; + } + function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { + var options = getDefaultTypeAcquisition(configFileName); + var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); + convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); + return options; + } + function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { + if (!jsonOptions) { + return; + } + var optionNameMap = commandLineOptionsToMap(optionDeclarations); + for (var id in jsonOptions) { + var opt = optionNameMap.get(id); + if (opt) { + defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + } + } + } + function convertJsonOption(opt, value, basePath, errors) { + if (isCompilerOptionsValue(opt, value)) { + var optType = opt.type; + if (optType === "list" && ts.isArray(value)) { + return convertJsonOptionOfListType(opt, value, basePath, errors); + } + else if (!ts.isString(optType)) { + return convertJsonOptionOfCustomType(opt, value, errors); + } + return normalizeNonListOptionValue(opt, basePath, value); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); + } + } + function normalizeOptionValue(option, basePath, value) { + if (isNullOrUndefined(value)) + return undefined; + if (option.type === "list") { + var listOption_1 = option; + if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { + return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + } + return value; + } + else if (!ts.isString(option.type)) { + return option.type.get(ts.isString(value) ? value.toLowerCase() : value); + } + return normalizeNonListOptionValue(option, basePath, value); + } + function normalizeNonListOptionValue(option, basePath, value) { + if (option.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + if (value === "") { + value = "."; + } + } + return value; + } + function convertJsonOptionOfCustomType(opt, value, errors) { + if (isNullOrUndefined(value)) + return undefined; + var key = value.toLowerCase(); + var val = opt.type.get(key); + if (val !== undefined) { + return val; + } + else { + errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); + } + } + function convertJsonOptionOfListType(option, values, basePath, errors) { + return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); + } + function trimString(s) { + return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); + } + /** + * Tests for a path that ends in a recursive directory wildcard. + * Matches **, \**, **\, and \**\, but not a**b. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\* # matches the recursive directory wildcard "**". + * \/?$ # matches an optional trailing directory separator at the end of the string. + */ + var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; + /** + * Tests for a path where .. appears after a recursive directory wildcard. + * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * (^|\/) # matches either the beginning of the string or a directory separator. + * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. + * (.*\/)? # optionally matches any number of characters followed by a directory separator. + * \.\. # matches a parent directory path component ".." + * ($|\/) # matches either the end of the string or a directory separator. + */ + var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; + /** + * Tests for a path containing a wildcard character in a directory component of the path. + * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * \/ # matches a directory separator. + * [^/]*? # matches any number of characters excluding directory separators (non-greedy). + * [*?] # matches either a wildcard character (* or ?) + * [^/]* # matches any number of characters excluding directory separators (greedy). + * \/ # matches a directory separator. + */ + var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; + /** + * Matches the portion of a wildcard path that does not contain wildcards. + * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. + * + * NOTE: used \ in place of / above to avoid issues with multiline comments. + * + * Breakdown: + * ^ # matches the beginning of the string + * [^*?]* # matches any number of non-wildcard characters + * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by + * # a path component that contains at least one wildcard character (* or ?). + */ + var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; + /** + * Expands an array of file specifications. + * + * @param filesSpecs The literal file names to include. + * @param includeSpecs The wildcard file specifications to include. + * @param excludeSpecs The wildcard file specifications to exclude. + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param errors An array for diagnostic reporting. + */ + function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { + basePath = ts.normalizePath(basePath); + var validatedIncludeSpecs, validatedExcludeSpecs; + // The exclude spec list is converted into a regular expression, which allows us to quickly + // test whether a file or directory should be excluded before recursively traversing the + // file system. + if (includeSpecs) { + validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); + } + if (excludeSpecs) { + validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); + } + // Wildcard directories (provided as part of a wildcard path) are stored in a + // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), + // or a recursive directory. This information is used by filesystem watchers to monitor for + // new entries in these paths. + var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); + var spec = { filesSpecs: filesSpecs, referencesSpecs: undefined, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; + return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); + } + /** + * Gets the file names from the provided config file specs that contain, files, include, exclude and + * other properties needed to resolve the file names + * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details + * @param basePath The base path for any relative file specifications. + * @param options Compiler options. + * @param host The host used to resolve files and directories. + * @param extraFileExtensions optionaly file extra file extension information from host + */ + /* @internal */ + function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { + if (extraFileExtensions === void 0) { extraFileExtensions = []; } + basePath = ts.normalizePath(basePath); + var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; + // Literal file names (provided via the "files" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map later when when including + // wildcard paths. + var literalFileMap = ts.createMap(); + // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a + // file map with a possibly case insensitive key. We use this map to store paths matched + // via wildcard, and to handle extension priority. + var wildcardFileMap = ts.createMap(); + var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; + // Rather than requery this for each file and filespec, we query the supported extensions + // once and store it on the expansion context. + var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); + // Literal files are always included verbatim. An "include" or "exclude" specification cannot + // remove a literal file. + if (filesSpecs) { + for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { + var fileName = filesSpecs_1[_i]; + var file = ts.getNormalizedAbsolutePath(fileName, basePath); + literalFileMap.set(keyMapper(file), file); + } + } + if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { + for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { + var file = _b[_a]; + // If we have already included a literal or wildcard path with a + // higher priority extension, we should skip this file. + // + // This handles cases where we may encounter both .ts and + // .d.ts (or .js if "allowJs" is enabled) in the same + // directory when they are compilation outputs. + if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + continue; + } + // We may have included a wildcard path with a lower priority + // extension due to the user-defined order of entries in the + // "include" array. If there is a lower priority extension in the + // same directory, we should remove it. + removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); + var key = keyMapper(file); + if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { + wildcardFileMap.set(key, file); + } + } + } + var literalFiles = ts.arrayFrom(literalFileMap.values()); + var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var projectReferences = spec.referencesSpecs && spec.referencesSpecs.map(function (r) { + return __assign({}, r, { path: ts.getNormalizedAbsolutePath(r.path, basePath) }); + }); + return { + fileNames: literalFiles.concat(wildcardFiles), + projectReferences: projectReferences, + wildcardDirectories: wildcardDirectories, + spec: spec + }; + } + ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; + function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { + return specs.filter(function (spec) { + var diag = specToDiagnostic(spec, allowTrailingRecursion); + if (diag !== undefined) { + errors.push(createDiagnostic(diag, spec)); + } + return diag === undefined; + }); + function createDiagnostic(message, spec) { + var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec); + return element ? + ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) : + 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 (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. + */ + function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { + // We watch a directory recursively if it contains a wildcard anywhere in a directory segment + // of the pattern: + // + // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively + // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added + // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler + // + // We watch a directory without recursion if it contains a wildcard in the file segment of + // the pattern: + // + // /a/b/* - Watch /a/b directly to catch any new file + // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z + var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); + var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); + var wildcardDirectories = {}; + if (include !== undefined) { + var recursiveKeys = []; + for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { + var file = include_1[_i]; + var spec = ts.normalizePath(ts.combinePaths(path, file)); + if (excludeRegex && excludeRegex.test(spec)) { + continue; + } + var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); + if (match) { + var key = match.key, flags = match.flags; + var existingFlags = wildcardDirectories[key]; + if (existingFlags === undefined || existingFlags < flags) { + wildcardDirectories[key] = flags; + if (flags === 1 /* Recursive */) { + recursiveKeys.push(key); + } + } + } + } + // Remove any subpaths under an existing recursively watched directory. + for (var key in wildcardDirectories) { + if (ts.hasProperty(wildcardDirectories, key)) { + for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { + var recursiveKey = recursiveKeys_1[_a]; + if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { + delete wildcardDirectories[key]; + } + } + } + } + } + return wildcardDirectories; + } + function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { + var match = wildcardDirectoryPattern.exec(spec); + if (match) { + return { + key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), + flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ + }; + } + if (ts.isImplicitGlob(spec)) { + return { key: spec, flags: 1 /* Recursive */ }; + } + return undefined; + } + /** + * Determines whether a literal or wildcard file has already been included that has a higher + * extension priority. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); + for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { + var higherPriorityExtension = extensions[i]; + var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); + if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { + return true; + } + } + return false; + } + /** + * Removes files included via wildcard expansion with a lower extension priority that have + * already been included. + * + * @param file The path to the file. + * @param extensionPriority The priority of the extension. + * @param context The expansion context. + */ + function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { + var extensionPriority = ts.getExtensionPriority(file, extensions); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); + for (var i = nextExtensionPriority; i < extensions.length; i++) { + var lowerPriorityExtension = extensions[i]; + var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); + wildcardFiles.delete(lowerPriorityPath); + } + } + /** + * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. + * Also converts enum values back to strings. + */ + /* @internal */ + function convertCompilerOptionsForTelemetry(opts) { + var out = {}; + for (var key in opts) { + if (opts.hasOwnProperty(key)) { + var type = getOptionFromName(key); + if (type !== undefined) { // Ignore unknown options + out[key] = getOptionValueWithEmptyStrings(opts[key], type); + } + } + } + return out; + } + ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; + function getOptionValueWithEmptyStrings(value, option) { + switch (option.type) { + case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". + return ""; + case "string": // Could be any arbitrary string -- use empty string instead. + return ""; + case "number": // Allow numbers, but be sure to check it's actually a number. + return typeof value === "number" ? value : ""; + case "boolean": + return typeof value === "boolean" ? value : ""; + case "list": + var elementType_1 = option.element; + return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + default: + return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { + if (optionEnumValue === value) { + return optionStringValue; + } + }); // TODO: GH#18217 + } + } })(ts || (ts = {})); -/// -/// var ts; (function (ts) { function trace(host) { @@ -23732,7 +23818,7 @@ var ts; ts.trace = trace; /* @internal */ function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; + return !!compilerOptions.traceResolution && host.trace !== undefined; } ts.isTraceEnabled = isTraceEnabled; function withPackageId(packageId, r) { @@ -23749,7 +23835,8 @@ var ts; (function (Extensions) { Extensions[Extensions["TypeScript"] = 0] = "TypeScript"; Extensions[Extensions["JavaScript"] = 1] = "JavaScript"; - Extensions[Extensions["DtsOnly"] = 2] = "DtsOnly"; /** Only '.d.ts' */ + Extensions[Extensions["Json"] = 2] = "Json"; + Extensions[Extensions["DtsOnly"] = 3] = "DtsOnly"; /** Only '.d.ts' */ })(Extensions || (Extensions = {})); /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */ function resolvedTypeScriptOnly(resolved) { @@ -23789,16 +23876,24 @@ var ts; return path; } } + /* @internal */ function readJson(path, host) { try { var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; + if (!jsonText) + return {}; + var result = ts.parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; } catch (e) { // gracefully handle if readFile fails or returns not JSON return {}; } } + ts.readJson = readJson; function getEffectiveTypeRoots(options, host) { if (options.typeRoots) { return options.typeRoots; @@ -23903,7 +23998,6 @@ var ts; } } function secondaryLookup() { - var resolvedFile; var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile); if (initialLocationForSecondaryLookup !== undefined) { // check secondary locations @@ -23911,7 +24005,7 @@ var ts; trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } var result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); - resolvedFile = resolvedTypeScriptOnly(result && result.value); + var resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); } @@ -23984,7 +24078,7 @@ var ts; } function getOrCreateCacheForModuleName(nonRelativeModuleName) { if (ts.isExternalModuleNameRelative(nonRelativeModuleName)) { - return undefined; + return undefined; // TODO: GH#18217 } var perModuleNameCache = moduleNameToDirectoryMap.get(nonRelativeModuleName); if (!perModuleNameCache) { @@ -24056,6 +24150,12 @@ var ts; } } ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps; + function resolveModuleNameFromCache(moduleName, containingFile, cache) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory); + return perFolderCache && perFolderCache.get(moduleName); + } + ts.resolveModuleNameFromCache = resolveModuleNameFromCache; function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache) { var traceEnabled = isTraceEnabled(compilerOptions, host); if (traceEnabled) { @@ -24090,7 +24190,7 @@ var ts; result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache); break; default: - ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); + return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution); } if (perFolderCache) { perFolderCache.set(moduleName, result); @@ -24316,7 +24416,11 @@ var ts; var traceEnabled = isTraceEnabled(compilerOptions, host); var failedLookupLocations = []; var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled }; - var result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript)); + var result = jsOnly ? + tryResolve(Extensions.JavaScript) : + (tryResolve(Extensions.TypeScript) || + tryResolve(Extensions.JavaScript) || + (compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined)); if (result && result.value) { var _a = result.value, resolved = _a.resolved, originalPath = _a.originalPath, isExternalLibraryImport = _a.isExternalLibraryImport; return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations); @@ -24339,7 +24443,7 @@ var ts; var originalPath = void 0; if (!compilerOptions.preserveSymlinks && resolvedValue) { originalPath = resolvedValue.path; - var path = realPath(resolved_1.value.path, host, traceEnabled); + var path = realPath(resolvedValue.path, host, traceEnabled); if (path === originalPath) { originalPath = undefined; } @@ -24364,13 +24468,14 @@ var ts; if (traceEnabled) { trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real); } + ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real); // tslint:disable-line return real; } function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } - if (!ts.pathEndsWithDirectorySeparator(candidate)) { + if (!ts.hasTrailingDirectorySeparator(candidate)) { if (!onlyRecordFailures) { var parentOfCandidate = ts.getDirectoryPath(candidate); if (!directoryProbablyExists(parentOfCandidate, state.host)) { @@ -24455,6 +24560,10 @@ var ts; * 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. */ function loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + if (extensions === Extensions.Json) { + var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); if (resolvedByAddingExtension) { @@ -24487,10 +24596,12 @@ var ts; return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */); case Extensions.JavaScript: return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */); + case Extensions.Json: + return tryExtension(".json" /* Json */); } function tryExtension(ext) { var path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); - return path && { path: path, ext: ext }; + return path === undefined ? undefined : { path: path, ext: ext }; } } /** Return the file if it exists. */ @@ -24539,8 +24650,11 @@ var ts; } else { var jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string") { - subModuleName = ts.removeExtension(ts.removeExtension(jsPath.substring(nodeModuleDirectory.length + 1), ".js" /* Js */), ".jsx" /* Jsx */) + ".d.ts" /* Dts */; + if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { + var potentialSubModule_1 = jsPath.substring(nodeModuleDirectory.length + 1); + subModuleName = (ts.forEach(ts.supportedJavascriptExtensions, function (extension) { + return ts.tryRemoveExtension(potentialSubModule_1, extension); + }) || potentialSubModule_1) + ".d.ts" /* Dts */; } else { subModuleName = "index.d.ts"; @@ -24573,14 +24687,23 @@ var ts; } } function loadModuleFromPackageJson(jsonContent, extensions, candidate, failedLookupLocations, state) { - var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state); + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); if (!file) { - return undefined; + if (extensions === Extensions.TypeScript) { + // When resolving typescript modules, try resolving using main field as well + file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + if (!file) { + return undefined; + } + } + else { + return undefined; + } } var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); if (fromFile) { - var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + var resolved = resolvedIfExtensionMatches(extensions, fromFile); if (resolved) { return resolved; } @@ -24608,6 +24731,8 @@ var ts; switch (extensions) { case Extensions.JavaScript: return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */; + case Extensions.Json: + return extension === ".json" /* Json */; case Extensions.TypeScript: return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */; case Extensions.DtsOnly: @@ -24678,7 +24803,7 @@ var ts; if (packageResult) { return packageResult; } - if (extensions !== Extensions.JavaScript) { + if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) { var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types"); var nodeModulesAtTypesExists = nodeModulesFolderExists; if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes_1, state.host)) { @@ -24805,9 +24930,3644 @@ var ts; return value !== undefined ? { value: value } : undefined; } })(ts || (ts = {})); -/// -/// -/// +/* @internal */ +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) { + return node.body ? getModuleInstanceStateWorker(node.body) : 1 /* Instantiated */; + } + ts.getModuleInstanceState = getModuleInstanceState; + function getModuleInstanceStateWorker(node) { + // A module is uninstantiated if it contains only + switch (node.kind) { + // 1. interface declarations, type alias declarations + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return 0 /* NonInstantiated */; + // 2. const enum declarations + case 241 /* EnumDeclaration */: + if (ts.isEnumConst(node)) { + return 2 /* ConstEnumOnly */; + } + break; + // 3. non-exported import declarations + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + if (!(ts.hasModifier(node, 1 /* Export */))) { + return 0 /* NonInstantiated */; + } + break; + // 4. other uninstantiated module declarations. + case 243 /* ModuleBlock */: { + var state_1 = 0 /* NonInstantiated */; + ts.forEachChild(node, function (n) { + var childState = getModuleInstanceStateWorker(n); + switch (childState) { + case 0 /* NonInstantiated */: + // child is non-instantiated - continue searching + return; + case 2 /* ConstEnumOnly */: + // child is const enum only - record state and continue searching + state_1 = 2 /* ConstEnumOnly */; + return; + case 1 /* Instantiated */: + // child is instantiated - record state and stop + state_1 = 1 /* Instantiated */; + return true; + default: + ts.Debug.assertNever(childState); + } + }); + return state_1; + } + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(node); + case 71 /* Identifier */: + // Only jsdoc typedef definition can exist in jsdoc namespace, and it should + // be considered the same as type alias + if (node.isInJSDocNamespace) { + return 0 /* NonInstantiated */; + } + } + return 1 /* Instantiated */; + } + var ContainerFlags; + (function (ContainerFlags) { + // The current node is not a container, and no container manipulation should happen before + // recursing into it. + ContainerFlags[ContainerFlags["None"] = 0] = "None"; + // The current node is a container. It should be set as the current container (and block- + // container) before recursing into it. The current node does not have locals. Examples: + // + // Classes, ObjectLiterals, TypeLiterals, Interfaces... + ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer"; + // The current node is a block-scoped-container. It should be set as the current block- + // container before recursing into it. Examples: + // + // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... + ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer"; + // The current node is the container of a control flow path. The current control flow should + // be saved and restored, and a new control flow initialized within the container. + 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"); + binder(file, options); + ts.performance.mark("afterBind"); + ts.performance.measure("Bind", "beforeBind", "afterBind"); + } + ts.bindSourceFile = bindSourceFile; + function createBinder() { + var file; + var options; + var languageVersion; + var parent; + var container; + var thisParentContainer; // Container one level up + var blockScopeContainer; + var lastContainer; + var delayedTypeAliases; + var seenThisKeyword; + // state used by control flow analysis + var currentFlow; + var currentBreakTarget; + var currentContinueTarget; + var currentReturnTarget; + var currentTrueTarget; + var currentFalseTarget; + var preSwitchCaseFlow; + var activeLabels; + var hasExplicitReturn; + // state used for emit helpers + var emitFlags; + // If this file is an external module, then it is automatically in strict-mode according to + // ES6. If it is not an external module, then we'll determine if it is in strict mode or + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. + var inStrictMode; + var symbolCount = 0; + var Symbol; // tslint:disable-line variable-name + var classifiableNames; + var unreachableFlow = { flags: 1 /* Unreachable */ }; + var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; + // state used to aggregate transform flags during bind. + var subtreeTransformFlags = 0 /* None */; + var skipTransformFlagAggregation; + /** + * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file) + * If so, the node _must_ be in the current file (as that's the only way anything could have traversed to it to yield it as the error node) + * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations. + */ + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2); + } + function bindSourceFile(f, opts) { + file = f; + options = opts; + languageVersion = ts.getEmitScriptTarget(options); + inStrictMode = bindInStrictMode(file, opts); + classifiableNames = ts.createUnderscoreEscapedMap(); + symbolCount = 0; + skipTransformFlagAggregation = file.isDeclarationFile; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + delayedBindJSDocTypedefTag(); + } + file = undefined; + options = undefined; + languageVersion = undefined; + parent = undefined; + container = undefined; + thisParentContainer = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + delayedTypeAliases = undefined; + seenThisKeyword = false; + currentFlow = undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + currentReturnTarget = undefined; + currentTrueTarget = undefined; + currentFalseTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + emitFlags = 0 /* None */; + subtreeTransformFlags = 0 /* None */; + } + return bindSourceFile; + function bindInStrictMode(file, opts) { + if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags, name) { + symbolCount++; + return new Symbol(flags, name); + } + function addDeclarationToSymbol(symbol, node, symbolFlags) { + symbol.flags |= symbolFlags; + node.symbol = symbol; + symbol.declarations = ts.append(symbol.declarations, node); + if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) { + symbol.exports = ts.createSymbolTable(); + } + if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { + symbol.members = ts.createSymbolTable(); + } + if (symbolFlags & 67216319 /* Value */) { + var valueDeclaration = symbol.valueDeclaration; + if (!valueDeclaration || + (valueDeclaration.kind !== node.kind && ts.isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules + symbol.valueDeclaration = node; + } + } + } + // Should not be called on a declaration with a computed property name, + // unless it is a well known Symbol. + function getDeclarationName(node) { + if (node.kind === 252 /* ExportAssignment */) { + return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */; + } + var name = ts.getNameOfDeclaration(node); + if (name) { + if (ts.isAmbientModule(node)) { + var moduleName = ts.getTextOfIdentifierOrLiteral(name); + return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\""); + } + if (name.kind === 147 /* ComputedPropertyName */) { + var nameExpression = name.expression; + // treat computed property names where expression is string/numeric literal as just string/numeric literal + if (ts.isStringOrNumericLiteral(nameExpression)) { + return ts.escapeLeadingUnderscores(nameExpression.text); + } + ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); + return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name)); + } + return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + } + switch (node.kind) { + case 155 /* Constructor */: + return "__constructor" /* Constructor */; + case 163 /* FunctionType */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + return "__call" /* Call */; + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: + return "__new" /* New */; + case 160 /* IndexSignature */: + return "__index" /* Index */; + case 253 /* ExportDeclaration */: + return "__export" /* ExportStar */; + case 277 /* SourceFile */: + // json file should behave as + // module.exports = ... + return "export=" /* ExportEquals */; + case 202 /* BinaryExpression */: + if (ts.getSpecialPropertyAssignmentKind(node) === 2 /* ModuleExports */) { + // module.exports = ... + return "export=" /* ExportEquals */; + } + ts.Debug.fail("Unknown binary declaration kind"); + break; + case 287 /* JSDocFunctionType */: + return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */); + case 149 /* Parameter */: + // Parameters with names are handled at the top of this function. Parameters + // without names can only come from JSDocFunctionTypes. + ts.Debug.assert(node.parent.kind === 287 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; }); + var functionType = node.parent; + var index = functionType.parameters.indexOf(node); + return "arg" + index; + } + } + function getDisplayName(node) { + return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.assertDefined(getDeclarationName(node))); + } + /** + * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. + * @param symbolTable - The symbol table which node will be added to. + * @param parent - node's parent declaration. + * @param node - The declaration to be added to the symbol table + * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) + * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. + */ + function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) { + ts.Debug.assert(!ts.hasDynamicName(node)); + var isDefaultExport = ts.hasModifier(node, 512 /* Default */); + // The exported symbol for an export default function/class node is always named "default" + var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node); + var symbol; + if (name === undefined) { + symbol = createSymbol(0 /* None */, "__missing" /* Missing */); + } + else { + // Check and see if the symbol table already has a symbol with this name. If not, + // create a new symbol with this name and add it to the table. Note that we don't + // give the new symbol any flags *yet*. This ensures that it will not conflict + // with the 'excludes' flags we pass in. + // + // If we do get an existing symbol, see if it conflicts with the new symbol we're + // creating. For example, a 'var' symbol and a 'class' symbol will conflict within + // the same symbol table. If we have a conflict, report the issue on each + // declaration we have for this symbol, and then create a new symbol for this + // declaration. + // + // Note that when properties declared in Javascript constructors + // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. + // Always. This allows the common Javascript pattern of overwriting a prototype method + // with an bound instance method of the same type: `this.method = this.method.bind(this)` + // + // If we created a new symbol, either because we didn't have a symbol with this name + // in the symbol table, or we conflicted with an existing symbol, then just add this + // node as the sole declaration of the new symbol. + // + // Otherwise, we'll be merging into a compatible existing symbol (for example when + // you have multiple 'vars' with the same name in the same container). In this case + // just add this node into the declarations list of the symbol. + symbol = symbolTable.get(name); + if (includes & 2885600 /* Classifiable */) { + classifiableNames.set(name, true); + } + if (!symbol) { + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + if (isReplaceableByMethod) + symbol.isReplaceableByMethod = true; + } + else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { + // A symbol already exists, so don't add this as a declaration. + return symbol; + } + else if (symbol.flags & excludes) { + if (symbol.isReplaceableByMethod) { + // Javascript constructor-declared symbols can be discarded in favor of + // prototype symbols like methods. + symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); + } + else { + if (ts.isNamedDeclaration(node)) { + node.name.parent = node; + } + // Report errors every position with duplicate declaration + // Report errors on previous encountered declarations + var message_1 = symbol.flags & 2 /* BlockScopedVariable */ + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + var messageNeedsName_1 = true; + if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) { + message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations; + messageNeedsName_1 = false; + } + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (node.kind === 252 /* ExportAssignment */ && !node.isExportEquals)) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + messageNeedsName_1 = false; + } + } + } + var addError = function (decl) { + file.bindDiagnostics.push(createDiagnosticForNode(ts.getNameOfDeclaration(decl) || decl, message_1, messageNeedsName_1 ? getDisplayName(decl) : undefined)); + }; + ts.forEach(symbol.declarations, addError); + addError(node); + symbol = createSymbol(0 /* None */, name); + } + } + } + addDeclarationToSymbol(symbol, node, includes); + if (symbol.parent) { + ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one"); + } + else { + symbol.parent = parent; + } + return symbol; + } + function declareModuleMember(node, symbolFlags, symbolExcludes) { + var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */; + if (symbolFlags & 2097152 /* Alias */) { + if (node.kind === 255 /* ExportSpecifier */ || (node.kind === 246 /* ImportEqualsDeclaration */ && hasExportModifier)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + else { + // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag, + // and an associated export symbol with all the correct flags set on it. There are 2 main reasons: + // + // 1. We treat locals and exports of the same name as mutually exclusive within a container. + // That means the binder will issue a Duplicate Identifier error if you mix locals and exports + // with the same name in the same container. + // TODO: Make this a more specific error and decouple it from the exclusion logic. + // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, + // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way + // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. + // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge + // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation + // and this case is specially handled. Module augmentations should only be merged with original module definition + // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. + if (ts.isJSDocTypeAlias(node)) + ts.Debug.assert(ts.isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 32 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) { + if (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node)) { + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! + } + var exportKind = symbolFlags & 67216319 /* Value */ ? 1048576 /* ExportValue */ : 0; + var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes); + local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + node.localSymbol = local; + return local; + } + else { + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + } + // All container nodes are kept on a linked list in declaration order. This list is used by + // the getLocalNameOfContainer function in the type checker to validate that the local name + // used for a container is unique. + function bindContainer(node, containerFlags) { + // Before we recurse into a node's children, we first save the existing parent, container + // and block-container. Then after we pop out of processing the children, we restore + // these saved values. + var saveContainer = container; + var saveThisParentContainer = thisParentContainer; + var savedBlockScopeContainer = blockScopeContainer; + // Depending on what kind of node this is, we may have to adjust the current container + // and block-container. If the current node is a container, then it is automatically + // considered the current block-container as well. Also, for containers that we know + // may contain locals, we eagerly initialize the .locals field. We do this because + // it's highly likely that the .locals will be needed to place some child in (for example, + // a parameter, or variable declaration). + // + // However, we do not proactively create the .locals for block-containers because it's + // totally normal and common for block-containers to never actually have a block-scoped + // variable in them. We don't want to end up allocating an object for every 'block' we + // run into when most of them won't be necessary. + // + // Finally, if this is a block-container, then we clear out any existing .locals object + // it may contain within it. This happens in incremental scenarios. Because we can be + // reusing a node from a previous compilation, that node may have had 'locals' created + // for it. We must clear this so we don't accidentally move any stale data forward from + // a previous compilation. + if (containerFlags & 1 /* IsContainer */) { + if (node.kind !== 195 /* ArrowFunction */) { + thisParentContainer = container; + } + container = blockScopeContainer = node; + if (containerFlags & 32 /* HasLocals */) { + container.locals = ts.createSymbolTable(); + } + addToContainerChain(container); + } + else if (containerFlags & 2 /* IsBlockScopedContainer */) { + blockScopeContainer = node; + blockScopeContainer.locals = undefined; + } + if (containerFlags & 4 /* IsControlFlowContainer */) { + var saveCurrentFlow = currentFlow; + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + var saveReturnTarget = currentReturnTarget; + var saveActiveLabels = activeLabels; + var saveHasExplicitReturn = hasExplicitReturn; + var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) && + !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); + // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave + // similarly to break statements that exit to a label just past the statement body. + if (!isIIFE) { + currentFlow = { flags: 2 /* Start */ }; + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { + currentFlow.container = node; + } + } + // We create a return control flow graph for IIFEs and constructors. For constructors + // we use the return control flow graph in strict property intialization checks. + currentReturnTarget = isIIFE || node.kind === 155 /* Constructor */ ? createBranchLabel() : undefined; + currentBreakTarget = undefined; + currentContinueTarget = undefined; + activeLabels = undefined; + hasExplicitReturn = false; + bindChildren(node); + // Reset all reachability check related flags on node (for incremental scenarios) + node.flags &= ~1408 /* ReachabilityAndEmitFlags */; + if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) { + node.flags |= 128 /* HasImplicitReturn */; + if (hasExplicitReturn) + node.flags |= 256 /* HasExplicitReturn */; + } + if (node.kind === 277 /* SourceFile */) { + node.flags |= emitFlags; + } + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + currentFlow = finishFlowLabel(currentReturnTarget); + if (node.kind === 155 /* Constructor */) { + node.returnFlowNode = currentFlow; + } + } + if (!isIIFE) { + currentFlow = saveCurrentFlow; + } + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + currentReturnTarget = saveReturnTarget; + activeLabels = saveActiveLabels; + hasExplicitReturn = saveHasExplicitReturn; + } + else if (containerFlags & 64 /* IsInterface */) { + seenThisKeyword = false; + bindChildren(node); + node.flags = seenThisKeyword ? node.flags | 64 /* ContainsThis */ : node.flags & ~64 /* ContainsThis */; + } + else { + bindChildren(node); + } + container = saveContainer; + thisParentContainer = saveThisParentContainer; + blockScopeContainer = savedBlockScopeContainer; + } + function bindChildren(node) { + if (skipTransformFlagAggregation) { + bindChildrenWorker(node); + } + else if (node.transformFlags & 536870912 /* HasComputedFlags */) { + skipTransformFlagAggregation = true; + bindChildrenWorker(node); + skipTransformFlagAggregation = false; + subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + bindChildrenWorker(node); + subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); + } + } + function bindEachFunctionsFirst(nodes) { + bindEach(nodes, function (n) { return n.kind === 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + bindEach(nodes, function (n) { return n.kind !== 237 /* FunctionDeclaration */ ? bind(n) : undefined; }); + } + function bindEach(nodes, bindFunction) { + if (bindFunction === void 0) { bindFunction = bind; } + if (nodes === undefined) { + return; + } + if (skipTransformFlagAggregation) { + ts.forEach(nodes, bindFunction); + } + else { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0 /* None */; + var nodeArrayFlags = 0 /* None */; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; + bindFunction(node); + nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */; + } + nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + } + function bindEachChild(node) { + ts.forEachChild(node, bind, bindEach); + } + function bindChildrenWorker(node) { + if (checkUnreachable(node)) { + bindEachChild(node); + return; + } + switch (node.kind) { + case 222 /* WhileStatement */: + bindWhileStatement(node); + break; + case 221 /* DoStatement */: + bindDoStatement(node); + break; + case 223 /* ForStatement */: + bindForStatement(node); + break; + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 220 /* IfStatement */: + bindIfStatement(node); + break; + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 233 /* TryStatement */: + bindTryStatement(node); + break; + case 230 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 244 /* CaseBlock */: + bindCaseBlock(node); + break; + case 269 /* CaseClause */: + bindCaseClause(node); + break; + case 231 /* LabeledStatement */: + bindLabeledStatement(node); + break; + case 200 /* PrefixUnaryExpression */: + bindPrefixUnaryExpressionFlow(node); + break; + case 201 /* PostfixUnaryExpression */: + bindPostfixUnaryExpressionFlow(node); + break; + case 202 /* BinaryExpression */: + bindBinaryExpressionFlow(node); + break; + case 196 /* DeleteExpression */: + bindDeleteExpressionFlow(node); + break; + case 203 /* ConditionalExpression */: + bindConditionalExpressionFlow(node); + break; + case 235 /* VariableDeclaration */: + bindVariableDeclarationFlow(node); + break; + case 189 /* CallExpression */: + bindCallExpressionFlow(node); + break; + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + bindJSDocTypeAlias(node); + break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime + case 277 /* SourceFile */: { + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); + break; + } + case 216 /* Block */: + case 243 /* ModuleBlock */: + bindEachFunctionsFirst(node.statements); + break; + default: + bindEachChild(node); + break; + } + bindJSDoc(node); + } + function isNarrowingExpression(expr) { + switch (expr.kind) { + case 71 /* Identifier */: + case 99 /* ThisKeyword */: + case 187 /* PropertyAccessExpression */: + return isNarrowableReference(expr); + case 189 /* CallExpression */: + return hasNarrowableArgument(expr); + case 193 /* ParenthesizedExpression */: + return isNarrowingExpression(expr.expression); + case 202 /* BinaryExpression */: + return isNarrowingBinaryExpression(expr); + case 200 /* PrefixUnaryExpression */: + return expr.operator === 51 /* ExclamationToken */ && isNarrowingExpression(expr.operand); + } + return false; + } + function isNarrowableReference(expr) { + return expr.kind === 71 /* Identifier */ || + expr.kind === 99 /* ThisKeyword */ || + expr.kind === 97 /* SuperKeyword */ || + expr.kind === 187 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression); + } + function hasNarrowableArgument(expr) { + if (expr.arguments) { + for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { + var argument = _a[_i]; + if (isNarrowableReference(argument)) { + return true; + } + } + } + if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + isNarrowableReference(expr.expression.expression)) { + return true; + } + return false; + } + function isNarrowingTypeofOperands(expr1, expr2) { + return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2); + } + function isNarrowableInOperands(left, right) { + return ts.isStringLiteralLike(left) && isNarrowingExpression(right); + } + function isNarrowingBinaryExpression(expr) { + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableReference(expr.left); + case 32 /* EqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + case 34 /* EqualsEqualsEqualsToken */: + case 35 /* ExclamationEqualsEqualsToken */: + return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || + isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); + case 93 /* InstanceOfKeyword */: + return isNarrowableOperand(expr.left); + case 92 /* InKeyword */: + return isNarrowableInOperands(expr.left, expr.right); + case 26 /* CommaToken */: + return isNarrowingExpression(expr.right); + } + return false; + } + function isNarrowableOperand(expr) { + switch (expr.kind) { + case 193 /* ParenthesizedExpression */: + return isNarrowableOperand(expr.expression); + case 202 /* BinaryExpression */: + switch (expr.operatorToken.kind) { + case 58 /* EqualsToken */: + return isNarrowableOperand(expr.left); + case 26 /* CommaToken */: + return isNarrowableOperand(expr.right); + } + } + return isNarrowableReference(expr); + } + function createBranchLabel() { + return { + flags: 4 /* BranchLabel */, + antecedents: undefined + }; + } + function createLoopLabel() { + return { + flags: 8 /* LoopLabel */, + antecedents: undefined + }; + } + function setFlowNodeReferenced(flow) { + // On first reference we set the Referenced flag, thereafter we set the Shared flag + flow.flags |= flow.flags & 512 /* Referenced */ ? 1024 /* Shared */ : 512 /* Referenced */; + } + function addAntecedent(label, antecedent) { + if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) { + (label.antecedents || (label.antecedents = [])).push(antecedent); + setFlowNodeReferenced(antecedent); + } + } + function createFlowCondition(flags, antecedent, expression) { + if (antecedent.flags & 1 /* Unreachable */) { + return antecedent; + } + if (!expression) { + return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow; + } + if (expression.kind === 101 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || + expression.kind === 86 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { + return unreachableFlow; + } + if (!isNarrowingExpression(expression)) { + return antecedent; + } + setFlowNodeReferenced(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 }; + } + function createFlowAssignment(antecedent, node) { + setFlowNodeReferenced(antecedent); + return { flags: 16 /* Assignment */, antecedent: antecedent, node: node }; + } + function createFlowArrayMutation(antecedent, node) { + setFlowNodeReferenced(antecedent); + var res = { flags: 256 /* ArrayMutation */, antecedent: antecedent, node: node }; + return res; + } + function finishFlowLabel(flow) { + var antecedents = flow.antecedents; + if (!antecedents) { + return unreachableFlow; + } + if (antecedents.length === 1) { + return antecedents[0]; + } + return flow; + } + function isStatementCondition(node) { + var parent = node.parent; + switch (parent.kind) { + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: + return parent.expression === node; + case 223 /* ForStatement */: + case 203 /* ConditionalExpression */: + return parent.condition === node; + } + return false; + } + function isLogicalExpression(node) { + while (true) { + if (node.kind === 193 /* ParenthesizedExpression */) { + node = node.expression; + } + else if (node.kind === 200 /* PrefixUnaryExpression */ && node.operator === 51 /* ExclamationToken */) { + node = node.operand; + } + else { + return node.kind === 202 /* BinaryExpression */ && (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */ || + node.operatorToken.kind === 54 /* BarBarToken */); + } + } + } + function isTopLevelLogicalExpression(node) { + while (node.parent.kind === 193 /* ParenthesizedExpression */ || + node.parent.kind === 200 /* PrefixUnaryExpression */ && + node.parent.operator === 51 /* ExclamationToken */) { + node = node.parent; + } + return !isStatementCondition(node) && !isLogicalExpression(node.parent); + } + function bindCondition(node, trueTarget, falseTarget) { + var saveTrueTarget = currentTrueTarget; + var saveFalseTarget = currentFalseTarget; + currentTrueTarget = trueTarget; + currentFalseTarget = falseTarget; + bind(node); + currentTrueTarget = saveTrueTarget; + currentFalseTarget = saveFalseTarget; + if (!node || !isLogicalExpression(node)) { + addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node)); + addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node)); + } + } + function bindIterativeStatement(node, breakTarget, continueTarget) { + var saveBreakTarget = currentBreakTarget; + var saveContinueTarget = currentContinueTarget; + currentBreakTarget = breakTarget; + currentContinueTarget = continueTarget; + bind(node); + currentBreakTarget = saveBreakTarget; + currentContinueTarget = saveContinueTarget; + } + function bindWhileStatement(node) { + var preWhileLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postWhileLabel = createBranchLabel(); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = preWhileLabel; + bindCondition(node.expression, preBodyLabel, postWhileLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); + addAntecedent(preWhileLabel, currentFlow); + currentFlow = finishFlowLabel(postWhileLabel); + } + function bindDoStatement(node) { + var preDoLabel = createLoopLabel(); + var enclosingLabeledStatement = node.parent.kind === 231 /* LabeledStatement */ + ? ts.lastOrUndefined(activeLabels) + : undefined; + // if do statement is wrapped in labeled statement then target labels for break/continue with or without + // label should be the same + var preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel(); + var postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel(); + addAntecedent(preDoLabel, currentFlow); + currentFlow = preDoLabel; + bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); + addAntecedent(preConditionLabel, currentFlow); + currentFlow = finishFlowLabel(preConditionLabel); + bindCondition(node.expression, preDoLabel, postDoLabel); + currentFlow = finishFlowLabel(postDoLabel); + } + function bindForStatement(node) { + var preLoopLabel = createLoopLabel(); + var preBodyLabel = createBranchLabel(); + var postLoopLabel = createBranchLabel(); + bind(node.initializer); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + bindCondition(node.condition, preBodyLabel, postLoopLabel); + currentFlow = finishFlowLabel(preBodyLabel); + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + bind(node.incrementor); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindForInOrForOfStatement(node) { + var preLoopLabel = createLoopLabel(); + var postLoopLabel = createBranchLabel(); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = preLoopLabel; + if (node.kind === 225 /* ForOfStatement */) { + bind(node.awaitModifier); + } + bind(node.expression); + addAntecedent(postLoopLabel, currentFlow); + bind(node.initializer); + if (node.initializer.kind !== 236 /* VariableDeclarationList */) { + bindAssignmentTargetFlow(node.initializer); + } + bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); + addAntecedent(preLoopLabel, currentFlow); + currentFlow = finishFlowLabel(postLoopLabel); + } + function bindIfStatement(node) { + var thenLabel = createBranchLabel(); + var elseLabel = createBranchLabel(); + var postIfLabel = createBranchLabel(); + bindCondition(node.expression, thenLabel, elseLabel); + currentFlow = finishFlowLabel(thenLabel); + bind(node.thenStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(elseLabel); + bind(node.elseStatement); + addAntecedent(postIfLabel, currentFlow); + currentFlow = finishFlowLabel(postIfLabel); + } + function bindReturnOrThrow(node) { + bind(node.expression); + if (node.kind === 228 /* ReturnStatement */) { + hasExplicitReturn = true; + if (currentReturnTarget) { + addAntecedent(currentReturnTarget, currentFlow); + } + } + currentFlow = unreachableFlow; + } + function findActiveLabel(name) { + if (activeLabels) { + for (var _i = 0, activeLabels_1 = activeLabels; _i < activeLabels_1.length; _i++) { + var label = activeLabels_1[_i]; + if (label.name === name) { + return label; + } + } + } + return undefined; + } + function bindBreakOrContinueFlow(node, breakTarget, continueTarget) { + var flowLabel = node.kind === 227 /* BreakStatement */ ? breakTarget : continueTarget; + if (flowLabel) { + addAntecedent(flowLabel, currentFlow); + currentFlow = unreachableFlow; + } + } + function bindBreakOrContinueStatement(node) { + bind(node.label); + if (node.label) { + var activeLabel = findActiveLabel(node.label.escapedText); + if (activeLabel) { + activeLabel.referenced = true; + bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); + } + } + else { + bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); + } + } + function bindTryStatement(node) { + var preFinallyLabel = createBranchLabel(); + var preTryFlow = currentFlow; + // TODO: Every statement in try block is potentially an exit point! + bind(node.tryBlock); + addAntecedent(preFinallyLabel, currentFlow); + var flowAfterTry = currentFlow; + var flowAfterCatch = unreachableFlow; + if (node.catchClause) { + currentFlow = preTryFlow; + bind(node.catchClause); + addAntecedent(preFinallyLabel, currentFlow); + flowAfterCatch = currentFlow; + } + if (node.finallyBlock) { + // in finally flow is combined from pre-try/flow from try/flow from catch + // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); + currentFlow = finishFlowLabel(preFinallyLabel); + bind(node.finallyBlock); + // if flow after finally is unreachable - keep it + // otherwise check if flows after try and after catch are unreachable + // if yes - convert current flow to unreachable + // i.e. + // try { return "1" } finally { console.log(1); } + // console.log(2); // this line should be unreachable even if flow falls out of finally block + if (!(currentFlow.flags & 1 /* Unreachable */)) { + if ((flowAfterTry.flags & 1 /* Unreachable */) && (flowAfterCatch.flags & 1 /* Unreachable */)) { + currentFlow = flowAfterTry === reportedUnreachableFlow || flowAfterCatch === reportedUnreachableFlow + ? reportedUnreachableFlow + : unreachableFlow; + } + } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } + } + else { + currentFlow = finishFlowLabel(preFinallyLabel); + } + } + function bindSwitchStatement(node) { + var postSwitchLabel = createBranchLabel(); + bind(node.expression); + var saveBreakTarget = currentBreakTarget; + var savePreSwitchCaseFlow = preSwitchCaseFlow; + currentBreakTarget = postSwitchLabel; + preSwitchCaseFlow = currentFlow; + bind(node.caseBlock); + addAntecedent(postSwitchLabel, currentFlow); + var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 270 /* DefaultClause */; }); + // We mark a switch statement as possibly exhaustive if it has no default clause and if all + // case clauses have unreachable end points (e.g. they all return). + node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; + if (!hasDefault) { + addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); + } + currentBreakTarget = saveBreakTarget; + preSwitchCaseFlow = savePreSwitchCaseFlow; + currentFlow = finishFlowLabel(postSwitchLabel); + } + function bindCaseBlock(node) { + var savedSubtreeTransformFlags = subtreeTransformFlags; + subtreeTransformFlags = 0; + var clauses = node.clauses; + var fallthroughFlow = unreachableFlow; + for (var i = 0; i < clauses.length; i++) { + var clauseStart = i; + while (!clauses[i].statements.length && i + 1 < clauses.length) { + bind(clauses[i]); + i++; + } + var preCaseLabel = createBranchLabel(); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); + addAntecedent(preCaseLabel, fallthroughFlow); + currentFlow = finishFlowLabel(preCaseLabel); + var clause = clauses[i]; + bind(clause); + fallthroughFlow = currentFlow; + if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; + subtreeTransformFlags |= savedSubtreeTransformFlags; + } + function bindCaseClause(node) { + var saveCurrentFlow = currentFlow; + currentFlow = preSwitchCaseFlow; + bind(node.expression); + currentFlow = saveCurrentFlow; + bindEach(node.statements); + } + function pushActiveLabel(name, breakTarget, continueTarget) { + var activeLabel = { + name: name, + breakTarget: breakTarget, + continueTarget: continueTarget, + referenced: false + }; + (activeLabels || (activeLabels = [])).push(activeLabel); + return activeLabel; + } + function popActiveLabel() { + activeLabels.pop(); + } + function bindLabeledStatement(node) { + var preStatementLabel = createLoopLabel(); + var postStatementLabel = createBranchLabel(); + bind(node.label); + addAntecedent(preStatementLabel, currentFlow); + var activeLabel = pushActiveLabel(node.label.escapedText, postStatementLabel, preStatementLabel); + bind(node.statement); + popActiveLabel(); + if (!activeLabel.referenced && !options.allowUnusedLabels) { + errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label); + } + if (!node.statement || node.statement.kind !== 221 /* DoStatement */) { + // do statement sets current flow inside bindDoStatement + addAntecedent(postStatementLabel, currentFlow); + currentFlow = finishFlowLabel(postStatementLabel); + } + } + function bindDestructuringTargetFlow(node) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */) { + bindAssignmentTargetFlow(node.left); + } + else { + bindAssignmentTargetFlow(node); + } + } + function bindAssignmentTargetFlow(node) { + if (isNarrowableReference(node)) { + currentFlow = createFlowAssignment(currentFlow, node); + } + else if (node.kind === 185 /* ArrayLiteralExpression */) { + for (var _i = 0, _a = node.elements; _i < _a.length; _i++) { + var e = _a[_i]; + if (e.kind === 206 /* SpreadElement */) { + bindAssignmentTargetFlow(e.expression); + } + else { + bindDestructuringTargetFlow(e); + } + } + } + else if (node.kind === 186 /* ObjectLiteralExpression */) { + for (var _b = 0, _c = node.properties; _b < _c.length; _b++) { + var p = _c[_b]; + if (p.kind === 273 /* PropertyAssignment */) { + bindDestructuringTargetFlow(p.initializer); + } + else if (p.kind === 274 /* ShorthandPropertyAssignment */) { + bindAssignmentTargetFlow(p.name); + } + else if (p.kind === 275 /* SpreadAssignment */) { + bindAssignmentTargetFlow(p.expression); + } + } + } + } + function bindLogicalExpression(node, trueTarget, falseTarget) { + var preRightLabel = createBranchLabel(); + if (node.operatorToken.kind === 53 /* AmpersandAmpersandToken */) { + bindCondition(node.left, preRightLabel, falseTarget); + } + else { + bindCondition(node.left, trueTarget, preRightLabel); + } + currentFlow = finishFlowLabel(preRightLabel); + bind(node.operatorToken); + bindCondition(node.right, trueTarget, falseTarget); + } + function bindPrefixUnaryExpressionFlow(node) { + if (node.operator === 51 /* ExclamationToken */) { + var saveTrueTarget = currentTrueTarget; + currentTrueTarget = currentFalseTarget; + currentFalseTarget = saveTrueTarget; + bindEachChild(node); + currentFalseTarget = currentTrueTarget; + currentTrueTarget = saveTrueTarget; + } + else { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + } + function bindPostfixUnaryExpressionFlow(node) { + bindEachChild(node); + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + bindAssignmentTargetFlow(node.operand); + } + } + function bindBinaryExpressionFlow(node) { + var operator = node.operatorToken.kind; + if (operator === 53 /* AmpersandAmpersandToken */ || operator === 54 /* BarBarToken */) { + if (isTopLevelLogicalExpression(node)) { + var postExpressionLabel = createBranchLabel(); + bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); + currentFlow = finishFlowLabel(postExpressionLabel); + } + else { + bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); + } + } + else { + bindEachChild(node); + if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) { + bindAssignmentTargetFlow(node.left); + if (operator === 58 /* EqualsToken */ && node.left.kind === 188 /* ElementAccessExpression */) { + var elementAccess = node.left; + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + } + } + function bindDeleteExpressionFlow(node) { + bindEachChild(node); + if (node.expression.kind === 187 /* PropertyAccessExpression */) { + bindAssignmentTargetFlow(node.expression); + } + } + function bindConditionalExpressionFlow(node) { + var trueLabel = createBranchLabel(); + var falseLabel = createBranchLabel(); + var postExpressionLabel = createBranchLabel(); + bindCondition(node.condition, trueLabel, falseLabel); + currentFlow = finishFlowLabel(trueLabel); + bind(node.questionToken); + bind(node.whenTrue); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(falseLabel); + bind(node.colonToken); + bind(node.whenFalse); + addAntecedent(postExpressionLabel, currentFlow); + currentFlow = finishFlowLabel(postExpressionLabel); + } + function bindInitializedVariableFlow(node) { + var name = !ts.isOmittedExpression(node) ? node.name : undefined; + if (ts.isBindingPattern(name)) { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var child = _a[_i]; + bindInitializedVariableFlow(child); + } + } + else { + currentFlow = createFlowAssignment(currentFlow, node); + } + } + function bindVariableDeclarationFlow(node) { + bindEachChild(node); + if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) { + bindInitializedVariableFlow(node); + } + } + function bindJSDocTypeAlias(node) { + if (node.fullName) { + setParentPointers(node, node.fullName); + } + } + function bindCallExpressionFlow(node) { + // If the target of the call expression is a function expression or arrow function we have + // an immediately invoked function expression (IIFE). Initialize the flowNode property to + // the current control flow (which includes evaluation of the IIFE arguments). + var expr = node.expression; + while (expr.kind === 193 /* ParenthesizedExpression */) { + expr = expr.expression; + } + if (expr.kind === 194 /* FunctionExpression */ || expr.kind === 195 /* ArrowFunction */) { + bindEach(node.typeArguments); + bindEach(node.arguments); + bind(node.expression); + } + else { + bindEachChild(node); + } + if (node.expression.kind === 187 /* PropertyAccessExpression */) { + var propertyAccess = node.expression; + if (isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) { + currentFlow = createFlowArrayMutation(currentFlow, node); + } + } + } + function getContainerFlags(node) { + switch (node.kind) { + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 266 /* JsxAttributes */: + return 1 /* IsContainer */; + case 239 /* InterfaceDeclaration */: + return 1 /* IsContainer */ | 64 /* IsInterface */; + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: + return 1 /* IsContainer */ | 32 /* HasLocals */; + case 277 /* SourceFile */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 154 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } + // falls through + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 158 /* CallSignature */: + case 291 /* JSDocSignature */: + case 287 /* JSDocFunctionType */: + case 163 /* FunctionType */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 164 /* ConstructorType */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */; + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */; + case 243 /* ModuleBlock */: + return 4 /* IsControlFlowContainer */; + case 152 /* PropertyDeclaration */: + return node.initializer ? 4 /* IsControlFlowContainer */ : 0; + case 272 /* CatchClause */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 244 /* CaseBlock */: + return 2 /* IsBlockScopedContainer */; + case 216 /* Block */: + // do not treat blocks directly inside a function as a block-scoped-container. + // Locals that reside in this block should go to the function locals. Otherwise 'x' + // would not appear to be a redeclaration of a block scoped local in the following + // example: + // + // function foo() { + // var x; + // let x; + // } + // + // If we placed 'var x' into the function locals and 'let x' into the locals of + // the block, then there would be no collision. + // + // By not creating a new block-scoped-container here, we ensure that both 'var x' + // and 'let x' go into the Function-container's locals, and we do get a collision + // conflict. + return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */; + } + return 0 /* None */; + } + function addToContainerChain(next) { + if (lastContainer) { + lastContainer.nextContainer = next; + } + lastContainer = next; + } + function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { + switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. + case 242 /* ModuleDeclaration */: + return declareModuleMember(node, symbolFlags, symbolExcludes); + case 277 /* SourceFile */: + return declareSourceFileMember(node, symbolFlags, symbolExcludes); + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + return declareClassMember(node, symbolFlags, symbolExcludes); + case 241 /* EnumDeclaration */: + return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 186 /* ObjectLiteralExpression */: + case 239 /* InterfaceDeclaration */: + case 266 /* JsxAttributes */: + // Interface/Object-types always have their children added to the 'members' of + // their container. They are only accessible through an instance of their + // container, and are never in scope otherwise (even inside the body of the + // object / type / interface declaring them). An exception is type parameters, + // which are in scope without qualification (similar to 'locals'). + return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 291 /* JSDocSignature */: + case 160 /* IndexSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 287 /* JSDocFunctionType */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 240 /* TypeAliasDeclaration */: + case 179 /* MappedType */: + // All the children of these container types are never visible through another + // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, + // they're only accessed 'lexically' (i.e. from code that exists underneath + // their container in the tree). To accomplish this, we simply add their declared + // symbol to the 'locals' of the container. These symbols can then be found as + // the type checker walks up the containers, checking them for matching names. + return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function declareClassMember(node, symbolFlags, symbolExcludes) { + return ts.hasModifier(node, 32 /* Static */) + ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) + : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); + } + function declareSourceFileMember(node, symbolFlags, symbolExcludes) { + return ts.isExternalModule(file) + ? declareModuleMember(node, symbolFlags, symbolExcludes) + : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + function hasExportDeclarations(node) { + var body = node.kind === 277 /* SourceFile */ ? node : node.body; + if (body && (body.kind === 277 /* SourceFile */ || body.kind === 243 /* ModuleBlock */)) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var stat = _a[_i]; + if (stat.kind === 253 /* ExportDeclaration */ || stat.kind === 252 /* ExportAssignment */) { + return true; + } + } + } + return false; + } + function setExportContextFlag(node) { + // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular + // declarations with export modifiers) is an export context in which declarations are implicitly exported. + if (node.flags & 4194304 /* Ambient */ && !hasExportDeclarations(node)) { + node.flags |= 32 /* ExportContext */; + } + else { + node.flags &= ~32 /* ExportContext */; + } + } + function bindModuleDeclaration(node) { + setExportContextFlag(node); + if (ts.isAmbientModule(node)) { + if (ts.hasModifier(node, 1 /* Export */)) { + errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); + } + if (ts.isModuleAugmentationExternal(node)) { + declareModuleSymbol(node); + } + else { + var pattern = void 0; + if (node.name.kind === 9 /* StringLiteral */) { + var text = node.name.text; + if (ts.hasZeroOrOneAsteriskCharacter(text)) { + pattern = ts.tryParsePattern(text); + } + else { + errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); + } + } + var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 67215503 /* ValueModuleExcludes */); + file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol }); + } + } + else { + var state = declareModuleSymbol(node); + if (state !== 0 /* NonInstantiated */) { + var symbol = node.symbol; + // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only + symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) + // Current must be `const enum` only + && state === 2 /* ConstEnumOnly */ + // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK) + && symbol.constEnumOnlyModule !== false; + } + } + } + function declareModuleSymbol(node) { + var state = getModuleInstanceState(node); + var instantiated = state !== 0 /* NonInstantiated */; + declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 67215503 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */); + return state; + } + function bindFunctionOrConstructorType(node) { + // For a given function symbol "<...>(...) => T" we want to generate a symbol identical + // to the one we would get for: { <...>(...): T } + // + // We do that by making an anonymous type literal symbol, and then setting the function + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // from an actual type literal symbol you would have gotten had you used the long form. + var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217 + addDeclarationToSymbol(symbol, node, 131072 /* Signature */); + var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); + addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */); + typeLiteralSymbol.members = ts.createSymbolTable(); + 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++) { + var prop = _a[_i]; + if (prop.kind === 275 /* SpreadAssignment */ || prop.name.kind !== 71 /* Identifier */) { + continue; + } + var identifier = prop.name; + // ECMA-262 11.1.5 Object Initializer + // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true + // a.This production is contained in strict code and IsDataDescriptor(previous) is true and + // IsDataDescriptor(propId.descriptor) is true. + // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. + // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. + // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true + // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields + var currentKind = prop.kind === 273 /* PropertyAssignment */ || prop.kind === 274 /* ShorthandPropertyAssignment */ || prop.kind === 154 /* MethodDeclaration */ + ? 1 /* Property */ + : 2 /* Accessor */; + var existingKind = seen.get(identifier.escapedText); + if (!existingKind) { + seen.set(identifier.escapedText, currentKind); + continue; + } + if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { + var span = ts.getErrorSpanForNode(file, identifier); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); + } + } + } + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); + } + function bindJsxAttributes(node) { + return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */); + } + function bindJsxAttribute(node, symbolFlags, symbolExcludes) { + return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function bindAnonymousDeclaration(node, symbolFlags, name) { + var symbol = createSymbol(symbolFlags, name); + if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) { + symbol.parent = container.symbol; + } + addDeclarationToSymbol(symbol, node, symbolFlags); + return symbol; + } + function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) { + switch (blockScopeContainer.kind) { + case 242 /* ModuleDeclaration */: + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + case 277 /* SourceFile */: + if (ts.isExternalOrCommonJsModule(container)) { + declareModuleMember(node, symbolFlags, symbolExcludes); + break; + } + // falls through + default: + if (!blockScopeContainer.locals) { + blockScopeContainer.locals = ts.createSymbolTable(); + addToContainerChain(blockScopeContainer); + } + declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); + } + } + function bindBlockScopedVariableDeclaration(node) { + bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 67216319 /* BlockScopedVariableExcludes */); + } + function delayedBindJSDocTypedefTag() { + if (!delayedTypeAliases) { + return; + } + var saveContainer = container; + var saveLastContainer = lastContainer; + var saveBlockScopeContainer = blockScopeContainer; + var saveParent = parent; + var saveCurrentFlow = currentFlow; + for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) { + var typeAlias = delayedTypeAliases_1[_i]; + var host = ts.getJSDocHost(typeAlias); + container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; + blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; + currentFlow = { flags: 2 /* Start */ }; + parent = typeAlias; + bind(typeAlias.typeExpression); + if (!typeAlias.fullName || typeAlias.fullName.kind === 71 /* Identifier */) { + parent = typeAlias.parent; + bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + } + else { + bind(typeAlias.fullName); + } + } + container = saveContainer; + lastContainer = saveLastContainer; + blockScopeContainer = saveBlockScopeContainer; + parent = saveParent; + currentFlow = saveCurrentFlow; + } + // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized + // check for reserved words used as identifiers in strict mode code. + function checkStrictModeIdentifier(node) { + if (inStrictMode && + node.originalKeywordKind >= 108 /* FirstFutureReservedWord */ && + node.originalKeywordKind <= 116 /* LastFutureReservedWord */ && + !ts.isIdentifierName(node) && + !(node.flags & 4194304 /* Ambient */)) { + // Report error only if there are no parse errors in file + if (!file.parseDiagnostics.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node))); + } + } + } + function getStrictModeIdentifierMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; + } + function checkStrictModeBinaryExpression(node) { + if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) { + // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) + checkStrictModeEvalOrArguments(node, node.left); + } + } + function checkStrictModeCatchClause(node) { + // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the + // Catch production is eval or arguments + if (inStrictMode && node.variableDeclaration) { + checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); + } + } + function checkStrictModeDeleteExpression(node) { + // Grammar checking + if (inStrictMode && node.expression.kind === 71 /* Identifier */) { + // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its + // UnaryExpression is a direct reference to a variable, function argument, or function name + var span = ts.getErrorSpanForNode(file, node.expression); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); + } + } + function isEvalOrArgumentsIdentifier(node) { + return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); + } + function checkStrictModeEvalOrArguments(contextNode, name) { + if (name && name.kind === 71 /* Identifier */) { + var identifier = name; + if (isEvalOrArgumentsIdentifier(identifier)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var span = ts.getErrorSpanForNode(file, name); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier))); + } + } + } + function getStrictModeEvalOrArgumentsMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Invalid_use_of_0_in_strict_mode; + } + function checkStrictModeFunctionName(node) { + if (inStrictMode) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) + checkStrictModeEvalOrArguments(node, node.name); + } + } + function getStrictModeBlockScopeFunctionDeclarationMessage(node) { + // Provide specialized messages to help the user understand why we think they're in + // strict mode. + if (ts.getContainingClass(node)) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; + } + if (file.externalModuleIndicator) { + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; + } + return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; + } + function checkStrictModeFunctionDeclaration(node) { + if (languageVersion < 2 /* ES2015 */) { + // Report error if function is not top level function declaration + if (blockScopeContainer.kind !== 277 /* SourceFile */ && + blockScopeContainer.kind !== 242 /* ModuleDeclaration */ && + !ts.isFunctionLike(blockScopeContainer)) { + // We check first if the name is inside class declaration or class expression; if so give explicit message + // otherwise report generic error message. + var errorSpan = ts.getErrorSpanForNode(file, node); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node))); + } + } + } + function checkStrictModeNumericLiteral(node) { + if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); + } + } + function checkStrictModePostfixUnaryExpression(node) { + // Grammar checking + // The identifier eval or arguments may not appear as the LeftHandSideExpression of an + // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression + // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + function checkStrictModePrefixUnaryExpression(node) { + // Grammar checking + if (inStrictMode) { + if (node.operator === 43 /* PlusPlusToken */ || node.operator === 44 /* MinusMinusToken */) { + checkStrictModeEvalOrArguments(node, node.operand); + } + } + } + function checkStrictModeWithStatement(node) { + // Grammar checking for withStatement + if (inStrictMode) { + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + } + } + function errorOnFirstToken(node, message, arg0, arg1, arg2) { + var span = ts.getSpanOfTokenAtPosition(file, node.pos); + file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); + } + function errorOrSuggestionOnNode(isError, node, message) { + errorOrSuggestionOnRange(isError, node, node, message); + } + function errorOrSuggestionOnRange(isError, startNode, endNode, message) { + addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message); + } + function addErrorOrSuggestionDiagnostic(isError, range, message) { + var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message); + if (isError) { + file.bindDiagnostics.push(diag); + } + else { + file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function bind(node) { + if (!node) { + return; + } + node.parent = parent; + var saveInStrictMode = inStrictMode; + // Even though in the AST the jsdoc @typedef node belongs to the current node, + // its symbol might be in the same scope with the current node's symbol. Consider: + // + // /** @typedef {string | number} MyType */ + // function foo(); + // + // Here the current node is "foo", which is a container, but the scope of "MyType" should + // not be inside "foo". Therefore we always bind @typedef before bind the parent node, + // and skip binding this tag later when binding all the other jsdoc tags. + // First we bind declaration nodes to a symbol if possible. We'll both create a symbol + // and then potentially add the symbol to an appropriate symbol table. Possible + // destination symbol tables are: + // + // 1) The 'exports' table of the current container's symbol. + // 2) The 'members' table of the current container's symbol. + // 3) The 'locals' table of the current container. + // + // However, not all symbols will end up in any of these tables. 'Anonymous' symbols + // (like TypeLiterals for example) will not be put in any table. + bindWorker(node); + // Then we recurse into the children of the node to bind them as well. For certain + // symbols we do specialized work when we recurse. For example, we'll keep track of + // the current 'container' node when it changes. This helps us know which symbol table + // a local should go into for example. Since terminal nodes are known not to have + // children, as an optimization we don't process those. + if (node.kind > 145 /* LastToken */) { + var saveParent = parent; + parent = node; + var containerFlags = getContainerFlags(node); + if (containerFlags === 0 /* None */) { + bindChildren(node); + } + else { + bindContainer(node, containerFlags); + } + parent = saveParent; + } + else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) { + subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); + var saveParent = parent; + if (node.kind === 1 /* EndOfFileToken */) + parent = node; + bindJSDoc(node); + parent = saveParent; + } + inStrictMode = saveInStrictMode; + } + function bindJSDoc(node) { + if (ts.hasJSDocNodes(node)) { + if (ts.isInJavaScriptFile(node)) { + for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { + var j = _a[_i]; + bind(j); + } + } + else { + for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) { + var j = _c[_b]; + setParentPointers(node, j); + } + } + } + } + function updateStrictModeStatementList(statements) { + if (!inStrictMode) { + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; + if (!ts.isPrologueDirective(statement)) { + return; + } + if (isUseStrictPrologueDirective(statement)) { + inStrictMode = true; + return; + } + } + } + } + /// Should be called only on prologue directives (isPrologueDirective(node) should be true) + function isUseStrictPrologueDirective(node) { + var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression); + // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the + // string to contain unicode escapes (as per ES5). + return nodeText === '"use strict"' || nodeText === "'use strict'"; + } + function bindWorker(node) { + switch (node.kind) { + /* Strict mode checks */ + case 71 /* Identifier */: + // for typedef type names with namespaces, bind the new jsdoc type symbol here + // because it requires all containing namespaces to be in effect, namely the + // current "blockScopeContainer" needs to be set to its immediate namespace parent. + if (node.isInJSDocNamespace) { + var parentNode = node.parent; + while (parentNode && !ts.isJSDocTypeAlias(parentNode)) { + parentNode = parentNode.parent; + } + bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + break; + } + // falls through + case 99 /* ThisKeyword */: + if (currentFlow && (ts.isExpression(node) || parent.kind === 274 /* ShorthandPropertyAssignment */)) { + node.flowNode = currentFlow; + } + return checkStrictModeIdentifier(node); + case 187 /* PropertyAccessExpression */: + if (currentFlow && isNarrowableReference(node)) { + node.flowNode = currentFlow; + } + if (ts.isSpecialPropertyDeclaration(node)) { + bindSpecialPropertyDeclaration(node); + } + break; + case 202 /* BinaryExpression */: + var specialKind = ts.getSpecialPropertyAssignmentKind(node); + switch (specialKind) { + case 1 /* ExportsProperty */: + bindExportsPropertyAssignment(node); + break; + case 2 /* ModuleExports */: + bindModuleExportsAssignment(node); + break; + case 3 /* PrototypeProperty */: + bindPrototypePropertyAssignment(node.left, node); + break; + case 6 /* Prototype */: + bindPrototypeAssignment(node); + break; + case 4 /* ThisProperty */: + bindThisPropertyAssignment(node); + break; + case 5 /* Property */: + bindSpecialPropertyAssignment(node); + break; + case 0 /* None */: + // Nothing to do + break; + default: + ts.Debug.fail("Unknown special property assignment kind"); + } + return checkStrictModeBinaryExpression(node); + case 272 /* CatchClause */: + return checkStrictModeCatchClause(node); + case 196 /* DeleteExpression */: + return checkStrictModeDeleteExpression(node); + case 8 /* NumericLiteral */: + return checkStrictModeNumericLiteral(node); + case 201 /* PostfixUnaryExpression */: + return checkStrictModePostfixUnaryExpression(node); + case 200 /* PrefixUnaryExpression */: + return checkStrictModePrefixUnaryExpression(node); + case 229 /* WithStatement */: + return checkStrictModeWithStatement(node); + case 176 /* ThisType */: + seenThisKeyword = true; + return; + case 161 /* TypePredicate */: + break; // Binding the children will handle everything + case 148 /* TypeParameter */: + return bindTypeParameter(node); + case 149 /* Parameter */: + return bindParameter(node); + case 235 /* VariableDeclaration */: + return bindVariableDeclarationOrBindingElement(node); + case 184 /* BindingElement */: + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + return bindPropertyWorker(node); + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */); + case 276 /* EnumMember */: + return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 68008959 /* EnumMemberExcludes */); + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */); + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + // If this is an ObjectLiteralExpression method, then it sits in the same space + // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes + // so that it will conflict with any other object literal members with the same + // name. + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 67208127 /* MethodExcludes */); + case 237 /* FunctionDeclaration */: + return bindFunctionDeclaration(node); + case 155 /* Constructor */: + return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */); + case 156 /* GetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 67150783 /* GetAccessorExcludes */); + case 157 /* SetAccessor */: + return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 67183551 /* SetAccessorExcludes */); + case 163 /* FunctionType */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: + case 164 /* ConstructorType */: + return bindFunctionOrConstructorType(node); + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 179 /* MappedType */: + return bindAnonymousTypeWorker(node); + case 186 /* ObjectLiteralExpression */: + return bindObjectLiteralExpression(node); + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + return bindFunctionExpression(node); + case 189 /* CallExpression */: + if (ts.isInJavaScriptFile(node)) { + bindCallExpression(node); + } + break; + // Members of classes, interfaces, and modules + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + // All classes are automatically in strict mode in ES6. + inStrictMode = true; + return bindClassLikeDeclaration(node); + case 239 /* InterfaceDeclaration */: + return bindBlockScopedDeclaration(node, 64 /* Interface */, 67901832 /* InterfaceExcludes */); + case 240 /* TypeAliasDeclaration */: + return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 67901928 /* TypeAliasExcludes */); + case 241 /* EnumDeclaration */: + return bindEnumDeclaration(node); + case 242 /* ModuleDeclaration */: + return bindModuleDeclaration(node); + // Jsx-attributes + case 266 /* JsxAttributes */: + return bindJsxAttributes(node); + case 265 /* JsxAttribute */: + return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: + return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + case 245 /* NamespaceExportDeclaration */: + return bindNamespaceExportDeclaration(node); + case 248 /* ImportClause */: + return bindImportClause(node); + case 253 /* ExportDeclaration */: + return bindExportDeclaration(node); + case 252 /* ExportAssignment */: + return bindExportAssignment(node); + case 277 /* SourceFile */: + updateStrictModeStatementList(node.statements); + return bindSourceFileIfExternalModule(); + case 216 /* Block */: + if (!ts.isFunctionLike(node.parent)) { + return; + } + // falls through + case 243 /* ModuleBlock */: + return updateStrictModeStatementList(node.statements); + case 296 /* JSDocParameterTag */: + if (node.parent.kind === 291 /* JSDocSignature */) { + return bindParameter(node); + } + if (node.parent.kind !== 290 /* JSDocTypeLiteral */) { + break; + } + // falls through + case 302 /* JSDocPropertyTag */: + var propTag = node; + var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 286 /* JSDocOptionalType */ ? + 4 /* Property */ | 16777216 /* Optional */ : + 4 /* Property */; + return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */); + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); + } + } + function bindPropertyWorker(node) { + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + function bindAnonymousTypeWorker(node) { + return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */); + } + function bindSourceFileIfExternalModule() { + setExportContextFlag(file); + if (ts.isExternalModule(file)) { + bindSourceFileAsExternalModule(); + } + else if (ts.isJsonSourceFile(file)) { + bindSourceFileAsExternalModule(); + // Create symbol equivalent for the module.exports = {} + var originalSymbol = file.symbol; + declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */); + file.symbol = originalSymbol; + } + } + function bindSourceFileAsExternalModule() { + bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\""); + } + function bindExportAssignment(node) { + if (!container.symbol || !container.symbol.exports) { + // Export assignment in some sort of block construct + bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node)); + } + else { + var flags = node.kind === 252 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) + // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; + ? 2097152 /* Alias */ + // An export default clause with any other expression exports a value + : 4 /* Property */; + // If there is an `export default x;` alias declaration, can't `export default` anything else. + // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) + declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */); + } + } + function bindNamespaceExportDeclaration(node) { + if (node.modifiers && node.modifiers.length) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here)); + } + if (node.parent.kind !== 277 /* SourceFile */) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level)); + return; + } + else { + var parent_1 = node.parent; + if (!ts.isExternalModule(parent_1)) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); + return; + } + if (!parent_1.isDeclarationFile) { + file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); + return; + } + } + file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable(); + declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + function bindExportDeclaration(node) { + if (!container.symbol || !container.symbol.exports) { + // Export * in some sort of block construct + bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node)); + } + else if (!node.exportClause) { + // All export * declarations are collected in an __export symbol + declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */); + } + } + function bindImportClause(node) { + if (node.name) { + declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); + } + } + function setCommonJsModuleIndicator(node) { + if (file.externalModuleIndicator) { + return false; + } + if (!file.commonJsModuleIndicator) { + file.commonJsModuleIndicator = node; + bindSourceFileAsExternalModule(); + } + return true; + } + function bindExportsPropertyAssignment(node) { + // When we create a property via 'exports.foo = bar', the 'exports.foo' property access + // expression is the declaration + if (!setCommonJsModuleIndicator(node)) { + return; + } + var lhs = node.left; + var symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, function (id, symbol) { + if (symbol) { + addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* JSContainer */); + } + return symbol; + }); + if (symbol) { + var flags = ts.isClassExpression(node.right) ? + 4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ : + 4 /* Property */ | 1048576 /* ExportValue */; + declareSymbol(symbol.exports, symbol, lhs, flags, 0 /* None */); + } + } + function bindModuleExportsAssignment(node) { + // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports' + // is still pointing to 'module.exports'. + // We do not want to consider this as 'export=' since a module can have only one of these. + // Similarly we do not want to treat 'module.exports = exports' as an 'export='. + if (!setCommonJsModuleIndicator(node)) { + return; + } + var assignedExpression = ts.getRightMostAssignedExpression(node.right); + if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) { + return; + } + // 'module.exports = expr' assignment + var flags = ts.exportAssignmentIsAlias(node) + ? 2097152 /* Alias */ + : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; + declareSymbol(file.symbol.exports, file.symbol, node, flags, 0 /* None */); + } + function bindThisPropertyAssignment(node) { + ts.Debug.assert(ts.isInJavaScriptFile(node)); + var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false); + switch (thisContainer.kind) { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + var constructorSymbol = thisContainer.symbol; + // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression. + if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 58 /* EqualsToken */) { + var l = thisContainer.parent.left; + if (ts.isPropertyAccessEntityNameExpression(l) && ts.isPrototypeAccess(l.expression)) { + constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer); + } + } + if (constructorSymbol) { + // Declare a 'member' if the container is an ES5 class or ES6 constructor + constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable(); + // It's acceptable for multiple 'this' assignments of the same identifier to occur + declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */, 0 /* PropertyExcludes */ & ~4 /* Property */); + } + break; + case 155 /* Constructor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + // this.foo assignment in a JavaScript class + // Bind this property to the containing class + var containingClass = thisContainer.parent; + var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members; + declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */, 0 /* None */, /*isReplaceableByMethod*/ true); + break; + case 277 /* SourceFile */: + // this.foo assignment in a source file + // Do not bind. It would be nice to support this someday though. + break; + default: + ts.Debug.fail(ts.Debug.showSyntaxKind(thisContainer)); + } + } + function bindSpecialPropertyDeclaration(node) { + if (node.expression.kind === 99 /* ThisKeyword */) { + bindThisPropertyAssignment(node); + } + else if (ts.isPropertyAccessEntityNameExpression(node) && node.parent.parent.kind === 277 /* SourceFile */) { + if (ts.isPrototypeAccess(node.expression)) { + bindPrototypePropertyAssignment(node, node.parent); + } + else { + bindStaticPropertyAssignment(node); + } + } + } + /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */ + function bindPrototypeAssignment(node) { + node.left.parent = node; + node.right.parent = node; + var lhs = node.left; + bindPropertyAssignment(lhs, lhs, /*isPrototypeProperty*/ false); + } + /** + * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared. + * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration. + */ + function bindPrototypePropertyAssignment(lhs, parent) { + // Look up the function in the local scope, since prototype assignments should + // follow the function declaration + var classPrototype = lhs.expression; + var constructorFunction = classPrototype.expression; + // Fix up parent pointers since we're going to use these nodes before we bind into them + lhs.parent = parent; + constructorFunction.parent = classPrototype; + classPrototype.parent = lhs; + bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true); + } + function bindSpecialPropertyAssignment(node) { + var lhs = node.left; + // Fix up parent pointers since we're going to use these nodes before we bind into them + node.left.parent = node; + node.right.parent = node; + if (ts.isIdentifier(lhs.expression) && container === file && isNameOfExportsOrModuleExportsAliasDeclaration(file, lhs.expression)) { + // This can be an alias for the 'exports' or 'module.exports' names, e.g. + // var util = module.exports; + // util.property = function ... + bindExportsPropertyAssignment(node); + } + else { + bindStaticPropertyAssignment(lhs); + } + } + /** + * For nodes like `x.y = z`, declare a member 'y' on 'x' if x is a function (or IIFE) or class or {}, or not declared. + * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y; + */ + function bindStaticPropertyAssignment(node) { + node.expression.parent = node; + bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false); + } + function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty) { + var namespaceSymbol = lookupSymbolForPropertyAccess(name); + var isToplevelNamespaceableInitializer = ts.isBinaryExpression(propertyAccess.parent) + ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 277 /* SourceFile */ && + !!ts.getJavascriptInitializer(ts.getInitializerOfBinaryExpression(propertyAccess.parent), ts.isPrototypeAccess(propertyAccess.parent.left)) + : propertyAccess.parent.parent.kind === 277 /* SourceFile */; + if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & 1920 /* Namespace */)) && isToplevelNamespaceableInitializer) { + // make symbols or add declarations for intermediate containers + var flags_1 = 1536 /* Module */ | 67108864 /* JSContainer */; + var excludeFlags_1 = 67215503 /* ValueModuleExcludes */ & ~67108864 /* JSContainer */; + namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, function (id, symbol, parent) { + if (symbol) { + addDeclarationToSymbol(symbol, id, flags_1); + return symbol; + } + else { + return declareSymbol(parent ? parent.exports : container.locals, parent, id, flags_1, excludeFlags_1); + } + }); + } + if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + return; + } + // Set up the members collection if it doesn't exist already + var symbolTable = isPrototypeProperty ? + (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) : + (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable())); + // Declare the method/property + var jsContainerFlag = isToplevelNamespaceableInitializer ? 67108864 /* JSContainer */ : 0; + var isMethod = ts.isFunctionLikeDeclaration(ts.getAssignedJavascriptInitializer(propertyAccess)); + var symbolFlags = (isMethod ? 8192 /* Method */ : 4 /* Property */) | jsContainerFlag; + var symbolExcludes = (isMethod ? 67208127 /* MethodExcludes */ : 0 /* PropertyExcludes */) & ~jsContainerFlag; + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, symbolFlags, symbolExcludes); + } + /** + * Javascript containers are: + * - Functions + * - classes + * - namespaces + * - variables initialized with function expressions + * - with class expressions + * - with empty object literals + * - with non-empty object literals if assigned to the prototype property + */ + function isJavascriptContainer(symbol) { + if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) { + return true; + } + var node = symbol.valueDeclaration; + var init = !node ? undefined : + ts.isVariableDeclaration(node) ? node.initializer : + ts.isBinaryExpression(node) ? node.right : + ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right : + undefined; + init = init && ts.getRightMostAssignedExpression(init); + if (init) { + var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node); + return !!ts.getJavascriptInitializer(ts.isBinaryExpression(init) && init.operatorToken.kind === 54 /* BarBarToken */ ? init.right : init, isPrototypeAssignment); + } + return false; + } + function getParentOfBinaryExpression(expr) { + while (ts.isBinaryExpression(expr.parent)) { + expr = expr.parent; + } + return expr.parent; + } + function lookupSymbolForPropertyAccess(node, lookupContainer) { + if (lookupContainer === void 0) { lookupContainer = container; } + if (ts.isIdentifier(node)) { + return lookupSymbolForNameWorker(lookupContainer, node.escapedText); + } + else { + var symbol = lookupSymbolForPropertyAccess(node.expression); + return symbol && symbol.exports && symbol.exports.get(node.name.escapedText); + } + } + function forEachIdentifierInEntityName(e, parent, action) { + if (isExportsOrModuleExportsOrAlias(file, e)) { + return file.symbol; + } + else if (ts.isIdentifier(e)) { + return action(e, lookupSymbolForPropertyAccess(e), parent); + } + else { + var s = forEachIdentifierInEntityName(e.expression, parent, action); + if (!s || !s.exports) + return ts.Debug.fail(); + return action(e.name, s.exports.get(e.name.escapedText), s); + } + } + function bindCallExpression(node) { + // We're only inspecting call expressions to detect CommonJS modules, so we can skip + // this check if we've already seen the module indicator + if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) { + setCommonJsModuleIndicator(node); + } + } + function bindClassLikeDeclaration(node) { + if (node.kind === 238 /* ClassDeclaration */) { + bindBlockScopedDeclaration(node, 32 /* Class */, 68008383 /* ClassExcludes */); + } + else { + var bindingName = node.name ? node.name.escapedText : "__class" /* Class */; + bindAnonymousDeclaration(node, 32 /* Class */, bindingName); + // Add name of class expression into the map for semantic classifier + if (node.name) { + classifiableNames.set(node.name.escapedText, true); + } + } + var symbol = node.symbol; + // TypeScript 1.0 spec (April 2014): 8.4 + // Every class automatically contains a static property member named 'prototype', the + // type of which is an instantiation of the class type with type Any supplied as a type + // argument for each type parameter. It is an error to explicitly declare a static + // property member with the name 'prototype'. + // + // Note: we check for this here because this class may be merging into a module. The + // module might have an exported variable called 'prototype'. We can't allow that as + // that would clash with the built-in 'prototype' for the class. + var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype"); + var symbolExport = symbol.exports.get(prototypeSymbol.escapedName); + if (symbolExport) { + if (node.name) { + node.name.parent = node; + } + file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol))); + } + symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol); + prototypeSymbol.parent = symbol; + } + function bindEnumDeclaration(node) { + return ts.isEnumConst(node) + ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 68008831 /* ConstEnumExcludes */) + : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 68008191 /* RegularEnumExcludes */); + } + function bindVariableDeclarationOrBindingElement(node) { + if (inStrictMode) { + checkStrictModeEvalOrArguments(node, node.name); + } + if (!ts.isBindingPattern(node.name)) { + if (ts.isBlockOrCatchScoped(node)) { + bindBlockScopedVariableDeclaration(node); + } + else if (ts.isParameterDeclaration(node)) { + // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration + // because its parent chain has already been set up, since parents are set before descending into children. + // + // If node is a binding element in parameter declaration, we need to use ParameterExcludes. + // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration + // For example: + // function foo([a,a]) {} // Duplicate Identifier error + // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter + // // which correctly set excluded symbols + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216318 /* FunctionScopedVariableExcludes */); + } + } + } + function bindParameter(node) { + if (node.kind === 296 /* JSDocParameterTag */ && container.kind !== 291 /* JSDocSignature */) { + return; + } + if (inStrictMode && !(node.flags & 4194304 /* Ambient */)) { + // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a + // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) + checkStrictModeEvalOrArguments(node, node.name); + } + if (ts.isBindingPattern(node.name)) { + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); + } + else { + declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 67216319 /* ParameterExcludes */); + } + // If this is a property-parameter, then also declare the property symbol into the + // containing class. + if (ts.isParameterPropertyDeclaration(node)) { + var classDeclaration = node.parent.parent; + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + } + } + function bindFunctionDeclaration(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + checkStrictModeFunctionName(node); + if (inStrictMode) { + checkStrictModeFunctionDeclaration(node); + bindBlockScopedDeclaration(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 67215791 /* FunctionExcludes */); + } + } + function bindFunctionExpression(node) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */)) { + if (ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + } + if (currentFlow) { + node.flowNode = currentFlow; + } + checkStrictModeFunctionName(node); + var bindingName = node.name ? node.name.escapedText : "__function" /* Function */; + return bindAnonymousDeclaration(node, 16 /* Function */, bindingName); + } + function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) { + if (!file.isDeclarationFile && !(node.flags & 4194304 /* Ambient */) && ts.isAsyncFunction(node)) { + emitFlags |= 1024 /* HasAsyncFunctions */; + } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return ts.hasDynamicName(node) + ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */) + : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); + } + function getInferTypeContainer(node) { + var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; }); + return extendsType && extendsType.parent; + } + function bindTypeParameter(node) { + if (ts.isJSDocTemplateTag(node.parent)) { + var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217 + if (container_1) { + if (!container_1.locals) { + container_1.locals = ts.createSymbolTable(); + } + declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + else if (node.parent.kind === 174 /* InferType */) { + var container_2 = getInferTypeContainer(node.parent); + if (container_2) { + if (!container_2.locals) { + container_2.locals = ts.createSymbolTable(); + } + declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + else { + bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217 + } + } + else { + declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 67639784 /* TypeParameterExcludes */); + } + } + // reachability checks + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums); + } + function checkUnreachable(node) { + if (!(currentFlow.flags & 1 /* Unreachable */)) { + return false; + } + if (currentFlow === unreachableFlow) { + var reportError = + // report error on all statements except empty ones + (ts.isStatementButNotDeclaration(node) && node.kind !== 218 /* EmptyStatement */) || + // report error on class declarations + node.kind === 238 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 242 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (ts.isEnumDeclaration(node) && (!ts.isEnumConst(node) || options.preserveConstEnums)); + if (reportError) { + currentFlow = reportedUnreachableFlow; + if (!options.allowUnreachableCode) { + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var isError_1 = ts.unreachableCodeIsError(options) && + !(node.flags & 4194304 /* Ambient */) && + (!ts.isVariableStatement(node) || + !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) || + node.declarationList.declarations.some(function (d) { return !!d.initializer; })); + eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); }); + } + } + } + return true; + } + } + function eachUnreachableRange(node, cb) { + if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) { + var statements = node.parent.statements; + var slice_1 = ts.sliceAfter(statements, node); + ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); }); + } + else { + cb(node, node); + } + } + // As opposed to a pure declaration like an `interface` + function isExecutableStatement(s) { + // Don't remove statements that can validly be used before they appear. + return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + // `var x;` may declare a variable used above + !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; })); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return true; + case 242 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 241 /* EnumDeclaration */: + return ts.hasModifier(s, 2048 /* Const */); + default: + return false; + } + } + /* @internal */ + function isExportsOrModuleExportsOrAlias(sourceFile, node) { + return ts.isExportsIdentifier(node) || + ts.isModuleExportsPropertyAccessExpression(node) || + ts.isIdentifier(node) && isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node); + } + ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias; + function isNameOfExportsOrModuleExportsAliasDeclaration(sourceFile, node) { + var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText); + return !!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && + !!symbol.valueDeclaration.initializer && isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, symbol.valueDeclaration.initializer); + } + function isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node) { + return isExportsOrModuleExportsOrAlias(sourceFile, node) || + (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && (isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.left) || isExportsOrModuleExportsOrAliasOrAssignment(sourceFile, node.right))); + } + function lookupSymbolForNameWorker(container, name) { + var local = container.locals && container.locals.get(name); + if (local) { + return local.exportSymbol || local; + } + return container.symbol && container.symbol.exports && container.symbol.exports.get(name); + } + /** + * Computes the transform flags for a node, given the transform flags of its subtree + * + * @param node The node to analyze + * @param subtreeFlags Transform flags computed for this node's subtree + */ + function computeTransformFlagsForNode(node, subtreeFlags) { + var kind = node.kind; + switch (kind) { + case 189 /* CallExpression */: + return computeCallExpression(node, subtreeFlags); + case 190 /* NewExpression */: + return computeNewExpression(node, subtreeFlags); + case 242 /* ModuleDeclaration */: + return computeModuleDeclaration(node, subtreeFlags); + case 193 /* ParenthesizedExpression */: + return computeParenthesizedExpression(node, subtreeFlags); + case 202 /* BinaryExpression */: + return computeBinaryExpression(node, subtreeFlags); + case 219 /* ExpressionStatement */: + return computeExpressionStatement(node, subtreeFlags); + case 149 /* Parameter */: + return computeParameter(node, subtreeFlags); + case 195 /* ArrowFunction */: + return computeArrowFunction(node, subtreeFlags); + case 194 /* FunctionExpression */: + return computeFunctionExpression(node, subtreeFlags); + case 237 /* FunctionDeclaration */: + return computeFunctionDeclaration(node, subtreeFlags); + case 235 /* VariableDeclaration */: + return computeVariableDeclaration(node, subtreeFlags); + case 236 /* VariableDeclarationList */: + return computeVariableDeclarationList(node, subtreeFlags); + case 217 /* VariableStatement */: + return computeVariableStatement(node, subtreeFlags); + case 231 /* LabeledStatement */: + return computeLabeledStatement(node, subtreeFlags); + case 238 /* ClassDeclaration */: + return computeClassDeclaration(node, subtreeFlags); + case 207 /* ClassExpression */: + return computeClassExpression(node, subtreeFlags); + case 271 /* HeritageClause */: + return computeHeritageClause(node, subtreeFlags); + case 272 /* CatchClause */: + return computeCatchClause(node, subtreeFlags); + case 209 /* ExpressionWithTypeArguments */: + return computeExpressionWithTypeArguments(node, subtreeFlags); + case 155 /* Constructor */: + return computeConstructor(node, subtreeFlags); + case 152 /* PropertyDeclaration */: + return computePropertyDeclaration(node, subtreeFlags); + case 154 /* MethodDeclaration */: + return computeMethod(node, subtreeFlags); + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return computeAccessor(node, subtreeFlags); + case 246 /* ImportEqualsDeclaration */: + return computeImportEquals(node, subtreeFlags); + case 187 /* PropertyAccessExpression */: + return computePropertyAccess(node, subtreeFlags); + case 188 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); + default: + return computeOther(node, kind, subtreeFlags); + } + } + ts.computeTransformFlagsForNode = computeTransformFlagsForNode; + function computeCallExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */ + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { + // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + if (expression.kind === 91 /* ImportKeyword */) { + transformFlags |= 67108864 /* ContainsDynamicImport */; + // A dynamic 'import()' call that contains a lexical 'this' will + // require a captured 'this' when emitting down-level. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeNewExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; + } + function computeBinaryExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var operatorTokenKind = node.operatorToken.kind; + var leftKind = node.left.kind; + if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 186 /* ObjectLiteralExpression */) { + // Destructuring object assignments with are ES2015 syntax + // and possibly ESNext if they contain rest + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 58 /* EqualsToken */ && leftKind === 185 /* ArrayLiteralExpression */) { + // Destructuring assignments are ES2015 syntax. + transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + } + else if (operatorTokenKind === 40 /* AsteriskAsteriskToken */ + || operatorTokenKind === 62 /* AsteriskAsteriskEqualsToken */) { + // Exponentiation is ES2016 syntax. + transformFlags |= 32 /* AssertES2016 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeParameter(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var name = node.name; + var initializer = node.initializer; + var dotDotDotToken = node.dotDotDotToken; + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & 4096 /* ContainsDecorators */ + || ts.isThisIdentifier(name)) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If a parameter has an accessibility modifier, then it is TypeScript syntax. + if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { + transformFlags |= 3 /* AssertTypeScript */ | 262144 /* ContainsParameterPropertyAssignments */; + } + // parameters with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a parameter has an initializer, a binding pattern or a dotDotDot token, then + // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. + if (subtreeFlags & 8388608 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* ParameterExcludes */; + } + function computeParenthesizedExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionKind = expression.kind; + var expressionTransformFlags = expression.transformFlags; + // If the node is synthesized, it means the emitter put the parentheses there, + // not the user. If we didn't want them, the emitter would not have put them + // there. + if (expressionKind === 210 /* AsExpression */ + || expressionKind === 192 /* TypeAssertionExpression */) { + transformFlags |= 3 /* AssertTypeScript */; + } + // If the expression of a ParenthesizedExpression is a destructuring assignment, + // then the ParenthesizedExpression is a destructuring assignment. + if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 1024 /* DestructuringAssignment */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; + } + function computeClassDeclaration(node, subtreeFlags) { + var transformFlags; + if (ts.hasModifier(node, 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + // A ClassDeclaration is ES6 syntax. + transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, computed property name, or decorator is + // TypeScript syntax. + // An exported declaration may be TypeScript syntax, but is handled by the visitor + // for a namespace declaration. + if ((subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */) + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~942011713 /* ClassExcludes */; + } + function computeClassExpression(node, subtreeFlags) { + // A ClassExpression is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // A class with a parameter property assignment, property initializer, or decorator is + // TypeScript syntax. + if (subtreeFlags & 274432 /* TypeScriptClassSyntaxMask */ + || node.typeParameters) { + transformFlags |= 3 /* AssertTypeScript */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~942011713 /* ClassExcludes */; + } + function computeHeritageClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + switch (node.token) { + case 85 /* ExtendsKeyword */: + // An `extends` HeritageClause is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 108 /* ImplementsKeyword */: + // An `implements` HeritageClause is TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + default: + ts.Debug.fail("Unexpected token for heritage clause"); + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeCatchClause(node, subtreeFlags) { + var transformFlags = subtreeFlags; + if (!node.variableDeclaration) { + transformFlags |= 8 /* AssertESNext */; + } + else if (ts.isBindingPattern(node.variableDeclaration.name)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; + } + function computeExpressionWithTypeArguments(node, subtreeFlags) { + // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the + // extends clause of a class. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // If an ExpressionWithTypeArguments contains type arguments, then it + // is TypeScript syntax. + if (node.typeArguments) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeConstructor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; + } + function computeMethod(node, subtreeFlags) { + // A MethodDeclaration is ES6 syntax. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // An async method declaration is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + } + function computeAccessor(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.type + || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly + || !node.body) { + transformFlags |= 3 /* AssertTypeScript */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; + } + function computePropertyDeclaration(node, subtreeFlags) { + // A PropertyDeclaration is TypeScript syntax. + var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor + // so that it handle the transformation. + if (node.initializer || ts.isComputedPropertyName(node.name)) { + transformFlags |= 8192 /* ContainsPropertyInitializer */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeFunctionDeclaration(node, subtreeFlags) { + var transformFlags; + var modifierFlags = ts.getModifierFlags(node); + var body = node.body; + if (!body || (modifierFlags & 2 /* Ambient */)) { + // An ambient declaration is TypeScript syntax. + // A FunctionDeclaration without a body is an overload and is TypeScript syntax. + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & 2270 /* TypeScriptModifier */ + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function declaration is ES2017 syntax. + if (modifierFlags & 256 /* Async */) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function declarations with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionDeclaration's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionDeclaration is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + // Currently we do not support transforming any other generator fucntions + // down level. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003935041 /* FunctionExcludes */; + } + function computeFunctionExpression(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async function expression is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= node.asteriskToken ? 8 /* AssertESNext */ : 16 /* AssertES2017 */; + } + // function expressions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If a FunctionExpression's subtree has marked the container as needing to capture the + // lexical this, or the function contains parameters with initializers, then this node is + // ES6 syntax. + if (subtreeFlags & 163840 /* ES2015FunctionSyntaxMask */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a FunctionExpression is generator function and is the body of a + // transformed async function, then this node can be transformed to a + // down-level generator. + if (node.asteriskToken) { + transformFlags |= 768 /* AssertGenerator */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003935041 /* FunctionExcludes */; + } + function computeArrowFunction(node, subtreeFlags) { + // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. + var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) + || node.typeParameters + || node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + // An async arrow function is ES2017 syntax. + if (ts.hasModifier(node, 256 /* Async */)) { + transformFlags |= 16 /* AssertES2017 */; + } + // arrow functions with object rest destructuring are ES Next syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // If an ArrowFunction contains a lexical this, its container must capture the lexical this. + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + transformFlags |= 32768 /* ContainsCapturedLexicalThis */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; + } + function computePropertyAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If a PropertyAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeVariableDeclaration(node, subtreeFlags) { + var transformFlags = subtreeFlags; + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + // A VariableDeclaration containing ObjectRest is ESNext syntax + if (subtreeFlags & 1048576 /* ContainsObjectRest */) { + transformFlags |= 8 /* AssertESNext */; + } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeVariableStatement(node, subtreeFlags) { + var transformFlags; + var declarationListTransformFlags = node.declarationList.transformFlags; + // An ambient declaration is TypeScript syntax. + if (ts.hasModifier(node, 2 /* Ambient */)) { + transformFlags = 3 /* AssertTypeScript */; + } + else { + transformFlags = subtreeFlags; + if (declarationListTransformFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeLabeledStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */ + && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeImportEquals(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // An ImportEqualsDeclaration with a namespace reference is TypeScript. + if (!ts.isExternalModuleImportEqualsDeclaration(node)) { + transformFlags |= 3 /* AssertTypeScript */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeExpressionStatement(node, subtreeFlags) { + var transformFlags = subtreeFlags; + // If the expression of an expression statement is a destructuring assignment, + // then we treat the statement as ES6 so that we can indicate that we do not + // need to hold on to the right-hand side. + if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { + transformFlags |= 192 /* AssertES2015 */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~939525441 /* NodeExcludes */; + } + function computeModuleDeclaration(node, subtreeFlags) { + var transformFlags = 3 /* AssertTypeScript */; + var modifierFlags = ts.getModifierFlags(node); + if ((modifierFlags & 2 /* Ambient */) === 0) { + transformFlags |= subtreeFlags; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~977327425 /* ModuleExcludes */; + } + function computeVariableDeclarationList(node, subtreeFlags) { + var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 8388608 /* ContainsBindingPattern */) { + transformFlags |= 192 /* AssertES2015 */; + } + // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. + if (node.flags & 3 /* BlockScoped */) { + transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; + } + function computeOther(node, kind, subtreeFlags) { + // Mark transformations needed for each node + var transformFlags = subtreeFlags; + var excludeFlags = 939525441 /* NodeExcludes */; + switch (kind) { + case 120 /* AsyncKeyword */: + case 199 /* AwaitExpression */: + // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) + transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; + break; + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 305 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 117 /* AbstractKeyword */: + case 124 /* DeclareKeyword */: + case 76 /* ConstKeyword */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 211 /* NonNullExpression */: + case 132 /* ReadonlyKeyword */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + break; + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 10 /* JsxText */: + case 261 /* JsxClosingElement */: + case 262 /* JsxFragment */: + case 263 /* JsxOpeningFragment */: + case 264 /* JsxClosingFragment */: + case 265 /* JsxAttribute */: + case 266 /* JsxAttributes */: + case 267 /* JsxSpreadAttribute */: + case 268 /* JsxExpression */: + // These nodes are Jsx syntax. + transformFlags |= 4 /* AssertJsx */; + break; + case 13 /* NoSubstitutionTemplateLiteral */: + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 274 /* ShorthandPropertyAssignment */: + case 115 /* StaticKeyword */: + case 212 /* MetaProperty */: + // These nodes are ES6 syntax. + transformFlags |= 192 /* AssertES2015 */; + break; + case 9 /* StringLiteral */: + if (node.hasExtendedUnicodeEscape) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 8 /* NumericLiteral */: + if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 225 /* ForOfStatement */: + // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). + if (node.awaitModifier) { + transformFlags |= 8 /* AssertESNext */; + } + transformFlags |= 192 /* AssertES2015 */; + break; + case 205 /* YieldExpression */: + // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async + // generator). + transformFlags |= 8 /* AssertESNext */ | 192 /* AssertES2015 */ | 16777216 /* ContainsYield */; + break; + case 119 /* AnyKeyword */: + case 134 /* NumberKeyword */: + case 131 /* NeverKeyword */: + case 135 /* ObjectKeyword */: + case 137 /* StringKeyword */: + case 122 /* BooleanKeyword */: + case 138 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 148 /* TypeParameter */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 161 /* TypePredicate */: + case 162 /* TypeReference */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 165 /* TypeQuery */: + case 166 /* TypeLiteral */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 174 /* InferType */: + case 175 /* ParenthesizedType */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: + case 245 /* NamespaceExportDeclaration */: + // Types and signatures are TypeScript syntax, and exclude all other facts. + transformFlags = 3 /* AssertTypeScript */; + excludeFlags = -3 /* TypeExcludes */; + break; + case 147 /* ComputedPropertyName */: + // Even though computed property names are ES6, we don't treat them as such. + // This is so that they can flow through PropertyName transforms unaffected. + // Instead, we mark the container as ES6, so that it can properly handle the transform. + transformFlags |= 2097152 /* ContainsComputedPropertyName */; + if (subtreeFlags & 16384 /* ContainsLexicalThis */) { + // A computed method name like `[this.getName()](x: string) { ... }` needs to + // distinguish itself from the normal case of a method body containing `this`: + // `this` inside a method doesn't need to be rewritten (the method provides `this`), + // whereas `this` inside a computed name *might* need to be rewritten if the class/object + // is inside an arrow function: + // `_this = this; () => class K { [_this.getName()]() { ... } }` + // To make this distinction, use ContainsLexicalThisInComputedPropertyName + // instead of ContainsLexicalThis for computed property names + transformFlags |= 65536 /* ContainsLexicalThisInComputedPropertyName */; + } + break; + case 206 /* SpreadElement */: + transformFlags |= 192 /* AssertES2015 */ | 524288 /* ContainsSpread */; + break; + case 275 /* SpreadAssignment */: + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectSpread */; + break; + case 97 /* SuperKeyword */: + // This node is ES6 syntax. + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + break; + case 99 /* ThisKeyword */: + // Mark this node and its ancestors as containing a lexical `this` keyword. + transformFlags |= 16384 /* ContainsLexicalThis */; + break; + case 182 /* ObjectBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + if (subtreeFlags & 524288 /* ContainsRest */) { + transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; + } + excludeFlags = 940049729 /* BindingPatternExcludes */; + break; + case 183 /* ArrayBindingPattern */: + transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; + excludeFlags = 940049729 /* BindingPatternExcludes */; + break; + case 184 /* BindingElement */: + transformFlags |= 192 /* AssertES2015 */; + if (node.dotDotDotToken) { + transformFlags |= 524288 /* ContainsRest */; + } + break; + case 150 /* Decorator */: + // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; + break; + case 186 /* ObjectLiteralExpression */: + excludeFlags = 942740801 /* ObjectLiteralExcludes */; + if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { + // If an ObjectLiteralExpression contains a ComputedPropertyName, then it + // is an ES6 node. + transformFlags |= 192 /* AssertES2015 */; + } + if (subtreeFlags & 65536 /* ContainsLexicalThisInComputedPropertyName */) { + // A computed property name containing `this` might need to be rewritten, + // so propagate the ContainsLexicalThis flag upward. + transformFlags |= 16384 /* ContainsLexicalThis */; + } + if (subtreeFlags & 1048576 /* ContainsObjectSpread */) { + // If an ObjectLiteralExpression contains a spread element, then it + // is an ES next node. + transformFlags |= 8 /* AssertESNext */; + } + break; + case 185 /* ArrayLiteralExpression */: + case 190 /* NewExpression */: + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + if (subtreeFlags & 524288 /* ContainsSpread */) { + // If the this node contains a SpreadExpression, then it is an ES6 + // node. + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + // A loop containing a block scoped binding *may* need to be transformed from ES6. + if (subtreeFlags & 4194304 /* ContainsBlockScopedBinding */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 277 /* SourceFile */: + if (subtreeFlags & 32768 /* ContainsCapturedLexicalThis */) { + transformFlags |= 192 /* AssertES2015 */; + } + break; + case 228 /* ReturnStatement */: + // Return statements may require an `await` in ESNext. + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */ | 8 /* AssertESNext */; + break; + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: + transformFlags |= 33554432 /* ContainsHoistedDeclarationOrCompletion */; + break; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~excludeFlags; + } + /** + * Gets the transform flags to exclude when unioning the transform flags of a subtree. + * + * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`. + * For performance reasons, `computeTransformFlagsForNode` uses local constant values rather + * than calling this function. + */ + /* @internal */ + function getTransformFlagsSubtreeExclusions(kind) { + if (kind >= 161 /* FirstTypeNode */ && kind <= 181 /* LastTypeNode */) { + return -3 /* TypeExcludes */; + } + switch (kind) { + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 185 /* ArrayLiteralExpression */: + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; + case 242 /* ModuleDeclaration */: + return 977327425 /* ModuleExcludes */; + case 149 /* Parameter */: + return 939525441 /* ParameterExcludes */; + case 195 /* ArrowFunction */: + return 1003902273 /* ArrowFunctionExcludes */; + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + return 1003935041 /* FunctionExcludes */; + case 236 /* VariableDeclarationList */: + return 948962625 /* VariableDeclarationListExcludes */; + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + return 942011713 /* ClassExcludes */; + case 155 /* Constructor */: + return 1003668801 /* ConstructorExcludes */; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return 1003668801 /* MethodOrAccessorExcludes */; + case 119 /* AnyKeyword */: + case 134 /* NumberKeyword */: + case 131 /* NeverKeyword */: + case 137 /* StringKeyword */: + case 135 /* ObjectKeyword */: + case 122 /* BooleanKeyword */: + case 138 /* SymbolKeyword */: + case 105 /* VoidKeyword */: + case 148 /* TypeParameter */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return -3 /* TypeExcludes */; + case 186 /* ObjectLiteralExpression */: + return 942740801 /* ObjectLiteralExcludes */; + case 272 /* CatchClause */: + return 940574017 /* CatchClauseExcludes */; + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + return 940049729 /* BindingPatternExcludes */; + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 305 /* PartiallyEmittedExpression */: + case 193 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; + default: + return 939525441 /* NodeExcludes */; + } + } + ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; + /** + * "Binds" JSDoc nodes in TypeScript code. + * Since we will never create symbols for JSDoc, we just set parent pointers instead. + */ + function setParentPointers(parent, child) { + child.parent = parent; + ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); }); + } +})(ts || (ts = {})); +/** @internal */ +var ts; +(function (ts) { + function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier) { + return getSymbolWalker; + function getSymbolWalker(accept) { + if (accept === void 0) { accept = function () { return true; }; } + var visitedTypes = []; // Sparse array from id to type + var visitedSymbols = []; // Sparse array from id to symbol + return { + walkType: function (type) { + try { + visitType(type); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + walkSymbol: function (symbol) { + try { + visitSymbol(symbol); + return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) }; + } + finally { + ts.clear(visitedTypes); + ts.clear(visitedSymbols); + } + }, + }; + function visitType(type) { + if (!type) { + return; + } + if (visitedTypes[type.id]) { + return; + } + visitedTypes[type.id] = 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 & 131072 /* 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 & 65536 /* TypeParameter */) { + visitTypeParameter(type); + } + if (type.flags & 786432 /* UnionOrIntersection */) { + visitUnionOrIntersectionType(type); + } + if (type.flags & 1048576 /* Index */) { + visitIndexType(type); + } + if (type.flags & 2097152 /* IndexedAccess */) { + visitIndexedAccessType(type); + } + } + function visitTypeReference(type) { + visitType(type.target); + ts.forEach(type.typeArguments, visitType); + } + function visitTypeParameter(type) { + visitType(getConstraintOfTypeParameter(type)); + } + function visitUnionOrIntersectionType(type) { + ts.forEach(type.types, visitType); + } + 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) { + var typePredicate = getTypePredicateOfSignature(signature); + if (typePredicate) { + visitType(typePredicate.type); + } + ts.forEach(signature.typeParameters, visitType); + 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); + ts.forEach(interfaceT.typeParameters, visitType); + ts.forEach(getBaseTypes(interfaceT), visitType); + 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 false; + } + var symbolId = ts.getSymbolId(symbol); + if (visitedSymbols[symbolId]) { + return false; + } + visitedSymbols[symbolId] = symbol; + if (!accept(symbol)) { + return true; + } + var t = getTypeOfSymbol(symbol); + visitType(t); // Should handle members on classes and such + if (symbol.exports) { + 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 === 165 /* TypeQuery */) { + var query = d.type; + var entity = getResolvedSymbol(getFirstIdentifier(query.exprName)); + visitSymbol(entity); + } + }); + return false; + } + } + } + ts.createGetSymbolWalker = createGetSymbolWalker; +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -24864,19 +28624,21 @@ var ts; var identityMapper = ts.identity; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); - var modulekind = ts.getEmitModuleKind(compilerOptions); - var noUnusedIdentifiers = !!compilerOptions.noUnusedLocals || !!compilerOptions.noUnusedParameters; + var moduleKind = ts.getEmitModuleKind(compilerOptions); var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions); var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks"); var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis"); + var keyofStringsOnly = !!compilerOptions.keyofStringsOnly; var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); + var requireSymbol = createSymbol(4 /* Property */, "require"); + var moduleSymbol = createSymbol(4 /* Property */, "module"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; // for public members that accept a Node or one of its subtypes, we must guard against @@ -24897,25 +28659,27 @@ var ts; getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: function (symbol, location) { location = ts.getParseTreeNode(location); - return location ? getTypeOfSymbolAtLocation(symbol, location) : unknownType; + return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; }, - getSymbolsOfParameterPropertyDeclaration: function (parameter, parameterName) { - parameter = ts.getParseTreeNode(parameter, ts.isParameter); - ts.Debug.assert(parameter !== undefined, "Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { + var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); + if (parameter === undefined) + return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName)); }, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, getPropertiesOfType: getPropertiesOfType, getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, + getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); }, getIndexInfoOfType: getIndexInfoOfType, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: getIndexTypeOfType, getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, - getTypeFromTypeNode: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); - return node ? getTypeFromTypeNode(node) : unknownType; + getTypeFromTypeNode: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); + return node ? getTypeFromTypeNode(node) : errorType; }, getParameterType: getTypeAtPosition, getReturnTypeOfSignature: getReturnTypeOfSignature, @@ -24941,8 +28705,8 @@ var ts; node = ts.getParseTreeNode(node); return node ? getShorthandAssignmentValueSymbol(node) : undefined; }, - getExportSpecifierLocalTargetSymbol: function (node) { - node = ts.getParseTreeNode(node, ts.isExportSpecifier); + getExportSpecifierLocalTargetSymbol: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier); return node ? getExportSpecifierLocalTargetSymbol(node) : undefined; }, getExportSymbolOfSymbol: function (symbol) { @@ -24950,10 +28714,10 @@ var ts; }, getTypeAtLocation: function (node) { node = ts.getParseTreeNode(node); - return node ? getTypeOfNode(node) : unknownType; + return node ? getTypeOfNode(node) : errorType; }, - getPropertySymbolOfDestructuringAssignment: function (location) { - location = ts.getParseTreeNode(location, ts.isIdentifier); + getPropertySymbolOfDestructuringAssignment: function (locationIn) { + var location = ts.getParseTreeNode(locationIn, ts.isIdentifier); return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined; }, signatureToString: function (signature, enclosingDeclaration, flags, kind) { @@ -24980,44 +28744,43 @@ var ts; writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (node) { - node = ts.getParseTreeNode(node, ts.isExpression); + getContextualType: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isExpression); return node ? getContextualType(node) : undefined; }, - getContextualTypeForArgumentAtIndex: function (node, argIndex) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); return node && getContextualTypeForArgumentAtIndex(node, argIndex); }, - getContextualTypeForJsxAttribute: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxAttributeLike); + getContextualTypeForJsxAttribute: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike); return node && getContextualTypeForJsxAttribute(node); }, isContextSensitive: isContextSensitive, getFullyQualifiedName: getFullyQualifiedName, - getResolvedSignature: function (node, candidatesOutArray, theArgumentCount) { - node = ts.getParseTreeNode(node, ts.isCallLikeExpression); + getResolvedSignature: function (nodeIn, candidatesOutArray, theArgumentCount) { + var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); apparentArgumentCount = theArgumentCount; var res = node ? getResolvedSignature(node, candidatesOutArray) : undefined; apparentArgumentCount = undefined; return res; }, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, - isValidPropertyAccess: function (node, propertyName) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessOrQualifiedName); + isValidPropertyAccess: function (nodeIn, propertyName) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode); return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName)); }, - isValidPropertyAccessForCompletions: function (node, type, property) { - node = ts.getParseTreeNode(node, ts.isPropertyAccessExpression); + isValidPropertyAccessForCompletions: function (nodeIn, type, property) { + var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression); return !!node && isValidPropertyAccessForCompletions(node, type, property); }, - getSignatureFromDeclaration: function (declaration) { - declaration = ts.getParseTreeNode(declaration, ts.isFunctionLike); + getSignatureFromDeclaration: function (declarationIn) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike); return declaration ? getSignatureFromDeclaration(declaration) : undefined; }, isImplementationOfOverload: function (node) { @@ -25029,7 +28792,8 @@ var ts; var links = getSymbolLinks(symbol); if (!links.immediateTarget) { var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true); } return links.immediateTarget; @@ -25038,15 +28802,15 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintFromTypeParameter, getFirstIdentifier), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier), getAmbientModules: getAmbientModules, - getAllAttributesTypeFromJsxOpeningLikeElement: function (node) { - node = ts.getParseTreeNode(node, ts.isJsxOpeningLikeElement); + getAllAttributesTypeFromJsxOpeningLikeElement: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isJsxOpeningLikeElement); return node ? getAllAttributesTypeFromJsxOpeningLikeElement(node) : undefined; }, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, - isOptionalParameter: function (node) { - node = ts.getParseTreeNode(node, ts.isParameter); + isOptionalParameter: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isParameter); return node ? isOptionalParameter(node) : false; }, tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); }, @@ -25068,6 +28832,8 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, getBooleanType: function () { return booleanType; }, + getFalseType: function () { return falseType; }, + getTrueType: function () { return trueType; }, getVoidType: function () { return voidType; }, getUndefinedType: function () { return undefinedType; }, getNullType: function () { return nullType; }, @@ -25075,11 +28841,13 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, isArrayLikeType: isArrayLikeType, + isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, + getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, getBaseConstraintOfType: getBaseConstraintOfType, - getDefaultFromTypeParameter: function (type) { return type && type.flags & 32768 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, + getDefaultFromTypeParameter: function (type) { return type && type.flags & 65536 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals); }, @@ -25091,13 +28859,48 @@ var ts; node = ts.getParseTreeNode(node); return node && tryGetThisTypeAt(node); }, - getTypeArgumentConstraint: function (node) { - node = ts.getParseTreeNode(node, ts.isTypeNode); + getTypeArgumentConstraint: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode); return node && getTypeArgumentConstraint(node); }, - getSuggestionDiagnostics: function (file) { return suggestionDiagnostics.get(file.fileName) || ts.emptyArray; }, + getSuggestionDiagnostics: function (file, ct) { + var diagnostics; + try { + // Record the cancellation token so it can be checked later on during checkSourceElement. + // Do this in a finally block so we can ensure that it gets reset back to nothing after + // this call is done. + cancellationToken = ct; + // Ensure file is type checked + checkSourceFile(file); + ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */)); + diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.get(file.fileName)); + if (!file.isDeclarationFile && (!unusedIsError(0 /* Local */) || !unusedIsError(1 /* Parameter */))) { + addUnusedDiagnostics(); + } + return diagnostics || ts.emptyArray; + } + finally { + cancellationToken = undefined; + } + function addUnusedDiagnostics() { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && !unusedIsError(kind)) { + (diagnostics || (diagnostics = [])).push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); + } + }); + } + }, + runWithCancellationToken: function (token, callback) { + try { + cancellationToken = token; + return callback(checker); + } + finally { + cancellationToken = undefined; + } + } }; - var tupleTypes = []; + var tupleTypes = ts.createMap(); var unionTypes = ts.createMap(); var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); @@ -25109,22 +28912,25 @@ var ts; var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var wildcardType = createIntrinsicType(1 /* Any */, "any"); - var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var undefinedType = createIntrinsicType(4096 /* Undefined */, "undefined"); - var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(4096 /* Undefined */ | 16777216 /* ContainsWideningType */, "undefined"); - var nullType = createIntrinsicType(8192 /* Null */, "null"); - var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(8192 /* Null */ | 16777216 /* ContainsWideningType */, "null"); - var stringType = createIntrinsicType(2 /* String */, "string"); - var numberType = createIntrinsicType(4 /* Number */, "number"); - var trueType = createIntrinsicType(128 /* BooleanLiteral */, "true"); - var falseType = createIntrinsicType(128 /* BooleanLiteral */, "false"); - var booleanType = createBooleanType([trueType, falseType]); - var esSymbolType = createIntrinsicType(512 /* ESSymbol */, "symbol"); - var voidType = createIntrinsicType(2048 /* Void */, "void"); - var neverType = createIntrinsicType(16384 /* Never */, "never"); - var silentNeverType = createIntrinsicType(16384 /* Never */, "never"); - var implicitNeverType = createIntrinsicType(16384 /* Never */, "never"); - var nonPrimitiveType = createIntrinsicType(134217728 /* NonPrimitive */, "object"); + var errorType = createIntrinsicType(1 /* Any */, "error"); + var unknownType = createIntrinsicType(2 /* Unknown */, "unknown"); + var undefinedType = createIntrinsicType(8192 /* Undefined */, "undefined"); + var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(8192 /* Undefined */ | 134217728 /* ContainsWideningType */, "undefined"); + var nullType = createIntrinsicType(16384 /* Null */, "null"); + var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(16384 /* Null */ | 134217728 /* ContainsWideningType */, "null"); + var stringType = createIntrinsicType(4 /* String */, "string"); + var numberType = createIntrinsicType(8 /* Number */, "number"); + var falseType = createIntrinsicType(256 /* BooleanLiteral */, "false"); + var trueType = createIntrinsicType(256 /* BooleanLiteral */, "true"); + var booleanType = createBooleanType([falseType, trueType]); + var esSymbolType = createIntrinsicType(1024 /* ESSymbol */, "symbol"); + var voidType = createIntrinsicType(4096 /* Void */, "void"); + var neverType = createIntrinsicType(32768 /* Never */, "never"); + var silentNeverType = createIntrinsicType(32768 /* Never */, "never"); + var implicitNeverType = createIntrinsicType(32768 /* Never */, "never"); + var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); + var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]); + var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType; var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = ts.createSymbolTable(); @@ -25134,22 +28940,24 @@ var ts; var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= 67108864 /* ContainsAnyFunctionType */; + anyFunctionType.flags |= 536870912 /* ContainsAnyFunctionType */; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(32768 /* TypeParameter */); - var markerSubType = createType(32768 /* TypeParameter */); + var markerSuperType = createType(65536 /* TypeParameter */); + var markerSubType = createType(65536 /* TypeParameter */); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(32768 /* TypeParameter */); + var markerOtherType = createType(65536 /* TypeParameter */); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, unknownType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var resolvingSignaturesArray = [resolvingSignature]; var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var jsObjectLiteralIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false); var globals = ts.createSymbolTable(); + var amalgamatedDuplicates; var reverseMappedCache = ts.createMap(); var ambientModulesCache; /** @@ -25187,8 +28995,10 @@ var ts; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; var deferredGlobalTemplateStringsArrayType; + var deferredGlobalImportMetaType; + var deferredGlobalExtractSymbol; var deferredNodes; - var deferredUnusedIdentifierNodes; + var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name var flowLoopStart = 0; var flowLoopCount = 0; var sharedFlowCount = 0; @@ -25215,17 +29025,6 @@ var ts; var diagnostics = ts.createDiagnosticCollection(); // Suggestion diagnostics must have a file. Keyed by source file name. var suggestionDiagnostics = ts.createMultiMap(); - function addSuggestionDiagnostic(diag) { - suggestionDiagnostics.add(diag.file.fileName, __assign({}, diag, { category: ts.DiagnosticCategory.Suggestion })); - } - function addErrorOrSuggestionDiagnostic(isError, diag) { - if (isError) { - diagnostics.add(diag); - } - else { - addSuggestionDiagnostic(diag); - } - } var TypeFacts; (function (TypeFacts) { TypeFacts[TypeFacts["None"] = 0] = "None"; @@ -25328,7 +29127,7 @@ var ts; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType"; TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType"; TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType"; - TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstraint"] = 4] = "ResolvedBaseConstraint"; + TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint"; })(TypeSystemPropertyName || (TypeSystemPropertyName = {})); var CheckMode; (function (CheckMode) { @@ -25357,168 +29156,21 @@ var ts; ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target"; ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both"; })(ExpandingFlags || (ExpandingFlags = {})); - var TypeIncludes; - (function (TypeIncludes) { - TypeIncludes[TypeIncludes["Any"] = 1] = "Any"; - TypeIncludes[TypeIncludes["Undefined"] = 2] = "Undefined"; - TypeIncludes[TypeIncludes["Null"] = 4] = "Null"; - TypeIncludes[TypeIncludes["Never"] = 8] = "Never"; - TypeIncludes[TypeIncludes["NonWideningType"] = 16] = "NonWideningType"; - TypeIncludes[TypeIncludes["String"] = 32] = "String"; - TypeIncludes[TypeIncludes["Number"] = 64] = "Number"; - TypeIncludes[TypeIncludes["ESSymbol"] = 128] = "ESSymbol"; - TypeIncludes[TypeIncludes["LiteralOrUniqueESSymbol"] = 256] = "LiteralOrUniqueESSymbol"; - TypeIncludes[TypeIncludes["ObjectType"] = 512] = "ObjectType"; - TypeIncludes[TypeIncludes["EmptyObject"] = 1024] = "EmptyObject"; - TypeIncludes[TypeIncludes["Union"] = 2048] = "Union"; - TypeIncludes[TypeIncludes["Wildcard"] = 4096] = "Wildcard"; - })(TypeIncludes || (TypeIncludes = {})); var MembersOrExportsResolutionKind; (function (MembersOrExportsResolutionKind) { MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports"; MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers"; })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {})); + var UnusedKind; + (function (UnusedKind) { + UnusedKind[UnusedKind["Local"] = 0] = "Local"; + UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter"; + })(UnusedKind || (UnusedKind = {})); var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; - /** - * @deprecated - */ - function getSymbolDisplayBuilder() { - return { - buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { - typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); - }, - buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { - symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); - }, - buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { - signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); - }, - buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { - var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildParameterDisplay: function (symbol, writer, enclosing, flags) { - var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { - var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { - typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - }, - buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { - var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { - var printer = ts.createPrinter({ removeComments: true }); - var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); - var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; - var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { - var printer = ts.createPrinter({ removeComments: true }); - var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - }, - buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { - writer.writePunctuation(":"); - writer.writeSpace(" "); - var predicate = getTypePredicateOfSignature(signature); - if (predicate) { - return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); - } - var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - var printer = ts.createPrinter({ removeComments: true }); - printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); - } - }; - function emitTextWriterWrapper(underlying) { - return { - write: ts.noop, - writeTextOfNode: ts.noop, - writeLine: ts.noop, - increaseIndent: function () { - return underlying.increaseIndent(); - }, - decreaseIndent: function () { - return underlying.decreaseIndent(); - }, - getText: function () { - return ""; - }, - rawWrite: ts.noop, - writeLiteral: function (s) { - return underlying.writeStringLiteral(s); - }, - getTextPos: function () { - return 0; - }, - getLine: function () { - return 0; - }, - getColumn: function () { - return 0; - }, - getIndent: function () { - return 0; - }, - isAtStartOfLine: function () { - return false; - }, - clear: function () { - return underlying.clear(); - }, - writeKeyword: function (text) { - return underlying.writeKeyword(text); - }, - writeOperator: function (text) { - return underlying.writeOperator(text); - }, - writePunctuation: function (text) { - return underlying.writePunctuation(text); - }, - writeSpace: function (text) { - return underlying.writeSpace(text); - }, - writeStringLiteral: function (text) { - return underlying.writeStringLiteral(text); - }, - writeParameter: function (text) { - return underlying.writeParameter(text); - }, - writeProperty: function (text) { - return underlying.writeProperty(text); - }, - writeSymbol: function (text, symbol) { - return underlying.writeSymbol(text, symbol); - }, - trackSymbol: function (symbol, enclosing, meaning) { - return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); - }, - reportInaccessibleThisError: function () { - return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); - }, - reportPrivateInBaseOfClassExpression: function (name) { - return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); - }, - reportInaccessibleUniqueSymbolError: function () { - return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); - } - }; - } - } function getJsxNamespace(location) { if (location) { var file = ts.getSourceFileOfNode(location); @@ -25528,7 +29180,7 @@ var ts; } var jsxPragma = file.pragmas.get("jsx"); if (jsxPragma) { - var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; + var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; // TODO: GH#18217 file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; @@ -25556,11 +29208,48 @@ var ts; getDiagnostics(sourceFile, cancellationToken); return emitResolver; } + function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) { + var diagnostic = location + ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) + : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); + var existing = diagnostics.lookup(diagnostic); + if (existing) { + return existing; + } + else { + diagnostics.add(diagnostic); + return diagnostic; + } + } + function addRelatedInfo(diagnostic) { + var relatedInformation = []; + for (var _i = 1; _i < arguments.length; _i++) { + relatedInformation[_i - 1] = arguments[_i]; + } + var _a; + if (!diagnostic.relatedInformation) { + diagnostic.relatedInformation = []; + } + (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation); + return diagnostic; + } function error(location, message, arg0, arg1, arg2, arg3) { var diagnostic = location ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3); diagnostics.add(diagnostic); + return diagnostic; + } + function addErrorOrSuggestion(isError, diagnostic) { + if (isError) { + diagnostics.add(diagnostic); + } + else { + suggestionDiagnostics.add(diagnostic.file.fileName, __assign({}, diagnostic, { category: ts.DiagnosticCategory.Suggestion })); + } + } + function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) { + addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); } function createSymbol(flags, name, checkFlags) { symbolCount++; @@ -25629,9 +29318,17 @@ var ts; recordMergedSymbol(result, symbol); return result; } + /** + * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it. + * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it. + */ function mergeSymbol(target, source) { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | target.flags) & 67108864 /* JSContainer */) { + ts.Debug.assert(source !== target); + if (!(target.flags & 33554432 /* Transient */)) { + target = cloneSymbol(target); + } // Javascript static-property-assignment declarations always merge, even though they are also values if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { // reset flag when merging instantiated module into value module that has only const enums @@ -25640,7 +29337,7 @@ var ts; target.flags |= source.flags; if (source.valueDeclaration && (!target.valueDeclaration || - (target.valueDeclaration.kind === 237 /* ModuleDeclaration */ && source.valueDeclaration.kind !== 237 /* ModuleDeclaration */))) { + ts.isEffectiveModuleDeclaration(target.valueDeclaration) && !ts.isEffectiveModuleDeclaration(source.valueDeclaration))) { // other kinds of value declarations take precedence over modules target.valueDeclaration = source.valueDeclaration; } @@ -25655,38 +29352,67 @@ var ts; target.exports = ts.createSymbolTable(); mergeSymbolTable(target.exports, source.exports); } - if ((source.flags | target.flags) & 67108864 /* JSContainer */) { - var sourceInitializer = ts.getJSInitializerSymbol(source); - var targetInitializer = ts.getJSInitializerSymbol(target); - if (sourceInitializer !== source || targetInitializer !== target) { - mergeSymbol(targetInitializer, sourceInitializer); - } - } recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { - var message_2 = target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */ + var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); + var isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ + : isEitherBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(source.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); - ts.forEach(target.declarations, function (node) { - var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; - error(errorNode, message_2, symbolToString(source)); - }); + var sourceSymbolFile_1 = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); + var targetSymbolFile_1 = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch + if (sourceSymbolFile_1 && targetSymbolFile_1 && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile_1 !== targetSymbolFile_1) { + var firstFile_1 = ts.comparePaths(sourceSymbolFile_1.path, targetSymbolFile_1.path) === -1 /* LessThan */ ? sourceSymbolFile_1 : targetSymbolFile_1; + var secondFile = firstFile_1 === sourceSymbolFile_1 ? targetSymbolFile_1 : sourceSymbolFile_1; + var cacheKey = firstFile_1.path + "|" + secondFile.path; + var existing = amalgamatedDuplicates.get(cacheKey) || { firstFile: firstFile_1, secondFile: secondFile, firstFileInstances: ts.createMap(), secondFileInstances: ts.createMap() }; + var symbolName_1 = symbolToString(source); + var firstInstanceList_1 = existing.firstFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + var secondInstanceList_1 = existing.secondFileInstances.get(symbolName_1) || { instances: [], blockScoped: isEitherBlockScoped }; + ts.forEach(source.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = sourceSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + var targetList = targetSymbolFile_1 === firstFile_1 ? firstInstanceList_1 : secondInstanceList_1; + targetList.instances.push(errorNode); + }); + existing.firstFileInstances.set(symbolName_1, firstInstanceList_1); + existing.secondFileInstances.set(symbolName_1, secondInstanceList_1); + amalgamatedDuplicates.set(cacheKey, existing); + return target; + } + var symbolName_2 = symbolToString(source); + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_2, target); + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_2, source); + } + return target; + } + function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) { + ts.forEach(target.declarations, function (node) { + var errorNode = (ts.getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getOuterNameOfJsInitializer(node) : ts.getNameOfDeclaration(node)) || node; + addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + }); + } + function addDuplicateDeclarationError(errorNode, message, symbolName, relatedNode) { + var err = lookupOrIssueError(errorNode, message, symbolName); + if (relatedNode && ts.length(err.relatedInformation) < 5) { + addRelatedInfo(err, !ts.length(err.relatedInformation) ? ts.createDiagnosticForNode(relatedNode, ts.Diagnostics._0_was_also_declared_here, symbolName) : ts.createDiagnosticForNode(relatedNode, ts.Diagnostics.and_here)); } } function combineSymbolTables(first, second) { - if (!first || first.size === 0) + if (!ts.hasEntries(first)) return second; - if (!second || second.size === 0) + if (!ts.hasEntries(second)) return first; var combined = ts.createSymbolTable(); mergeSymbolTable(combined, first); @@ -25695,17 +29421,7 @@ var ts; } function mergeSymbolTable(target, source) { source.forEach(function (sourceSymbol, id) { - var targetSymbol = target.get(id); - if (!targetSymbol) { - target.set(id, sourceSymbol); - } - else { - if (!(targetSymbol.flags & 33554432 /* Transient */)) { - targetSymbol = cloneSymbol(targetSymbol); - target.set(id, targetSymbol); - } - mergeSymbol(targetSymbol, sourceSymbol); - } + target.set(id, target.has(id) ? mergeSymbol(target.get(id), sourceSymbol) : sourceSymbol); }); } function mergeModuleAugmentation(moduleName) { @@ -25723,7 +29439,7 @@ var ts; else { // find a module that about to be augmented // do not validate names of augmentations that are defined in ambient context - var moduleNotFoundError = !(moduleName.parent.parent.flags & 2097152 /* Ambient */) + var moduleNotFoundError = !(moduleName.parent.parent.flags & 4194304 /* Ambient */) ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found : undefined; var mainModule = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true); @@ -25733,10 +29449,7 @@ var ts; // obtain item referenced by 'export=' mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920 /* Namespace */) { - // if module symbol has already been merged - it is safe to use it. - // otherwise clone it - mainModule = mainModule.flags & 33554432 /* Transient */ ? mainModule : cloneSymbol(mainModule); - mergeSymbol(mainModule, moduleAugmentation.symbol); + mainModule = mergeSymbol(mainModule, moduleAugmentation.symbol); } else { // moduleName will be a StringLiteral since this is not `declare global`. @@ -25770,7 +29483,7 @@ var ts; return nodeLinks[nodeId] || (nodeLinks[nodeId] = { flags: 0 }); } function isGlobalSourceFile(node) { - return node.kind === 272 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); + return node.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } function getSymbol(symbols, name, meaning) { if (meaning) { @@ -25805,16 +29518,16 @@ var ts; if (parameterSymbol && propertySymbol) { return [parameterSymbol, propertySymbol]; } - ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); + return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration"); } function isBlockScopedNameDeclaredBeforeUse(declaration, usage) { var declarationFile = ts.getSourceFileOfNode(declaration); var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { - if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || + if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || (!compilerOptions.outFile && !compilerOptions.out) || isInTypeQuery(usage) || - declaration.flags & 2097152 /* Ambient */) { + declaration.flags & 4194304 /* Ambient */) { // nodes are in different files and order cannot be determined return true; } @@ -25828,20 +29541,24 @@ var ts; } if (declaration.pos <= usage.pos) { // declaration is before usage - if (declaration.kind === 180 /* BindingElement */) { + if (declaration.kind === 184 /* BindingElement */) { // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2]) - var errorBindingElement = ts.getAncestor(usage, 180 /* BindingElement */); + var errorBindingElement = ts.getAncestor(usage, 184 /* BindingElement */); if (errorBindingElement) { return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) || declaration.pos < errorBindingElement.pos; } // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a) - return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 230 /* VariableDeclaration */), usage); + return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 235 /* VariableDeclaration */), usage); } - else if (declaration.kind === 230 /* VariableDeclaration */) { + else if (declaration.kind === 235 /* VariableDeclaration */) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } + else if (ts.isClassDeclaration(declaration)) { + // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) + return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; }); + } return true; } // declaration is after usage, but it can still be legal if usage is deferred: @@ -25852,22 +29569,23 @@ var ts; // 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 === 250 /* ExportSpecifier */ || (usage.parent.kind === 247 /* ExportAssignment */ && usage.parent.isExportEquals)) { + // 2. inside a jsdoc comment + if (usage.parent.kind === 255 /* ExportSpecifier */ || (usage.parent.kind === 252 /* 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 === 247 /* ExportAssignment */ && usage.isExportEquals) { + if (usage.kind === 252 /* ExportAssignment */ && usage.isExportEquals) { return true; } var container = ts.getEnclosingBlockScopeContainer(declaration); - return isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); + return !!(usage.flags & 2097152 /* JSDoc */) || isInTypeQuery(usage) || isUsedInFunctionOrInstanceProperty(usage, declaration, container); function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) { var container = ts.getEnclosingBlockScopeContainer(declaration); switch (declaration.parent.parent.kind) { - case 212 /* VariableStatement */: - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 217 /* VariableStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: // variable statement/for/for-of statement case, // use site should not be inside variable declaration (initializer of declaration or binding element) if (isSameScopeDescendentOf(usage, declaration, container)) { @@ -25876,7 +29594,8 @@ var ts; break; } // ForIn/ForOf case - use site should not be used in expression part - return ts.isForInOrOfStatement(declaration.parent.parent) && isSameScopeDescendentOf(usage, declaration.parent.parent.expression, container); + var grandparent = declaration.parent.parent; + return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, container); } function isUsedInFunctionOrInstanceProperty(usage, declaration, container) { return !!ts.findAncestor(usage, function (current) { @@ -25887,21 +29606,22 @@ var ts; return true; } var initializerOfProperty = current.parent && - current.parent.kind === 151 /* PropertyDeclaration */ && + current.parent.kind === 152 /* PropertyDeclaration */ && current.parent.initializer === current; if (initializerOfProperty) { if (ts.hasModifier(current.parent, 32 /* Static */)) { - if (declaration.kind === 153 /* MethodDeclaration */) { + if (declaration.kind === 154 /* MethodDeclaration */) { return true; } } else { - var isDeclarationInstanceProperty = declaration.kind === 151 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); + var isDeclarationInstanceProperty = declaration.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */); if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) { return true; } } } + return false; }); } } @@ -25937,12 +29657,12 @@ var ts; // - parameters are only in the scope of function body // This restriction does not apply to JSDoc comment types because they are parented // at a higher level than type parameters would normally be - if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 282 /* JSDocComment */) { + if (meaning & result.flags & 67901928 /* Type */ && lastLocation.kind !== 289 /* JSDocComment */) { useResult = result.flags & 262144 /* TypeParameter */ // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || - lastLocation.kind === 148 /* Parameter */ || - lastLocation.kind === 147 /* TypeParameter */ + lastLocation.kind === 149 /* Parameter */ || + lastLocation.kind === 148 /* TypeParameter */ // local types not visible outside the function body : false; } @@ -25952,12 +29672,12 @@ var ts; // however it is detected separately when checking initializers of parameters // to make sure that they reference no variables declared after them. useResult = - lastLocation.kind === 148 /* Parameter */ || + lastLocation.kind === 149 /* Parameter */ || (lastLocation === location.type && - result.valueDeclaration.kind === 148 /* Parameter */); + !!ts.findAncestor(result.valueDeclaration, ts.isParameter)); } } - else if (location.kind === 170 /* ConditionalType */) { + else if (location.kind === 173 /* ConditionalType */) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. useResult = lastLocation === location.trueType; @@ -25971,14 +29691,14 @@ var ts; } } switch (location.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var moduleExports = getSymbolOfNode(location).exports; - if (location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location)) { + if (location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location)) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. if (result = moduleExports.get("default" /* Default */)) { @@ -26002,21 +29722,27 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 /* Alias */ && - ts.getDeclarationOfKind(moduleExport, 250 /* ExportSpecifier */)) { + ts.getDeclarationOfKind(moduleExport, 255 /* ExportSpecifier */)) { break; } } - if (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */)) { - break loop; + // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs) + if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) { + if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) { + result = undefined; + } + else { + break loop; + } } break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) { break loop; } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: // TypeScript 1.0 spec (April 2014): 8.4.1 // Initializer expressions for instance member variables are evaluated in the scope // of the class constructor body but are not permitted to reference parameters or @@ -26033,9 +29759,9 @@ var ts; } } break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location)), name, meaning & 67901928 /* Type */)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container @@ -26051,7 +29777,7 @@ var ts; } break loop; } - if (location.kind === 203 /* ClassExpression */ && meaning & 32 /* Class */) { + if (location.kind === 207 /* ClassExpression */ && meaning & 32 /* Class */) { var className = location.name; if (className && name === className.escapedText) { result = location.symbol; @@ -26059,7 +29785,7 @@ var ts; } } break; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* 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; @@ -26079,9 +29805,9 @@ var ts; // [foo()]() { } // <-- Reference to T from class's own computed property // } // - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: grandparent = location.parent.parent; - if (ts.isClassLike(grandparent) || grandparent.kind === 234 /* InterfaceDeclaration */) { + if (ts.isClassLike(grandparent) || grandparent.kind === 239 /* InterfaceDeclaration */) { // A reference to this grandparent's type parameters would be an error if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 67901928 /* Type */)) { error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); @@ -26089,19 +29815,19 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; } break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -26114,7 +29840,7 @@ var ts; } } break; - case 149 /* Decorator */: + case 150 /* Decorator */: // Decorators are resolved at the class declaration. Resolving at the parameter // or member would result in looking up locals in the method. // @@ -26123,7 +29849,7 @@ var ts; // method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter. // } // - if (location.parent && location.parent.kind === 148 /* Parameter */) { + if (location.parent && location.parent.kind === 149 /* Parameter */) { location = location.parent; } // @@ -26136,6 +29862,11 @@ var ts; location = location.parent; } break; + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + // js type aliases do not resolve names from their host, so skip past it + location = ts.getJSDocHost(location); + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -26146,12 +29877,12 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` 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 (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { if (lastLocation) { - ts.Debug.assert(lastLocation.kind === 272 /* SourceFile */); + ts.Debug.assert(lastLocation.kind === 277 /* SourceFile */); if (lastLocation.commonJsModuleIndicator && name === "exports") { return lastLocation.symbol; } @@ -26160,19 +29891,34 @@ var ts; result = lookup(globals, name, meaning); } } + if (!result) { + if (originalLocation && ts.isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { + return requireSymbol; + } + if (ts.isIdentifier(originalLocation) && ts.isPropertyAccessExpression(originalLocation.parent) && + originalLocation.escapedText === "module" && originalLocation.parent.name.escapedText === "exports") { + return moduleSymbol; + } + } + } if (!result) { if (nameNotFoundMessage) { if (!errorLocation || - !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && + !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { var suggestion = void 0; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { - suggestion = getSuggestionForNonexistentSymbol(originalLocation, name, meaning); + suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); if (suggestion) { - error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } } if (!suggestion) { @@ -26212,10 +29958,10 @@ var ts; } } // If we're in an external module, we can't reference value symbols created from UMD export declarations - if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */) { + if (result && isInExternalModule && (meaning & 67216319 /* Value */) === 67216319 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { var decls = result.declarations; - if (decls && decls.length === 1 && decls[0].kind === 240 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); + if (decls && decls.length === 1 && decls[0].kind === 245 /* NamespaceExportDeclaration */) { + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } } @@ -26223,12 +29969,12 @@ var ts; } function isSelfReferenceLocation(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 237 /* ModuleDeclaration */: // For `namespace N { N; }` + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: // For `namespace N { N; }` return true; default: return false; @@ -26240,8 +29986,11 @@ var ts; function isTypeParameterSymbolDeclaredInContainer(symbol, container) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (decl.kind === 147 /* TypeParameter */ && decl.parent === container) { - return true; + if (decl.kind === 148 /* TypeParameter */) { + var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent; + if (parent === container) { + return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217 + } } } return false; @@ -26250,7 +29999,7 @@ var ts; if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) { return false; } - var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ true); + var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false); var location = container; while (location) { if (ts.isClassLike(location.parent)) { @@ -26267,7 +30016,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.hasModifier(location, 32 /* Static */)) { - var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; + var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217 if (getPropertyOfType(instanceType, name)) { error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg)); return true; @@ -26280,11 +30029,11 @@ var ts; } function checkAndReportErrorForExtendingInterface(errorLocation) { var expression = getEntityNameForExtendingInterface(errorLocation); - var isError = !!(expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)); - if (isError) { + if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) { error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression)); + return true; } - return isError; + return false; } /** * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression, @@ -26293,9 +30042,9 @@ var ts; function getEntityNameForExtendingInterface(node) { switch (node.kind) { case 71 /* Identifier */: - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: if (ts.isEntityNameExpression(node.expression)) { return node.expression; } @@ -26359,17 +30108,26 @@ var ts; function checkResolvedBlockScopedVariable(result, errorLocation) { ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */)); // Block-scoped variables cannot be used before their definition - var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 236 /* EnumDeclaration */) ? d : undefined; }); - ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); - if (!(declaration.flags & 2097152 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var declaration = ts.forEach(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 241 /* EnumDeclaration */) ? d : undefined; }); + if (declaration === undefined) + return ts.Debug.fail("Declaration to checkResolvedBlockScopedVariable is undefined"); + if (!(declaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { + var diagnosticMessage = void 0; + var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration)); if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); } else if (result.flags & 256 /* RegularEnum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); + diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName); + } + else { + ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */)); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } } @@ -26378,17 +30136,17 @@ var ts; * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); } function getAnyImportSyntax(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return node; - case 243 /* ImportClause */: + case 248 /* ImportClause */: return node.parent; - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return node.parent.parent; - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return node.parent.parent.parent; default: return undefined; @@ -26398,7 +30156,7 @@ var ts; return ts.find(symbol.declarations, ts.isAliasSymbolDeclaration); } function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) { - if (node.moduleReference.kind === 252 /* ExternalModuleReference */) { + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { return resolveExternalModuleSymbol(resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node))); } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); @@ -26409,14 +30167,18 @@ var ts; ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); } + function isSyntacticDefault(node) { + return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node)); + } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { if (!allowSyntheticDefaultImports) { return false; } // Declaration files (and ambient modules) if (!file || file.isDeclarationFile) { - // Definitely cannot have a synthetic default if they have a default member specified - if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + // Definitely cannot have a synthetic default if they have a syntactic default member specified + var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration + if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) { return false; } // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member @@ -26453,7 +30215,7 @@ var ts; if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && hasSyntheticDefault) { + else if (hasSyntheticDefault) { // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } @@ -26490,7 +30252,7 @@ var ts; return valueSymbol; } var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName); - result.declarations = ts.concatenate(valueSymbol.declarations, typeSymbol.declarations); + result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues); result.parent = valueSymbol.parent || typeSymbol.parent; if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; @@ -26509,12 +30271,13 @@ var ts; if (symbol.flags & 3 /* Variable */) { var typeAnnotation = symbol.valueDeclaration.type; if (typeAnnotation) { - return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); + return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); // TODO: GH#18217 } } } function getExternalModuleMember(node, specifier, dontResolveAlias) { - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + if (dontResolveAlias === void 0) { dontResolveAlias = false; } + var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217 var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias); if (targetSymbol) { var name = specifier.propertyName || specifier.name; @@ -26524,7 +30287,7 @@ var ts; } var symbolFromVariable = void 0; // First check if module was specified with "export=". If so, get the member from the resolved type - if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=")) { + if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText); } else { @@ -26537,15 +30300,19 @@ var ts; if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } - var symbol = symbolFromModule && symbolFromVariable ? + var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { var moduleName = getFullyQualifiedName(moduleSymbol); var declarationName = ts.declarationNameToString(name); - var suggestion = getSuggestionForNonexistentModule(name, targetSymbol); + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); if (suggestion !== undefined) { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestion); + var suggestionName = symbolToString(suggestion); + var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName); + if (suggestion.valueDeclaration) { + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName)); + } } else { error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); @@ -26567,36 +30334,51 @@ var ts; resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias); } function getTargetOfExportAssignment(node, dontResolveAlias) { - return resolveEntityName(node.expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); + var expression = (ts.isExportAssignment(node) ? node.expression : node.right); + if (ts.isClassExpression(expression)) { + return checkExpression(expression).symbol; + } + var aliasLike = resolveEntityName(expression, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias); + if (aliasLike) { + return aliasLike; + } + checkExpression(expression); + return getNodeLinks(expression).resolvedSymbol; } function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) { + if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; } switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return getTargetOfImportClause(node, dontRecursivelyResolve); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return getTargetOfNamespaceImport(node, dontRecursivelyResolve); - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return getTargetOfImportSpecifier(node, dontRecursivelyResolve); - case 250 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return getTargetOfExportSpecifier(node, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: + case 202 /* BinaryExpression */: return getTargetOfExportAssignment(node, dontRecursivelyResolve); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); + default: + return ts.Debug.fail(); } } /** * Indicates that a symbol is an alias that does not merge with a local declaration. + * OR Is a JSContainer which may merge an alias with a local declaration */ function isNonLocalAlias(symbol, excludes) { if (excludes === void 0) { excludes = 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */; } - return symbol && (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */; + if (!symbol) + return false; + return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* JSContainer */); } function resolveSymbol(symbol, dontResolveAlias) { - var shouldResolve = !dontResolveAlias && isNonLocalAlias(symbol); - return shouldResolve ? resolveAlias(symbol) : symbol; + return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol; } function resolveAlias(symbol) { ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -26604,7 +30386,8 @@ var ts; if (!links.target) { links.target = resolvingSymbol; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); + if (!node) + return ts.Debug.fail(); var target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; @@ -26637,12 +30420,13 @@ var ts; if (!links.referenced) { links.referenced = true; var node = getDeclarationOfAliasSymbol(symbol); - ts.Debug.assert(!!node); - if (node.kind === 247 /* ExportAssignment */) { + if (!node) + return ts.Debug.fail(); + if (node.kind === 252 /* ExportAssignment */) { // export default checkExpressionCached(node.expression); } - else if (node.kind === 250 /* ExportSpecifier */) { + else if (node.kind === 255 /* ExportSpecifier */) { // export { } or export { as foo } checkExpressionCached(node.propertyName || node.name); } @@ -26664,13 +30448,13 @@ var ts; entityName = entityName.parent; } // Check for case 1 and 3 in the above example - if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 145 /* QualifiedName */) { + if (entityName.kind === 71 /* Identifier */ || entityName.parent.kind === 146 /* QualifiedName */) { return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } else { // Case 2 in above example // entityName.kind could be a QualifiedName or a Missing identifier - ts.Debug.assert(entityName.parent.kind === 241 /* ImportEqualsDeclaration */); + ts.Debug.assert(entityName.parent.kind === 246 /* ImportEqualsDeclaration */); return resolveEntityName(entityName, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias); } } @@ -26688,14 +30472,15 @@ var ts; var symbol; if (name.kind === 71 /* Identifier */) { var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; - symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors ? undefined : message, name, /*isUse*/ true); + var symbolFromJSPrototype = ts.isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { - return undefined; + return symbolFromJSPrototype; } } - else if (name.kind === 145 /* QualifiedName */ || name.kind === 183 /* PropertyAccessExpression */) { - var left = name.kind === 145 /* QualifiedName */ ? name.left : name.expression; - var right = name.kind === 145 /* QualifiedName */ ? name.right : name.name; + else if (name.kind === 146 /* QualifiedName */ || name.kind === 187 /* PropertyAccessExpression */) { + var left = name.kind === 146 /* QualifiedName */ ? name.left : name.expression; + var right = name.kind === 146 /* QualifiedName */ ? name.right : name.name; var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location); if (!namespace || ts.nodeIsMissing(right)) { return undefined; @@ -26704,10 +30489,6 @@ var ts; return namespace; } if (ts.isInJavaScriptFile(name)) { - var initializer = ts.getDeclaredJavascriptInitializer(namespace.valueDeclaration) || ts.getAssignedJavascriptInitializer(namespace.valueDeclaration); - if (initializer) { - namespace = getSymbolOfNode(initializer); - } if (namespace.valueDeclaration && ts.isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -26731,11 +30512,43 @@ var ts; } } else { - ts.Debug.assertNever(name, "Unknown entity name kind."); + throw ts.Debug.assertNever(name, "Unknown entity name kind."); } ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } + /** + * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too. + * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so + * name resolution won't work either. + * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. + */ + function resolveEntityNameFromJSSpecialAssignment(name, meaning) { + if (isJSDocTypeReference(name.parent)) { + var secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + if (secondaryLocation) { + return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); + } + } + } + function getJSSpecialAssignmentLocation(node) { + var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); }); + if (typeAlias) { + return; + } + var host = ts.getJSDocHost(node); + if (ts.isExpressionStatement(host) && + ts.isBinaryExpression(host.expression) && + ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) { + var symbol = getSymbolOfNode(host.expression.left); + return symbol && symbol.parent.valueDeclaration; + } + var sig = ts.getHostSignatureFromJSDocHost(host); + if (sig) { + var symbol = getSymbolOfNode(sig); + return symbol && symbol.valueDeclaration; + } + } function resolveExternalModuleName(location, moduleReferenceExpression) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -26759,13 +30572,14 @@ var ts; if (ambientModule) { return ambientModule; } - var resolvedModule = ts.getResolvedModule(ts.getSourceFileOfNode(location), moduleReference); + var currentSourceFile = ts.getSourceFileOfNode(location); + var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217 var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !ts.extensionIsTypeScript(resolvedModule.extension)) { - addSuggestionDiagnostic(createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations return getMergedSymbol(sourceFile.symbol); @@ -26783,19 +30597,34 @@ var ts; } } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !ts.extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !ts.resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { 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); } else { - addErrorOrSuggestionDiagnostic(noImplicitAny && !!moduleNotFoundError, createModuleImplicitlyAnyDiagnostic(errorNode, resolvedModule, moduleReference)); + errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference); } // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first. return undefined; } if (moduleNotFoundError) { - // report errors only if it was requested + // For relative paths, see if this was possibly a projectReference redirect + if (ts.pathIsRelative(moduleReference)) { + var sourceFile_1 = ts.getSourceFileOfNode(location); + var redirects = sourceFile_1.redirectedReferences; + if (redirects) { + var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); + for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { + var ext = _a[_i]; + var probePath = normalizedTargetPath + ext; + if (redirects.indexOf(probePath) >= 0) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); + return undefined; + } + } + } + } if (resolutionDiagnostic) { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } @@ -26812,29 +30641,52 @@ var ts; } return undefined; } - function createModuleImplicitlyAnyDiagnostic(errorNode, _a, moduleReference) { + function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) { var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName; - var errorInfo = packageId && ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)); - return ts.createDiagnosticForNodeFromMessageChain(errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + var errorInfo = packageId + ? ts.chainDiagnosticMessages( + /*details*/ undefined, typesPackageExists(packageId.name) + ? ts.Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_0 + : ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, ts.getMangledNameForScopedPackage(packageId.name)) + : undefined; + errorOrSuggestion(isError, errorNode, ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedFileName)); + } + function typesPackageExists(packageName) { + return host.getSourceFiles().some(function (sf) { return !!sf.resolvedModules && !!ts.forEachEntry(sf.resolvedModules, function (r) { + return r && r.packageId && r.packageId.name === ts.getTypesPackageName(packageName); + }); }); } - // 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=" /* ExportEquals */), dontResolveAlias)) || moduleSymbol; + return moduleSymbol && getMergedSymbol(getCommonJsExportEquals(resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias), moduleSymbol)) || moduleSymbol; + } + function getCommonJsExportEquals(exported, moduleSymbol) { + if (!exported || moduleSymbol.exports.size === 1) { + return exported; + } + var merged = cloneSymbol(exported); + if (merged.exports === undefined) { + merged.flags = merged.flags | 512 /* ValueModule */; + merged.exports = ts.createSymbolTable(); + } + moduleSymbol.exports.forEach(function (s, name) { + if (name === "export=" /* ExportEquals */) + return; + merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); + }); + return merged; } // 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 // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). - function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { + function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { - if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 277 /* SourceFile */)) { + error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); return symbol; } if (compilerOptions.esModuleInterop) { - var referenceParent = moduleReferenceExpression.parent; + var referenceParent = referencingLocation.parent; if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || ts.isImportCall(referenceParent)) { var type = getTypeOfSymbol(symbol); @@ -26897,7 +30749,7 @@ var ts; return undefined; } var type = getTypeOfSymbol(exportEquals); - return type.flags & 16382 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); + return type.flags & 32764 /* Primitive */ ? undefined : getPropertyOfType(type, memberName); } function getExportsOfSymbol(symbol) { return symbol.flags & 32 /* Class */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) : @@ -26946,7 +30798,7 @@ var ts; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. function visit(symbol) { - if (!(symbol && symbol.flags & 1952 /* HasExports */ && ts.pushIfUnique(visitedSymbols, symbol))) { + if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) { return; } var symbols = ts.cloneMap(symbol.exports); @@ -26987,6 +30839,51 @@ var ts; function getParentOfSymbol(symbol) { return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent)); } + /** + * Attempts to find the symbol corresponding to the container a symbol is in - usually this + * is just its' `.parent`, but for locals, this value is `undefined` + */ + function getContainersOfSymbol(symbol, enclosingDeclaration) { + var container = getParentOfSymbol(symbol); + if (container) { + var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer); + if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) { + return ts.concatenate([container], additionalContainers); // This order expresses a preference for the real container if it is in scope + } + return ts.append(additionalContainers, container); + } + var candidates = ts.mapDefined(symbol.declarations, function (d) { return !ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent) ? getSymbolOfNode(d.parent) : undefined; }); + if (!ts.length(candidates)) { + return undefined; + } + return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; }); + function fileSymbolIfFileSymbolExportEqualsContainer(d) { + var fileSymbol = getExternalModuleContainer(d); + var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */); + return resolveSymbol(exported) === resolveSymbol(container) ? fileSymbol : undefined; + } + } + function getAliasForSymbolInContainer(container, symbol) { + if (container === getParentOfSymbol(symbol)) { + // fast path, `symbol` is either already the alias or isn't aliased + return symbol; + } + var exports = getExportsOfSymbol(container); + var quick = exports.get(symbol.escapedName); + if (quick && symbolRefersToTarget(quick)) { + return quick; + } + return ts.forEachEntry(exports, function (exported) { + if (symbolRefersToTarget(exported)) { + return exported; + } + }); + function symbolRefersToTarget(s) { + if (s === symbol || resolveSymbol(s) === symbol || resolveSymbol(s) === resolveSymbol(symbol)) { + return s; + } + } + } function getExportSymbolOfValueSymbolIfExported(symbol) { return symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? getMergedSymbol(symbol.exportSymbol) @@ -26999,7 +30896,7 @@ var ts; var members = node.members; for (var _i = 0, members_2 = members; _i < members_2.length; _i++) { var member = members_2[_i]; - if (member.kind === 154 /* Constructor */ && ts.nodeIsPresent(member.body)) { + if (member.kind === 155 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -27017,14 +30914,20 @@ var ts; } function createBooleanType(trueFalseTypes) { var type = getUnionType(trueFalseTypes); - type.flags |= 8 /* Boolean */; + type.flags |= 16 /* Boolean */; type.intrinsicName = "boolean"; return type; } function createObjectType(objectFlags, symbol) { - var type = createType(65536 /* Object */); + var type = createType(131072 /* Object */); type.objectFlags = objectFlags; type.symbol = symbol; + type.members = undefined; + type.properties = undefined; + type.callSignatures = undefined; + type.constructSignatures = undefined; + type.stringIndexInfo = undefined; + type.numberIndexInfo = undefined; return type; } function createTypeofType() { @@ -27043,25 +30946,19 @@ var ts; function getNamedMembers(members) { var result; members.forEach(function (symbol, id) { - if (!isReservedMemberName(id)) { - if (!result) - result = []; - if (symbolIsValue(symbol)) { - result.push(symbol); - } + if (!isReservedMemberName(id) && symbolIsValue(symbol)) { + (result || (result = [])).push(symbol); } }); return result || ts.emptyArray; } function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { type.members = members; - type.properties = getNamedMembers(members); + type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members); type.callSignatures = callSignatures; type.constructSignatures = constructSignatures; - if (stringIndexInfo) - type.stringIndexInfo = stringIndexInfo; - if (numberIndexInfo) - type.numberIndexInfo = numberIndexInfo; + type.stringIndexInfo = stringIndexInfo; + type.numberIndexInfo = numberIndexInfo; return type; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) { @@ -27077,12 +30974,12 @@ var ts; } } switch (location.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (!ts.isExternalOrCommonJsModule(location)) { break; } // falls through - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (result = callback(getSymbolOfNode(location).exports)) { return result; } @@ -27101,11 +30998,8 @@ var ts; return undefined; } var id = "" + getSymbolId(symbol); - var visitedSymbolTables; - if (visitedSymbolTablesMap.has(id)) { - visitedSymbolTables = visitedSymbolTablesMap.get(id); - } - else { + var visitedSymbolTables = visitedSymbolTablesMap.get(id); + if (!visitedSymbolTables) { visitedSymbolTablesMap.set(id, visitedSymbolTables = []); } return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable); @@ -27131,7 +31025,7 @@ var ts; // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolFromSymbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - !ts.some(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && + !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) && (ignoreQualification || canQualifySymbol(symbolFromSymbolTable, meaning)); } function trySymbolTable(symbols, ignoreQualification) { @@ -27159,6 +31053,11 @@ var ts; return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } } + if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) { + if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) { + return [symbol]; + } + } }); } } @@ -27166,7 +31065,7 @@ var ts; var qualify = false; forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) { // If symbol of this name is not available in the symbol table we are ok - var symbolFromSymbolTable = symbolTable.get(symbol.escapedName); + var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName)); if (!symbolFromSymbolTable) { // Continue to the next symbol table return false; @@ -27177,7 +31076,7 @@ var ts; return true; } // Qualify if the symbol from symbol table has same meaning as expected - symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 250 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; + symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 255 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable; if (symbolFromSymbolTable.flags & meaning) { qualify = true; return true; @@ -27192,10 +31091,10 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: continue; default: return false; @@ -27213,6 +31112,54 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 67216319 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) { + if (!ts.length(symbols)) + return; + var hadAccessibleChain; + for (var _i = 0, _a = symbols; _i < _a.length; _i++) { + var symbol = _a[_i]; + // Symbol is accessible if it by itself is accessible + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + if (accessibleSymbolChain) { + hadAccessibleChain = symbol; + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); + if (hasAccessibleDeclarations) { + return hasAccessibleDeclarations; + } + } + else { + if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // Any meaning of a module symbol is always accessible via an `import` type + return { + accessibility: 0 /* Accessible */ + }; + } + } + // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. + // It could be a qualified symbol and hence verify the path + // e.g.: + // module m { + // export class c { + // } + // } + // const x: typeof m.c + // In the above example when we start with checking if typeof m.c symbol is accessible, + // we are going to see if c can be accessed in scope directly. + // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible + // It is accessible if the parent m is accessible because then m.c can be accessed through qualification + var parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + if (parentResult) { + return parentResult; + } + } + if (hadAccessibleChain) { + return { + accessibility: 1 /* NotAccessible */, + errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined, + }; + } + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -27222,48 +31169,21 @@ var ts; * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible */ function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { - if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { - var initialSymbol = symbol; - var meaningToLook = meaning; - while (symbol) { - // Symbol is accessible if it by itself is accessible - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); - if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); - if (!hasAccessibleDeclarations) { - return { - accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), - errorModuleName: symbol !== initialSymbol ? symbolToString(symbol, enclosingDeclaration, 1920 /* Namespace */) : undefined, - }; - } - return hasAccessibleDeclarations; - } - // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible. - // It could be a qualified symbol and hence verify the path - // e.g.: - // module m { - // export class c { - // } - // } - // const x: typeof m.c - // In the above example when we start with checking if typeof m.c symbol is accessible, - // we are going to see if c can be accessed in scope directly. - // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible - // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - meaningToLook = getQualifiedLeftMeaning(meaning); - symbol = getParentOfSymbol(symbol); + if (symbol && enclosingDeclaration) { + var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible); + if (result) { + return result; } // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); + var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { accessibility: 2 /* CannotBeNamed */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), errorModuleName: symbolToString(symbolExternalModule) }; } @@ -27271,21 +31191,24 @@ var ts; // Just a local name that is not accessible return { accessibility: 1 /* NotAccessible */, - errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning), + errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning), }; } return { accessibility: 0 /* Accessible */ }; - function getExternalModuleContainer(declaration) { - var node = ts.findAncestor(declaration, hasExternalModuleSymbol); - return node && getSymbolOfNode(node); - } + } + function getExternalModuleContainer(declaration) { + var node = ts.findAncestor(declaration, hasExternalModuleSymbol); + return node && getSymbolOfNode(node); } function hasExternalModuleSymbol(declaration) { - return ts.isAmbientModule(declaration) || (declaration.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + return ts.isAmbientModule(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); + } + function hasNonGlobalAugmentationExternalModuleSymbol(declaration) { + return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; - if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { + if (!ts.every(symbol.declarations, getIsDeclarationVisible)) { return undefined; } return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible }; @@ -27297,32 +31220,45 @@ var ts; if (anyImportSyntax && !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 - // since we will do the emitting later in trackSymbol. - if (shouldComputeAliasToMakeVisible) { - getNodeLinks(declaration).isVisible = true; - aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, anyImportSyntax); - } - return true; + return addVisibleAlias(declaration, anyImportSyntax); + } + else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) && + !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement + isDeclarationVisible(declaration.parent.parent.parent)) { + return addVisibleAlias(declaration, declaration.parent.parent); + } + else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement + && !ts.hasModifier(declaration, 1 /* Export */) + && isDeclarationVisible(declaration.parent)) { + return addVisibleAlias(declaration, declaration); } // Declaration is not visible return false; } return true; } + function addVisibleAlias(declaration, aliasingStatement) { + // 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 + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement); + } + return true; + } } function isEntityNameVisible(entityName, enclosingDeclaration) { // get symbol of the first identifier of the entityName var meaning; - if (entityName.parent.kind === 164 /* TypeQuery */ || + if (entityName.parent.kind === 165 /* TypeQuery */ || ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) || - entityName.parent.kind === 146 /* ComputedPropertyName */) { + entityName.parent.kind === 147 /* ComputedPropertyName */) { // Typeof value meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; } - else if (entityName.kind === 145 /* QualifiedName */ || entityName.kind === 183 /* PropertyAccessExpression */ || - entityName.parent.kind === 241 /* ImportEqualsDeclaration */) { + else if (entityName.kind === 146 /* QualifiedName */ || entityName.kind === 187 /* PropertyAccessExpression */ || + entityName.parent.kind === 246 /* ImportEqualsDeclaration */) { // Left identifier from type reference or TypeAlias // Entity name of the import declaration meaning = 1920 /* Namespace */; @@ -27355,7 +31291,7 @@ var ts; var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { - var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217 var printer = ts.createPrinter({ removeComments: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); @@ -27363,178 +31299,182 @@ var ts; } } function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + if (flags === void 0) { flags = 0 /* None */; } return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); function signatureToStringWorker(writer) { var sigOutput; if (flags & 262144 /* WriteArrowStyleSignature */) { - sigOutput = kind === 1 /* Construct */ ? 163 /* ConstructorType */ : 162 /* FunctionType */; + sigOutput = kind === 1 /* Construct */ ? 164 /* ConstructorType */ : 163 /* FunctionType */; } else { - sigOutput = kind === 1 /* Construct */ ? 158 /* ConstructSignature */ : 157 /* CallSignature */; + sigOutput = kind === 1 /* Construct */ ? 159 /* ConstructSignature */ : 158 /* CallSignature */; } var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); - printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); // TODO: GH#18217 return writer; } } function typeToString(type, enclosingDeclaration, flags, writer) { - if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */; } + if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (writer === void 0) { writer = ts.createTextWriter(""); } - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); - ts.Debug.assert(typeNode !== undefined, "should always get typenode"); + var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer); + if (typeNode === undefined) + return ts.Debug.fail("should always get typenode"); var options = { removeComments: true }; var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + var maxLength = noTruncation ? undefined : ts.defaultMaximumTruncationLength * 2; if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; } function toNodeBuilderFlags(flags) { + if (flags === void 0) { flags = 0 /* None */; } return flags & 9469291 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeToTypeNodeHelper(type, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); }); }, indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); }); }, signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); }); }, symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); }); }, symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToExpression(symbol, context, meaning); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); }); }, symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); }); }, symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = symbolToParameterDeclaration(symbol, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); }); }, typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { - ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); - var resultingNode = typeParameterToDeclaration(parameter, context); - var result = context.encounteredError ? undefined : resultingNode; - return result; + return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); }); }, }; - function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { - return { + function withContext(enclosingDeclaration, flags, tracker, cb) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = { enclosingDeclaration: enclosingDeclaration, - flags: flags, + flags: flags || 0 /* None */, tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, - symbolStack: undefined, - inferTypeParameters: undefined + visitedSymbols: undefined, + inferTypeParameters: undefined, + approximateLength: 0 }; + var resultingNode = cb(context); + return context.encounteredError ? undefined : resultingNode; + } + function checkTruncationLength(context) { + if (context.truncating) + return context.truncating; + return context.truncating = !(context.flags & 1 /* NoTruncation */) && context.approximateLength > ts.defaultMaximumTruncationLength; } function typeToTypeNodeHelper(type, context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } if (type.flags & 1 /* Any */) { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } - if (type.flags & 2 /* String */) { + if (type.flags & 2 /* Unknown */) { + return ts.createKeywordTypeNode(142 /* UnknownKeyword */); + } + if (type.flags & 4 /* String */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(137 /* StringKeyword */); } - if (type.flags & 4 /* Number */) { + if (type.flags & 8 /* Number */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(134 /* NumberKeyword */); } - if (type.flags & 8 /* Boolean */) { + if (type.flags & 16 /* Boolean */) { + context.approximateLength += 7; return ts.createKeywordTypeNode(122 /* BooleanKeyword */); } - if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { + if (type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */)) { var parentSymbol = getParentOfSymbol(type.symbol); var parentName = symbolToName(parentSymbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type ? parentName : ts.createQualifiedName(parentName, ts.symbolName(type.symbol)); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(enumLiteralName, /*typeArguments*/ undefined); } - if (type.flags & 272 /* EnumLike */) { + if (type.flags & 544 /* EnumLike */) { var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false); + context.approximateLength += ts.symbolName(type.symbol).length; return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); } - if (type.flags & (32 /* StringLiteral */)) { + if (type.flags & 64 /* StringLiteral */) { + context.approximateLength += (type.value.length + 2); return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value), 16777216 /* NoAsciiEscaping */)); } - if (type.flags & (64 /* NumberLiteral */)) { + if (type.flags & 128 /* NumberLiteral */) { + context.approximateLength += (("" + type.value).length); return ts.createLiteralTypeNode((ts.createLiteral(type.value))); } - if (type.flags & 128 /* BooleanLiteral */) { + if (type.flags & 256 /* BooleanLiteral */) { + context.approximateLength += type.intrinsicName.length; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } - if (type.flags & 1024 /* UniqueESSymbol */) { + if (type.flags & 2048 /* UniqueESSymbol */) { if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { - return ts.createTypeQueryNode(symbolToName(type.symbol, context, 67216319 /* Value */, /*expectsIdentifier*/ false)); + context.approximateLength += 6; + return symbolToTypeNode(type.symbol, context, 67216319 /* Value */); } if (context.tracker.reportInaccessibleUniqueSymbolError) { context.tracker.reportInaccessibleUniqueSymbolError(); } } + context.approximateLength += 13; return ts.createTypeOperatorNode(141 /* UniqueKeyword */, ts.createKeywordTypeNode(138 /* SymbolKeyword */)); } - if (type.flags & 2048 /* Void */) { + if (type.flags & 4096 /* Void */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(105 /* VoidKeyword */); } - if (type.flags & 4096 /* Undefined */) { + if (type.flags & 8192 /* Undefined */) { + context.approximateLength += 9; return ts.createKeywordTypeNode(140 /* UndefinedKeyword */); } - if (type.flags & 8192 /* Null */) { + if (type.flags & 16384 /* Null */) { + context.approximateLength += 4; return ts.createKeywordTypeNode(95 /* NullKeyword */); } - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { + context.approximateLength += 5; return ts.createKeywordTypeNode(131 /* NeverKeyword */); } - if (type.flags & 512 /* ESSymbol */) { + if (type.flags & 1024 /* ESSymbol */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(138 /* SymbolKeyword */); } - if (type.flags & 134217728 /* NonPrimitive */) { + if (type.flags & 16777216 /* NonPrimitive */) { + context.approximateLength += 6; return ts.createKeywordTypeNode(135 /* ObjectKeyword */); } - if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { + if (type.flags & 65536 /* TypeParameter */ && type.isThisType) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -27543,56 +31483,72 @@ var ts; context.tracker.reportInaccessibleThisError(); } } + context.approximateLength += 4; return ts.createThis(); } var objectFlags = ts.getObjectFlags(type); if (objectFlags & 4 /* Reference */) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); return typeReferenceToTypeNode(type); } - if (type.flags & 32768 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { - if (type.flags & 32768 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { - return ts.createInferTypeNode(ts.createTypeParameterDeclaration(getNameOfSymbolAsWritten(type.symbol))); + if (type.flags & 65536 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) { + if (type.flags & 65536 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) { + context.approximateLength += (ts.symbolName(type.symbol).length + 6); + return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined)); + } + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.flags & 65536 /* TypeParameter */ && + ts.length(type.symbol.declarations) && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context) && + !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) { + var name = type.symbol.declarations[0].name; + context.approximateLength += ts.idText(name).length; + return ts.createTypeReferenceNode(ts.getGeneratedNameForNode(name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */), /*typeArguments*/ undefined); } - var name = type.symbol ? symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier("?"); // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter. - return ts.createTypeReferenceNode(name, /*typeArguments*/ undefined); + return type.symbol + ? symbolToTypeNode(type.symbol, context, 67901928 /* Type */) + : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined); } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { - var name = symbolToTypeReferenceName(type.aliasSymbol); var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - return ts.createTypeReferenceNode(name, typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) + return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes); + return symbolToTypeNode(type.aliasSymbol, context, 67901928 /* Type */, typeArgumentNodes); } - if (type.flags & (131072 /* Union */ | 262144 /* Intersection */)) { - var types = type.flags & 131072 /* Union */ ? formatUnionTypes(type.types) : type.types; - var typeNodes = mapToTypeNodes(types, context); + if (type.flags & (262144 /* Union */ | 524288 /* Intersection */)) { + var types = type.flags & 262144 /* Union */ ? formatUnionTypes(type.types) : type.types; + var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true); if (typeNodes && typeNodes.length > 0) { - var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 131072 /* Union */ ? 168 /* UnionType */ : 169 /* IntersectionType */, typeNodes); + var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 262144 /* Union */ ? 171 /* UnionType */ : 172 /* IntersectionType */, typeNodes); return unionOrIntersectionTypeNode; } else { if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } - return undefined; + return undefined; // TODO: GH#18217 } } if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); // The type is an object literal type. return createAnonymousTypeNode(type); } - if (type.flags & 524288 /* Index */) { + if (type.flags & 1048576 /* Index */) { var indexedType = type.type; + context.approximateLength += 6; var indexTypeNode = typeToTypeNodeHelper(indexedType, context); return ts.createTypeOperatorNode(indexTypeNode); } - if (type.flags & 1048576 /* IndexedAccess */) { + if (type.flags & 2097152 /* IndexedAccess */) { var objectTypeNode = typeToTypeNodeHelper(type.objectType, context); var indexTypeNode = typeToTypeNodeHelper(type.indexType, context); + context.approximateLength += 2; return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode); } - if (type.flags & 2097152 /* Conditional */) { + if (type.flags & 4194304 /* Conditional */) { var checkTypeNode = typeToTypeNodeHelper(type.checkType, context); var saveInferTypeParameters = context.inferTypeParameters; context.inferTypeParameters = type.root.inferTypeParameters; @@ -27600,58 +31556,71 @@ var ts; context.inferTypeParameters = saveInferTypeParameters; var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } - if (type.flags & 4194304 /* Substitution */) { + if (type.flags & 8388608 /* Substitution */) { return typeToTypeNodeHelper(type.typeVariable, context); } - ts.Debug.fail("Should be unreachable."); + return ts.Debug.fail("Should be unreachable."); function createMappedTypeNodeFromType(type) { - ts.Debug.assert(!!(type.flags & 65536 /* Object */)); + ts.Debug.assert(!!(type.flags & 131072 /* Object */)); var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined; var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); + var appropriateConstraintTypeNode; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { + // We have a { [P in keyof T]: X } + // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType` + appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context)); + } + else { + appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context); + } + var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); + context.approximateLength += 10; return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); } function createAnonymousTypeNode(type) { var symbol = type.symbol; + var id; if (symbol) { + var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; + id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); + if (isJavaScriptConstructor(symbol.valueDeclaration)) { + // Instance and static types share the same symbol; only add 'typeof' for the static side. + var isInstanceType = type === getInferredClassType(symbol) ? 67901928 /* Type */ : 67216319 /* Value */; + return symbolToTypeNode(symbol, context, isInstanceType); + } // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 203 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || + else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 207 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { - return createTypeQueryNodeFromSymbol(symbol, 67216319 /* Value */); + return symbolToTypeNode(symbol, context, 67216319 /* Value */); } - else if (ts.contains(context.symbolStack, symbol)) { + else if (context.visitedSymbols && context.visitedSymbols.has(id)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags - var entityName = symbolToName(typeAlias, context, 67901928 /* Type */, /*expectsIdentifier*/ false); - return ts.createTypeReferenceNode(entityName, /*typeArguments*/ undefined); + return symbolToTypeNode(typeAlias, context, 67901928 /* Type */); } else { + context.approximateLength += 3; return ts.createKeywordTypeNode(119 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.symbolStack) { - context.symbolStack = []; - } - var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - return createTypeNodeFromObjectType(type); - } - else { - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + if (!context.visitedSymbols) { + context.visitedSymbols = ts.createMap(); } + context.visitedSymbols.set(id, true); + var result = createTypeNodeFromObjectType(type); + context.visitedSymbols.delete(id); + return result; } } else { @@ -27664,12 +31633,12 @@ var ts; var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || // is exported function symbol ts.forEach(symbol.declarations, function (declaration) { - return declaration.parent.kind === 272 /* SourceFile */ || declaration.parent.kind === 238 /* ModuleBlock */; + return declaration.parent.kind === 277 /* SourceFile */ || declaration.parent.kind === 243 /* ModuleBlock */; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // it is type of the symbol uses itself recursively - (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // And the build is going to succeed without visibility error or there is no structural fallback allowed + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedSymbols && context.visitedSymbols.has(id))) && // it is type of the symbol uses itself recursively + (!(context.flags & 8 /* UseStructuralFallback */) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); // TODO: GH#18217 // And the build is going to succeed without visibility error or there is no structural fallback allowed } } } @@ -27680,16 +31649,17 @@ var ts; var resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { + context.approximateLength += 2; return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */); } if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { var signature = resolved.callSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 162 /* FunctionType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* FunctionType */, context); return signatureNode; } if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { var signature = resolved.constructSignatures[0]; - var signatureNode = signatureToSignatureDeclarationHelper(signature, 163 /* ConstructorType */, context); + var signatureNode = signatureToSignatureDeclarationHelper(signature, 164 /* ConstructorType */, context); return signatureNode; } } @@ -27698,17 +31668,9 @@ var ts; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); + context.approximateLength += 2; return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } - function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { - var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); - return ts.createTypeQueryNode(entityName); - } - function symbolToTypeReferenceName(symbol) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - var entityName = symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName) ? symbolToName(symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ false) : ts.createIdentifier(""); - return entityName; - } function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { @@ -27721,8 +31683,15 @@ var ts; } else if (type.target.objectFlags & 8 /* Tuple */) { if (typeArguments.length > 0) { - var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, getTypeReferenceArity(type)), context); + var arity = getTypeReferenceArity(type); + var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context); + var hasRestElement = type.target.hasRestElement; if (tupleConstituentNodes && tupleConstituentNodes.length > 0) { + for (var i = type.target.minLength; i < arity; i++) { + tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ? + ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) : + ts.createOptionalTypeNode(tupleConstituentNodes[i]); + } return ts.createTupleTypeNode(tupleConstituentNodes); } } @@ -27730,17 +31699,18 @@ var ts; return ts.createTupleTypeNode([]); } context.encounteredError = true; - return undefined; + return undefined; // TODO: GH#18217 } else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 203 /* ClassExpression */) { + ts.isClassLike(type.symbol.valueDeclaration) && + !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) { return createAnonymousTypeNode(type); } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; - var qualifiedName = void 0; + var resultType = void 0; if (outerTypeParameters) { var length_1 = outerTypeParameters.length; while (i < length_1) { @@ -27754,65 +31724,78 @@ var ts; // the default outer type arguments), we don't show the group. 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); - (namePart.kind === 71 /* Identifier */ ? namePart : namePart.right).typeArguments = typeArgumentNodes_1; - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, namePart); - qualifiedName = ts.createQualifiedName(qualifiedName, /*right*/ undefined); - } - else { - qualifiedName = ts.createQualifiedName(namePart, /*right*/ undefined); - } + var flags_2 = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var ref = symbolToTypeNode(parent, context, 67901928 /* Type */, typeArgumentSlice); + context.flags = flags_2; + resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } - var entityName = void 0; - var nameIdentifier = symbolToTypeReferenceName(type.symbol); - if (qualifiedName) { - ts.Debug.assert(!qualifiedName.right); - qualifiedName = addToQualifiedNameMissingRightIdentifier(qualifiedName, nameIdentifier); - entityName = qualifiedName; - } - else { - entityName = nameIdentifier; - } var typeArgumentNodes = void 0; if (typeArguments.length > 0) { var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - if (typeArgumentNodes) { - var lastIdentifier = entityName.kind === 71 /* Identifier */ ? entityName : entityName.right; - lastIdentifier.typeArguments = undefined; - } - return ts.createTypeReferenceNode(entityName, typeArgumentNodes); + var flags = context.flags; + context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; + var finalRef = symbolToTypeNode(type.symbol, context, 67901928 /* Type */, typeArgumentNodes); + context.flags = flags; + return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } - function addToQualifiedNameMissingRightIdentifier(left, right) { - ts.Debug.assert(left.right === undefined); - if (right.kind === 71 /* Identifier */) { - left.right = right; - return left; + function appendReferenceToType(root, ref) { + if (ts.isImportTypeNode(root)) { + // first shift type arguments + var innerParams = root.typeArguments; + if (root.qualifier) { + (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams; + } + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) { + var id = ids_1[_i]; + root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id; + } + return root; } - var rightPart = right; - while (rightPart.left.kind !== 71 /* Identifier */) { - rightPart = rightPart.left; + else { + // first shift type arguments + var innerParams = root.typeArguments; + (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams; + root.typeArguments = ref.typeArguments; + // then move qualifiers + var ids = getAccessStack(ref); + for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) { + var id = ids_2[_a]; + root.typeName = ts.createQualifiedName(root.typeName, id); + } + return root; } - left.right = rightPart.left; - rightPart.left = left; - return right; + } + function getAccessStack(ref) { + var state = ref.typeName; + var ids = []; + while (!ts.isIdentifier(state)) { + ids.unshift(state.right); + state = state.left; + } + ids.unshift(state); + return ids; } function createTypeNodesFromResolvedType(resolvedType) { + if (checkTruncationLength(context)) { + return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)]; + } var typeElements = []; for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) { var signature = _a[_i]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 157 /* CallSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* CallSignature */, context)); } for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) { var signature = _c[_b]; - typeElements.push(signatureToSignatureDeclarationHelper(signature, 158 /* ConstructSignature */, context)); + typeElements.push(signatureToSignatureDeclarationHelper(signature, 159 /* ConstructSignature */, context)); } if (resolvedType.stringIndexInfo) { var indexInfo = resolvedType.objectFlags & 2048 /* ReverseMapped */ ? @@ -27827,8 +31810,10 @@ var ts; if (!properties) { return typeElements; } + var i = 0; for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + i++; if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { if (propertySymbol.flags & 4194304 /* Prototype */) { continue; @@ -27837,49 +31822,96 @@ var ts; context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); } } - var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? - anyType : getTypeOfSymbol(propertySymbol); - var saveEnclosingDeclaration = context.enclosingDeclaration; - context.enclosingDeclaration = undefined; - if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(propertySymbol.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 67216319 /* Value */); - if (name && context.tracker.trackSymbol) { - context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); - } - } - var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); - context.enclosingDeclaration = saveEnclosingDeclaration; - var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; - if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { - var signatures = getSignaturesOfType(propertyType, 0 /* Call */); - for (var _e = 0, signatures_1 = signatures; _e < signatures_1.length; _e++) { - var signature = signatures_1[_e]; - var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 152 /* MethodSignature */, context); - methodDeclaration.name = propertyName; - methodDeclaration.questionToken = optionalToken; - typeElements.push(methodDeclaration); - } - } - else { - var savedFlags = context.flags; - context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); - context.flags = savedFlags; - var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; - var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, - /*initializer*/ undefined); - typeElements.push(propertySignature); + if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) { + typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + addPropertyToElementList(properties[properties.length - 1], context, typeElements); + break; } + addPropertyToElementList(propertySymbol, context, typeElements); } return typeElements.length ? typeElements : undefined; } } - function mapToTypeNodes(types, context) { + function addPropertyToElementList(propertySymbol, context, typeElements) { + var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ && context.flags & 33554432 /* InReverseMappedType */ ? + anyType : getTypeOfSymbol(propertySymbol); + var saveEnclosingDeclaration = context.enclosingDeclaration; + context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.first(propertySymbol.declarations); + if (context.tracker.trackSymbol && hasLateBindableName(decl)) { + // get symbol of the first identifier of the entityName + var firstIdentifier = getFirstIdentifier(decl.name.expression); + var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); + if (name) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 67216319 /* Value */); + } + } + } + var propertyName = symbolToName(propertySymbol, context, 67216319 /* Value */, /*expectsIdentifier*/ true); + context.approximateLength += (ts.symbolName(propertySymbol).length + 1); + context.enclosingDeclaration = saveEnclosingDeclaration; + var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; + if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length) { + var signatures = getSignaturesOfType(propertyType, 0 /* Call */); + for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) { + var signature = signatures_1[_i]; + var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 153 /* MethodSignature */, context); + methodDeclaration.name = propertyName; + methodDeclaration.questionToken = optionalToken; + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(methodDeclaration, propertySymbol.valueDeclaration); + } + typeElements.push(methodDeclaration); + } + } + else { + var savedFlags = context.flags; + context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */) ? 33554432 /* InReverseMappedType */ : 0; + var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + context.flags = savedFlags; + var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined; + if (modifiers) { + context.approximateLength += 9; + } + var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, + /*initializer*/ undefined); + if (propertySymbol.valueDeclaration) { + // Copy comments to node for declaration emit + ts.setCommentRange(propertySignature, propertySymbol.valueDeclaration); + } + typeElements.push(propertySignature); + } + } + function mapToTypeNodes(types, context, isBareList) { if (ts.some(types)) { + if (checkTruncationLength(context)) { + if (!isBareList) { + return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)]; + } + else if (types.length > 2) { + return [ + typeToTypeNodeHelper(types[0], context), + ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined), + typeToTypeNodeHelper(types[types.length - 1], context) + ]; + } + } var result = []; + var i = 0; for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { var type = types_1[_i]; + i++; + if (checkTruncationLength(context) && (i + 2 < types.length - 1)) { + result.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined)); + var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context); + if (typeNode_1) { + result.push(typeNode_1); + } + break; + } + context.approximateLength += 2; // Account for whitespace + separator var typeNode = typeToTypeNodeHelper(type, context); if (typeNode) { result.push(typeNode); @@ -27897,10 +31929,11 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context); if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { context.encounteredError = true; } + context.approximateLength += (name.length + 4); return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(132 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } @@ -27913,7 +31946,7 @@ var ts; else { typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); } - var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); + var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 155 /* Constructor */); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); parameters.unshift(thisParameter); @@ -27939,60 +31972,78 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } + context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context, constraint) { - if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + function typeParameterShadowsNameInScope(type, context) { + return !!resolveName(context.enclosingDeclaration, type.symbol.escapedName, 67901928 /* Type */, /*nameNotFoundArg*/ undefined, type.symbol.escapedName, /*isUse*/ false); + } + function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic - var name = symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); - var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + var shouldUseGeneratedName = context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && + type.symbol.declarations[0] && + ts.isTypeParameterDeclaration(type.symbol.declarations[0]) && + typeParameterShadowsNameInScope(type, context); + var name = shouldUseGeneratedName + ? ts.getGeneratedNameForNode(type.symbol.declarations[0].name, 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */) + : symbolToName(type.symbol, context, 67901928 /* Type */, /*expectsIdentifier*/ true); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } - function symbolToParameterDeclaration(parameterSymbol, context) { - var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 148 /* Parameter */); - ts.Debug.assert(!!parameterDeclaration || isTransientSymbol(parameterSymbol) && !!parameterSymbol.isRestParameter); + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); } + var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + return typeParameterToDeclarationWithConstraint(type, context, constraintNode); + } + function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags) { + var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 149 /* Parameter */); + if (!parameterDeclaration && !isTransientSymbol(parameterSymbol)) { + parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 296 /* JSDocParameterTag */); + } var parameterType = getTypeOfSymbol(parameterSymbol); if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) { parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); - var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var dotDotDotToken = isRest ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? - parameterDeclaration.name.kind === 71 /* Identifier */ ? - ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : - cloneBindingName(parameterDeclaration.name) : + parameterDeclaration.name.kind === 71 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : + parameterDeclaration.name.kind === 146 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : + cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var questionToken = parameterDeclaration && isOptionalParameter(parameterDeclaration) ? ts.createToken(55 /* QuestionToken */) : undefined; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var questionToken = isOptional ? ts.createToken(55 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, /*initializer*/ undefined); + context.approximateLength += ts.symbolName(parameterSymbol).length + 3; return parameterNode; function cloneBindingName(node) { return elideInitializerAndSetEmitFlags(node); function elideInitializerAndSetEmitFlags(node) { var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags); var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited); - if (clone.kind === 180 /* BindingElement */) { + if (clone.kind === 184 /* BindingElement */) { clone.initializer = undefined; } return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } - function lookupSymbolChain(symbol, context, meaning) { - context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); + function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration. var chain; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { - chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); + chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } else { @@ -28002,16 +32053,18 @@ var ts; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); - var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - if (parentChain) { - parentSymbol = parent; - accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [symbol]); + var parents = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration); + if (ts.length(parents)) { + for (var _i = 0, _a = parents; _i < _a.length; _i++) { + var parent = _a[_i]; + var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + if (parentChain) { + accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]); + break; + } } } } @@ -28021,10 +32074,12 @@ var ts; if ( // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || + // If a parent symbol is an anonymous type, don't write it. + !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { + if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + return; + } return [symbol]; } } @@ -28054,6 +32109,120 @@ var ts; } return typeParameterNodes; } + /** + * Given A[B][C][D], finds A[B] + */ + function getTopmostIndexedAccessType(top) { + if (ts.isIndexedAccessTypeNode(top.objectType)) { + return getTopmostIndexedAccessType(top.objectType); + } + return top; + } + function getSpecifierForModuleSymbol(symbol, context) { + var file = ts.getDeclarationOfKind(symbol, 277 /* SourceFile */); + if (file && file.moduleName !== undefined) { + // Use the amd name if it is available + return file.moduleName; + } + if (!file) { + if (context.tracker.trackReferencedAmbientModule) { + var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule); + if (ts.length(ambientDecls)) { + for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) { + var decl = ambientDecls_1[_i]; + context.tracker.trackReferencedAmbientModule(decl, symbol); + } + } + } + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + else { + if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) { + // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name + return symbol.escapedName.substring(1, symbol.escapedName.length - 1); + } + var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration)); + var links = getSymbolLinks(symbol); + var specifier = links.specifierCache && links.specifierCache.get(contextFile.path); + if (!specifier) { + specifier = ts.flatten(ts.moduleSpecifiers.getModuleSpecifiers(symbol, compilerOptions, contextFile, context.tracker.moduleResolverHost, context.tracker.moduleResolverHost.getSourceFiles(), // TODO: GH#18217 + { importModuleSpecifierPreference: "non-relative" }))[0]; + links.specifierCache = links.specifierCache || ts.createMap(); + links.specifierCache.set(contextFile.path, specifier); + } + return specifier; + } + } + function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) { + var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module + var isTypeOf = meaning === 67216319 /* Value */; + if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) { + // module is root, must use `ImportTypeNode` + var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined; + var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context); + var specifier = getSpecifierForModuleSymbol(chain[0], context); + var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier)); + context.approximateLength += specifier.length + 10; // specifier + import("") + if (!nonRootParts || ts.isEntityName(nonRootParts)) { + if (nonRootParts) { + var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right; + lastId.typeArguments = undefined; + } + return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf); + } + else { + var splitNode = getTopmostIndexedAccessType(nonRootParts); + var qualifier = splitNode.objectType.typeName; + return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType); + } + } + var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0); + if (ts.isIndexedAccessTypeNode(entityName)) { + return entityName; // Indexed accesses can never be `typeof` + } + if (isTypeOf) { + return ts.createTypeQueryNode(entityName); + } + else { + var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right; + var lastTypeArgs = lastId.typeArguments; + lastId.typeArguments = undefined; + return ts.createTypeReferenceNode(entityName, lastTypeArgs); + } + function createAccessFromSymbolChain(chain, index, stopper) { + var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + if (index === 0) { + context.flags |= 16777216 /* InInitialEntityName */; + } + var symbolName = getNameOfSymbolAsWritten(symbol, context); + context.approximateLength += symbolName.length + 1; + if (index === 0) { + context.flags ^= 16777216 /* InInitialEntityName */; + } + var parent = chain[index - 1]; + if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent && getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) === symbol) { + // Should use an indexed access + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (ts.isIndexedAccessTypeNode(LHS)) { + return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + else { + return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName))); + } + } + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + if (index > stopper) { + var LHS = createAccessFromSymbolChain(chain, index - 1, stopper); + if (!ts.isEntityName(LHS)) { + return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable"); + } + return ts.createQualifiedName(LHS, identifier); + } + return identifier; + } + } function symbolToName(symbol, context, meaning, expectsIdentifier) { var chain = lookupSymbolChain(symbol, context, meaning); if (expectsIdentifier && chain.length !== 1 @@ -28120,6 +32289,7 @@ var ts; } } function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; } return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); function typePredicateToStringWorker(writer) { var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); @@ -28135,10 +32305,10 @@ var ts; for (var i = 0; i < types.length; i++) { var t = types[i]; flags |= t.flags; - if (!(t.flags & 12288 /* Nullable */)) { - if (t.flags & (128 /* BooleanLiteral */ | 256 /* EnumLiteral */)) { - var baseType = t.flags & 128 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); - if (baseType.flags & 131072 /* Union */) { + if (!(t.flags & 24576 /* Nullable */)) { + if (t.flags & (256 /* BooleanLiteral */ | 512 /* EnumLiteral */)) { + var baseType = t.flags & 256 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t); + if (baseType.flags & 262144 /* Union */) { var count = baseType.types.length; if (i + count <= types.length && types[i + count - 1] === baseType.types[count - 1]) { result.push(baseType); @@ -28150,9 +32320,9 @@ var ts; result.push(t); } } - if (flags & 8192 /* Null */) + if (flags & 16384 /* Null */) result.push(nullType); - if (flags & 4096 /* Undefined */) + if (flags & 8192 /* Undefined */) result.push(undefinedType); return result || types; } @@ -28167,8 +32337,8 @@ var ts; } function getTypeAliasForTypeLiteral(type) { if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) { - var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 172 /* ParenthesizedType */; }); - if (node.kind === 235 /* TypeAliasDeclaration */) { + var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 175 /* ParenthesizedType */; }); + if (node.kind === 240 /* TypeAliasDeclaration */) { return getSymbolOfNode(node); } } @@ -28176,14 +32346,11 @@ var ts; } function isTopLevelInExternalModuleAugmentation(node) { return node && node.parent && - node.parent.kind === 238 /* ModuleBlock */ && + node.parent.kind === 243 /* ModuleBlock */ && ts.isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type) { - return type.flags & 32 /* StringLiteral */ ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; - } function isDefaultBindingContext(location) { - return location.kind === 272 /* SourceFile */ || ts.isAmbientModule(location); + return location.kind === 277 /* SourceFile */ || ts.isAmbientModule(location); } /** * Gets a human-readable name for a symbol. @@ -28208,24 +32375,26 @@ var ts; if (name) { return ts.declarationNameToString(name); } - if (declaration.parent && declaration.parent.kind === 230 /* VariableDeclaration */) { + if (declaration.parent && declaration.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { - context.encounteredError = true; - } switch (declaration.kind) { - case 203 /* ClassExpression */: - return "(Anonymous class)"; - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - return "(Anonymous function)"; + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { + context.encounteredError = true; + } + return declaration.kind === 207 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - if (symbol.nameType && symbol.nameType.flags & 32 /* StringLiteral */) { - var stringValue = symbol.nameType.value; - if (!ts.isIdentifierText(stringValue, compilerOptions.target)) { - return "\"" + ts.escapeString(stringValue, 34 /* doubleQuote */) + "\""; + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 64 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { + return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; + } + if (nameType && nameType.flags & 2048 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; } } return ts.symbolName(symbol); @@ -28241,22 +32410,27 @@ var ts; return false; function determineIfDeclarationIsVisible() { switch (node.kind) { - case 180 /* BindingElement */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + // Top-level jsdoc type aliases are considered exported + // First parent is comment node, second is hosting declaration or token; we only care about those tokens or declarations whose parent is a source file + return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent)); + case 184 /* BindingElement */: return isDeclarationVisible(node.parent.parent); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: if (ts.isBindingPattern(node.name) && !node.name.elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } // falls through - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 232 /* FunctionDeclaration */: - case 236 /* EnumDeclaration */: - case 241 /* ImportEqualsDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 237 /* FunctionDeclaration */: + case 241 /* EnumDeclaration */: + case 246 /* ImportEqualsDeclaration */: // external module augmentation is always visible if (ts.isExternalModuleAugmentation(node)) { return true; @@ -28264,53 +32438,53 @@ var ts; var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 241 /* ImportEqualsDeclaration */ && parent.kind !== 272 /* SourceFile */ && parent.flags & 2097152 /* Ambient */)) { + !(node.kind !== 246 /* ImportEqualsDeclaration */ && parent.kind !== 277 /* SourceFile */ && parent.flags & 4194304 /* Ambient */)) { return isGlobalSourceFile(parent); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible return isDeclarationVisible(parent); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) { // Private/protected properties/methods are not visible return false; } // Public properties/methods are visible if its parents are visible, so: // falls through - case 154 /* Constructor */: - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - case 148 /* Parameter */: - case 238 /* ModuleBlock */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 165 /* TypeLiteral */: - case 161 /* TypeReference */: - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 172 /* ParenthesizedType */: + case 155 /* Constructor */: + case 159 /* ConstructSignature */: + case 158 /* CallSignature */: + case 160 /* IndexSignature */: + case 149 /* Parameter */: + case 243 /* ModuleBlock */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 166 /* TypeLiteral */: + case 162 /* TypeReference */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 175 /* ParenthesizedType */: return isDeclarationVisible(node.parent); // Default binding, import specifier and namespace import is visible // only on demand so by default it is not visible - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: return false; // Type parameters are always visible - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: // Source file and namespace export are always visible - case 272 /* SourceFile */: - case 240 /* NamespaceExportDeclaration */: + case 277 /* SourceFile */: + case 245 /* NamespaceExportDeclaration */: return true; // Export assignments do not create name bindings outside the module - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return false; default: return false; @@ -28319,10 +32493,10 @@ var ts; } function collectLinkedAliases(node, setVisibility) { var exportSymbol; - if (node.parent && node.parent.kind === 247 /* ExportAssignment */) { + if (node.parent && node.parent.kind === 252 /* ExportAssignment */) { exportSymbol = resolveName(node, node.escapedText, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } - else if (node.parent.kind === 250 /* ExportSpecifier */) { + else if (node.parent.kind === 255 /* ExportSpecifier */) { exportSymbol = getTargetOfExportSpecifier(node.parent, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } var result; @@ -28390,23 +32564,19 @@ var ts; return -1; } function hasType(target, propertyName) { - if (propertyName === 0 /* Type */) { - return getSymbolLinks(target).type; + switch (propertyName) { + case 0 /* Type */: + return !!getSymbolLinks(target).type; + case 2 /* DeclaredType */: + return !!getSymbolLinks(target).declaredType; + case 1 /* ResolvedBaseConstructorType */: + return !!target.resolvedBaseConstructorType; + case 3 /* ResolvedReturnType */: + return !!target.resolvedReturnType; + case 4 /* ImmediateBaseConstraint */: + return !!target.immediateBaseConstraint; } - if (propertyName === 2 /* DeclaredType */) { - return getSymbolLinks(target).declaredType; - } - if (propertyName === 1 /* ResolvedBaseConstructorType */) { - return target.resolvedBaseConstructorType; - } - if (propertyName === 3 /* ResolvedReturnType */) { - return target.resolvedReturnType; - } - if (propertyName === 4 /* ResolvedBaseConstraint */) { - var bc = target.resolvedBaseConstraint; - return bc && bc !== circularConstraintType; - } - ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + return ts.Debug.assertNever(propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. @@ -28416,20 +32586,19 @@ var ts; return resolutionResults.pop(); } function getDeclarationContainer(node) { - node = ts.findAncestor(ts.getRootDeclaration(node), function (node) { + return ts.findAncestor(ts.getRootDeclaration(node), function (node) { switch (node.kind) { - case 230 /* VariableDeclaration */: - case 231 /* VariableDeclarationList */: - case 246 /* ImportSpecifier */: - case 245 /* NamedImports */: - case 244 /* NamespaceImport */: - case 243 /* ImportClause */: + case 235 /* VariableDeclaration */: + case 236 /* VariableDeclarationList */: + case 251 /* ImportSpecifier */: + case 250 /* NamedImports */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: return false; default: return true; } - }); - return node && node.parent; + }).parent; } function getTypeOfPrototypeProperty(prototype) { // TypeScript 1.0 spec (April 2014): 8.4 @@ -28454,14 +32623,14 @@ var ts; return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); } function isComputedNonLiteralName(name) { - return name.kind === 146 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); + return name.kind === 147 /* ComputedPropertyName */ && !ts.isStringOrNumericLiteral(name.expression); } function getRestType(source, properties, symbol) { - source = filterType(source, function (t) { return !(t.flags & 12288 /* Nullable */); }); - if (source.flags & 16384 /* Never */) { + source = filterType(source, function (t) { return !(t.flags & 24576 /* Nullable */); }); + if (source.flags & 32768 /* Never */) { return emptyObjectType; } - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var members = ts.createSymbolTable(); @@ -28476,7 +32645,7 @@ var ts; var isPrivate = ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */); var isSetOnlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); if (!inNamesToRemove && !isPrivate && !isClassMethod(prop) && !isSetOnlyAccessor) { - members.set(prop.escapedName, prop); + members.set(prop.escapedName, getNonReadonlySymbol(prop)); } } var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */); @@ -28488,8 +32657,8 @@ var ts; var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); // If parent has the unknown (error) type, then so does this binding element - if (parentType === unknownType) { - return unknownType; + if (parentType === errorType) { + return errorType; } // If no type was specified or inferred for parent, // infer from the initializer of the binding element if one is present. @@ -28501,11 +32670,11 @@ var ts; return parentType; } var type; - if (pattern.kind === 178 /* ObjectBindingPattern */) { + if (pattern.kind === 182 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { - if (!isValidSpreadType(parentType)) { + if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) { error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types); - return unknownType; + return errorType; } var literalMembers = []; for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { @@ -28519,25 +32688,50 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name)) { - // computed properties with non-literal names are treated as 'any' - return anyType; + var isLate = isLateBindableName(name); + var isWellKnown = ts.isComputedPropertyName(name) && ts.isWellKnownSymbolSyntactically(name.expression); + if (!isLate && !isWellKnown && isComputedNonLiteralName(name)) { + var exprType = checkExpression(name.expression); + if (isTypeAssignableToKind(exprType, 3072 /* ESSymbolLike */)) { + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(exprType), typeToString(parentType)); + } + return anyType; + } + var indexerType = isTypeAssignableToKind(exprType, 168 /* NumberLike */) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); + if (!indexerType && noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (getIndexTypeOfType(parentType, 1 /* Number */)) { + error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); + } + else { + error(declaration, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(parentType)); + } + } + return indexerType || anyType; } // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - var text = ts.getTextOfPropertyName(name); + var nameType = isLate ? checkComputedPropertyName(name) : undefined; + var text = isLate ? getLateBoundNameFromType(nameType) : + isWellKnown ? ts.getPropertyNameForKnownSymbolName(ts.idText(name.expression.name)) : + ts.getTextOfPropertyName(name); // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation - if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { + if (strictNullChecks && declaration.flags & 4194304 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var propType = getTypeOfPropertyOfType(parentType, text); - var declaredType = propType && getConstraintForLocation(propType, declaration.name); + if (isLate && nameType && !getPropertyOfType(parentType, text) && isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { + if (noImplicitAny) { + error(declaration, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(nameType), typeToString(parentType)); + } + return anyType; + } + var declaredType = getConstraintForLocation(getTypeOfPropertyOfType(parentType, text), declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); - return unknownType; + return errorType; } } } @@ -28546,33 +32740,38 @@ var ts; // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). var elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); + var index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - // Rest element has an array type with the same element type as the parent type - type = createArrayType(elementType); + // If the parent is a tuple type, the rest element has an array type with a union of the + // remaining tuple element types. Otherwise, the rest element has an array type with same + // element type as the parent type. + type = isTupleType(parentType) ? + getArrayLiteralType((parentType.typeArguments || ts.emptyArray).slice(index, getTypeReferenceArity(parentType))) : + createArrayType(elementType); } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + pattern.elements.indexOf(declaration); - type = isTupleLikeType(parentType) - ? getTypeOfPropertyOfType(parentType, propName) - : elementType; + var index_1 = pattern.elements.indexOf(declaration); + type = isTupleLikeType(parentType) ? + getTupleElementType(parentType, index_1) || declaration.initializer && checkDeclarationInitializer(declaration) : + elementType; if (!type) { if (isTupleType(parentType)) { error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); } else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_1); } - return unknownType; + return errorType; } } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 4096 /* Undefined */)) { + if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkExpressionCached(declaration.initializer)) & 8192 /* Undefined */)) { type = getTypeWithFacts(type, 131072 /* NEUndefined */); } - return declaration.initializer ? + return declaration.initializer && !ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration)) ? getUnionType([type, checkExpressionCached(declaration.initializer)], 2 /* Subtype */) : type; } @@ -28589,7 +32788,7 @@ var ts; } function isEmptyArrayLiteral(node) { var expr = ts.skipParentheses(node); - return expr.kind === 181 /* ArrayLiteralExpression */ && expr.elements.length === 0; + return expr.kind === 185 /* ArrayLiteralExpression */ && expr.elements.length === 0; } function addOptionality(type, optional) { if (optional === void 0) { optional = true; } @@ -28599,11 +32798,11 @@ var ts; function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 219 /* ForInStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 224 /* ForInStatement */) { var indexType = getIndexType(checkNonNullExpression(declaration.parent.parent.expression)); - return indexType.flags & (32768 /* TypeParameter */ | 524288 /* Index */) ? indexType : stringType; + return indexType.flags & (65536 /* TypeParameter */ | 1048576 /* Index */) ? getExtractStringType(indexType) : stringType; } - if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 220 /* ForOfStatement */) { + if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 225 /* ForOfStatement */) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like // [Symbol.iterator] or next). This may be because we accessed properties from anyType, @@ -28614,24 +32813,16 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } - var isOptional = false; - if (includeOptionality) { - if (ts.isInJavaScriptFile(declaration) && ts.isParameter(declaration)) { - var parameterTags = ts.getJSDocParameterTags(declaration); - isOptional = !!(parameterTags && parameterTags.length > 0 && ts.find(parameterTags, function (tag) { return tag.isBracketed; })); - } - if (!ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken) { - isOptional = true; - } - } + var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration) + || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken); // Use type from type annotation if one is present var declaredType = tryGetTypeFromEffectiveTypeNode(declaration); if (declaredType) { return addOptionality(declaredType, isOptional); } if ((noImplicitAny || ts.isInJavaScriptFile(declaration)) && - declaration.kind === 230 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && - !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 2097152 /* Ambient */)) { + declaration.kind === 235 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 4194304 /* Ambient */)) { // If --noImplicitAny is on or the declaration is in a Javascript file, // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no // initializer or a 'null' or 'undefined' initializer. @@ -28644,11 +32835,11 @@ var ts; return autoArrayType; } } - if (declaration.kind === 148 /* Parameter */) { + if (declaration.kind === 149 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present - if (func.kind === 156 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { - var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 155 /* GetAccessor */); + if (func.kind === 157 /* SetAccessor */ && !hasNonBindableDynamicName(func)) { + var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 156 /* GetAccessor */); if (getter) { var getterSignature = getSignatureFromDeclaration(getter); var thisParameter = getAccessorThisParameter(func); @@ -28661,13 +32852,7 @@ var ts; } } // Use contextual parameter type if one is available - var type = void 0; - if (declaration.symbol.escapedName === "this") { - type = getContextualThisParameterType(func); - } - else { - type = getContextuallyTypedParameterType(declaration); - } + var type = declaration.symbol.escapedName === "this" ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality(type, isOptional); } @@ -28696,19 +32881,27 @@ var ts; return getWidenedLiteralType(checkExpressionCached(specialDeclaration)); } var types = []; + var constructorTypes; var definedInConstructor = false; var definedInMethod = false; var jsDocType; - for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var expression = declaration.kind === 198 /* BinaryExpression */ ? declaration : - declaration.kind === 183 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 198 /* BinaryExpression */) : + var _loop_4 = function (declaration) { + var declarationInConstructor = false; + var expression = ts.isBinaryExpression(declaration) ? declaration : + ts.isPropertyAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration : undefined; if (!expression) { - return unknownType; + return { value: errorType }; } - if (ts.isPropertyAccessExpression(expression.left) && expression.left.expression.kind === 99 /* ThisKeyword */) { - if (ts.getThisContainer(expression, /*includeArrowFunctions*/ false).kind === 154 /* Constructor */) { + var special = ts.isPropertyAccessExpression(expression) ? ts.getSpecialPropertyAccessKind(expression) : ts.getSpecialPropertyAssignmentKind(expression); + if (special === 4 /* ThisProperty */) { + var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false); + // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added. + // Function expressions that are assigned to the prototype count as methods. + declarationInConstructor = thisContainer.kind === 155 /* Constructor */ || + thisContainer.kind === 237 /* FunctionDeclaration */ || + (thisContainer.kind === 194 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent)); + if (declarationInConstructor) { definedInConstructor = true; } else { @@ -28722,26 +32915,95 @@ var ts; if (!jsDocType) { jsDocType = declarationType; } - else if (jsDocType !== unknownType && declarationType !== unknownType && + else if (jsDocType !== errorType && declarationType !== errorType && !isTypeIdenticalTo(jsDocType, declarationType) && !(symbol.flags & 67108864 /* JSContainer */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(jsDocType, declaration, declarationType); } } - else if (!jsDocType) { + else if (!jsDocType && ts.isBinaryExpression(expression)) { // If we don't have an explicit JSDoc type, get the type from the expression. - types.push(getWidenedLiteralType(checkExpressionCached(expression.right))); + var type_2 = getWidenedLiteralType(checkExpressionCached(expression.right)); + if (ts.getObjectFlags(type_2) & 16 /* Anonymous */ && + special === 2 /* ModuleExports */ && + symbol.escapedName === "export=" /* ExportEquals */) { + var exportedType_1 = resolveStructuredTypeMembers(type_2); + var members_3 = ts.createSymbolTable(); + ts.copyEntries(exportedType_1.members, members_3); + symbol.exports.forEach(function (s, name) { + if (members_3.has(name)) { + var exportedMember = exportedType_1.members.get(name); + var union = createSymbol(s.flags | exportedMember.flags, name); + union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]); + members_3.set(name, union); + } + else { + members_3.set(name, s); + } + }); + type_2 = createAnonymousType(exportedType_1.symbol, members_3, exportedType_1.callSignatures, exportedType_1.constructSignatures, exportedType_1.stringIndexInfo, exportedType_1.numberIndexInfo); + } + var anyedType = type_2; + if (isEmptyArrayLiteralType(type_2)) { + anyedType = anyArrayType; + if (noImplicitAny) { + reportImplicitAnyError(expression, anyArrayType); + } + } + types.push(anyedType); + if (declarationInConstructor) { + (constructorTypes || (constructorTypes = [])).push(anyedType); + } + } + }; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + var state_2 = _loop_4(declaration); + if (typeof state_2 === "object") + return state_2.value; + } + var type = jsDocType; + if (!type) { + // use only the constructor types unless they were only assigned null | undefined (including widening variants) + if (definedInMethod) { + var propType = getTypeOfSpecialPropertyOfBaseType(symbol); + if (propType) { + (constructorTypes || (constructorTypes = [])).push(propType); + definedInConstructor = true; + } + } + var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~(24576 /* Nullable */ | 134217728 /* ContainsWideningType */)); }) ? constructorTypes : types; // TODO: GH#18217 + type = getUnionType(sourceTypes, 2 /* Subtype */); + } + var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); + if (filterType(widened, function (t) { return !!(t.flags & ~24576 /* Nullable */); }) === neverType) { + if (noImplicitAny) { + reportImplicitAnyError(symbol.valueDeclaration, anyType); + } + return anyType; + } + return widened; + } + /** check for definition in base class if any declaration is in a class */ + function getTypeOfSpecialPropertyOfBaseType(specialProperty) { + var parentDeclaration = ts.forEach(specialProperty.declarations, function (d) { + var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent; + return ts.isClassLike(parent) && parent; + }); + if (parentDeclaration) { + var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)); + var baseClassType = classType && getBaseTypes(classType)[0]; + if (baseClassType) { + return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); } } - var type = jsDocType || getUnionType(types, 2 /* Subtype */); - return getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { - return checkDeclarationInitializer(element); + return addOptionality(checkDeclarationInitializer(element)); } if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -28755,12 +33017,12 @@ var ts; function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) { var members = ts.createSymbolTable(); var stringIndexInfo; - var hasComputedProperties = false; + var objectFlags = 128 /* ObjectLiteral */; ts.forEach(pattern.elements, function (e) { var name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { // do not include computed properties in the implied type - hasComputedProperties = true; + objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; return; } if (e.dotDotDotToken) { @@ -28775,24 +33037,24 @@ var ts; members.set(symbol.escapedName, symbol); }); var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); + result.flags |= 268435456 /* ContainsObjectLiteral */; + result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; } - if (hasComputedProperties) { - result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; - } return result; } // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) { var elements = pattern.elements; var lastElement = ts.lastOrUndefined(elements); - if (elements.length === 0 || (!ts.isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { + var hasRestElement = !!(lastElement && lastElement.kind === 184 /* BindingElement */ && lastElement.dotDotDotToken); + if (elements.length === 0 || elements.length === 1 && hasRestElement) { return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType; } - // If the pattern has at least one element, and no rest element, then it should imply a tuple type. var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); }); - var result = createTupleType(elementTypes); + var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1; + var result = createTupleType(elementTypes, minLength, hasRestElement); if (includePatternInType) { result = cloneTypeReference(result); result.pattern = pattern; @@ -28807,7 +33069,9 @@ var ts; // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of // the parameter. function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) { - return pattern.kind === 178 /* ObjectBindingPattern */ + if (includePatternInType === void 0) { includePatternInType = false; } + if (reportErrors === void 0) { reportErrors = false; } + return pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors); } @@ -28821,13 +33085,15 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + } + function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) { if (type) { if (reportErrors) { reportErrorsFromWidening(declaration, type); } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & 1024 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { + if (type.flags & 2048 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) { type = esSymbolType; } return getWidenedType(type); @@ -28844,7 +33110,7 @@ var ts; } function declarationBelongsToPrivateAmbientMember(declaration) { var root = ts.getRootDeclaration(declaration); - var memberDeclaration = root.kind === 148 /* Parameter */ ? root.parent : root; + var memberDeclaration = root.kind === 149 /* Parameter */ ? root.parent : root; return isPrivateWithinAmbient(memberDeclaration); } function tryGetTypeFromEffectiveTypeNode(declaration) { @@ -28860,64 +33126,64 @@ var ts; if (symbol.flags & 4194304 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } + // CommonsJS require and module both have type any. + if (symbol === requireSymbol || symbol === moduleSymbol) { + return links.type = anyType; + } // Handle catch clause variables var declaration = symbol.valueDeclaration; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return links.type = anyType; } // Handle export default expressions - if (declaration.kind === 247 /* ExportAssignment */) { - return links.type = checkExpression(declaration.expression); + if (ts.isSourceFile(declaration)) { + var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); + return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; } - if (ts.isInJavaScriptFile(declaration) && ts.isJSDocPropertyLikeTag(declaration) && declaration.typeExpression) { - return links.type = getTypeFromTypeNode(declaration.typeExpression.type); + if (declaration.kind === 252 /* ExportAssignment */) { + return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } - var type = void 0; - // Handle certain special assignment kinds, which happen to union across multiple declarations: - // * module.exports = expr - // * exports.p = expr - // * this.p = expr - // * className.prototype.method = expr - if (declaration.kind === 198 /* BinaryExpression */ || - declaration.kind === 183 /* PropertyAccessExpression */ && declaration.parent.kind === 198 /* BinaryExpression */) { - type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); - } - else if (ts.isJSDocPropertyTag(declaration) - || ts.isPropertyAccessExpression(declaration) - || ts.isIdentifier(declaration) - || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { - // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { - return getTypeOfFuncClassEnumModule(symbol); + var type = getJSSpecialType(symbol, declaration); + if (!type) { + if (ts.isJSDocPropertyLikeTag(declaration) + || ts.isPropertyAccessExpression(declaration) + || ts.isIdentifier(declaration) + || ts.isClassDeclaration(declaration) + || ts.isFunctionDeclaration(declaration) + || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) + || ts.isMethodSignature(declaration)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { + return getTypeOfFuncClassEnumModule(symbol); + } + type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; + } + else if (ts.isPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); + } + else if (ts.isJsxAttribute(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); + } + else if (ts.isShorthandPropertyAssignment(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); + } + else if (ts.isObjectLiteralMethod(declaration)) { + type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); + } + else if (ts.isParameter(declaration) + || ts.isPropertyDeclaration(declaration) + || ts.isPropertySignature(declaration) + || ts.isVariableDeclaration(declaration) + || ts.isBindingElement(declaration)) { + type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + } + else { + return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } - type = tryGetTypeFromEffectiveTypeNode(declaration) || anyType; - } - else if (ts.isPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration); - } - else if (ts.isJsxAttribute(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration); - } - else if (ts.isShorthandPropertyAssignment(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */); - } - else if (ts.isObjectLiteralMethod(declaration)) { - type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */); - } - else if (ts.isParameter(declaration) - || ts.isPropertyDeclaration(declaration) - || ts.isPropertySignature(declaration) - || ts.isVariableDeclaration(declaration) - || ts.isBindingElement(declaration)) { - type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - } - else { - ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration)); } if (!popTypeResolution()) { type = reportCircularityError(symbol); @@ -28926,9 +33192,57 @@ var ts; } return links.type; } + function getJSSpecialType(symbol, decl) { + if (!ts.isInJavaScriptFile(decl)) { + return undefined; + } + else if (ts.isJSDocPropertyLikeTag(decl) && decl.typeExpression) { + return getTypeFromTypeNode(decl.typeExpression.type); + } + // Handle certain special assignment kinds, which happen to union across multiple declarations: + // * module.exports = expr + // * exports.p = expr + // * this.p = expr + // * className.prototype.method = expr + else if (ts.isBinaryExpression(decl) || + ts.isPropertyAccessExpression(decl) && ts.isBinaryExpression(decl.parent)) { + return getJSInitializerType(decl, symbol, ts.getAssignedJavascriptInitializer(ts.isBinaryExpression(decl) ? decl.left : decl)) || + getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } + else if (ts.isParameter(decl) + || ts.isPropertyDeclaration(decl) + || ts.isPropertySignature(decl) + || ts.isVariableDeclaration(decl) + || ts.isBindingElement(decl)) { + // Use type from type annotation if one is present + var isOptional = ts.isParameter(decl) && isJSDocOptionalParameter(decl) || + !ts.isBindingElement(decl) && !ts.isVariableDeclaration(decl) && !!decl.questionToken; + var declaredType = tryGetTypeFromEffectiveTypeNode(decl); + return declaredType && addOptionality(declaredType, isOptional) || + getJSInitializerType(decl, symbol, ts.getDeclaredJavascriptInitializer(decl)) || + getWidenedTypeForVariableLikeDeclaration(decl, /*includeOptionality*/ true); + } + } + function getJSInitializerType(decl, symbol, init) { + if (init && ts.isInJavaScriptFile(init) && ts.isObjectLiteralExpression(init)) { + var exports_1 = ts.createSymbolTable(); + while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) { + var s_1 = getSymbolOfNode(decl); + if (s_1 && ts.hasEntries(s_1.exports)) { + mergeSymbolTable(exports_1, s_1.exports); + } + decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent; + } + var s = getSymbolOfNode(decl); + if (s && ts.hasEntries(s.exports)) { + mergeSymbolTable(exports_1, s.exports); + } + return createAnonymousType(symbol, exports_1, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + } + } function getAnnotatedAccessorType(accessor) { if (accessor) { - if (accessor.kind === 155 /* GetAccessor */) { + if (accessor.kind === 156 /* GetAccessor */) { var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor); return getterTypeAnnotation && getTypeFromTypeNode(getterTypeAnnotation); } @@ -28949,8 +33263,8 @@ var ts; function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - var getter = ts.getDeclarationOfKind(symbol, 155 /* GetAccessor */); - var setter = ts.getDeclarationOfKind(symbol, 156 /* SetAccessor */); + var getter = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); + var setter = ts.getDeclarationOfKind(symbol, 157 /* SetAccessor */); if (getter && ts.isInJavaScriptFile(getter)) { var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { @@ -28958,7 +33272,7 @@ var ts; } } if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } var type = void 0; // First try to see if the user specified a return type on the get-accessor. @@ -28995,7 +33309,7 @@ var ts; if (!popTypeResolution()) { type = anyType; if (noImplicitAny) { - var getter_1 = ts.getDeclarationOfKind(symbol, 155 /* GetAccessor */); + var getter_1 = ts.getDeclarationOfKind(symbol, 156 /* GetAccessor */); error(getter_1, 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, symbolToString(symbol)); } } @@ -29005,14 +33319,35 @@ var ts; } function getBaseTypeVariableOfClass(symbol) { var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol)); - return baseConstructorType.flags & 1081344 /* TypeVariable */ ? baseConstructorType : undefined; + return baseConstructorType.flags & 2162688 /* TypeVariable */ ? baseConstructorType : undefined; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { + var jsDeclaration = ts.getDeclarationOfJSInitializer(symbol.valueDeclaration); + if (jsDeclaration) { + var jsSymbol = getSymbolOfNode(jsDeclaration); + if (jsSymbol && (ts.hasEntries(jsSymbol.exports) || ts.hasEntries(jsSymbol.members))) { + symbol = cloneSymbol(symbol); + // note:we overwrite links because we just cloned the symbol + links = symbol; + if (ts.hasEntries(jsSymbol.exports)) { + symbol.exports = symbol.exports || ts.createSymbolTable(); + mergeSymbolTable(symbol.exports, jsSymbol.exports); + } + if (ts.hasEntries(jsSymbol.members)) { + symbol.members = symbol.members || ts.createSymbolTable(); + mergeSymbolTable(symbol.members, jsSymbol.members); + } + } + } if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) { links.type = anyType; } + else if (symbol.valueDeclaration.kind === 202 /* BinaryExpression */ || + symbol.valueDeclaration.kind === 187 /* PropertyAccessExpression */ && symbol.valueDeclaration.parent.kind === 202 /* BinaryExpression */) { + links.type = getWidenedTypeFromJSSpecialPropertyDeclarations(symbol); + } else { var type = createObjectType(16 /* Anonymous */, symbol); if (symbol.flags & 32 /* Class */) { @@ -29044,7 +33379,7 @@ var ts; // up recursively calling getTypeOfAlias, causing a stack overflow. links.type = targetSymbol.flags & 67216319 /* Value */ ? getTypeOfSymbol(targetSymbol) - : unknownType; + : errorType; } return links.type; } @@ -29053,11 +33388,11 @@ var ts; if (!links.type) { if (symbolInstantiationDepth === 100) { error(symbol.valueDeclaration, ts.Diagnostics.Generic_type_instantiation_is_excessively_deep_and_possibly_infinite); - links.type = unknownType; + links.type = errorType; } else { if (!pushTypeResolution(symbol, 0 /* Type */)) { - return unknownType; + return errorType; } symbolInstantiationDepth++; var type = instantiateType(getTypeOfSymbol(links.target), links.mapper); @@ -29074,7 +33409,7 @@ var ts; // Check if variable has type annotation that circularly references the variable itself if (ts.getEffectiveTypeAnnotationNode(symbol.valueDeclaration)) { error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); - return unknownType; + return errorType; } // Otherwise variable has initializer that circularly references the variable itself if (noImplicitAny) { @@ -29104,7 +33439,7 @@ var ts; if (symbol.flags & 2097152 /* Alias */) { return getTypeOfAlias(symbol); } - return unknownType; + return errorType; } function isReferenceToType(type, target) { return type !== undefined @@ -29115,16 +33450,18 @@ var ts; function getTargetType(type) { return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type; } + // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false. function hasBaseType(type, checkBase) { return check(type); function check(type) { if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { var target = getTargetType(type); - return target === checkBase || ts.forEach(getBaseTypes(target), check); + return target === checkBase || ts.some(getBaseTypes(target), check); } - else if (type.flags & 262144 /* Intersection */) { - return ts.forEach(type.types, check); + else if (type.flags & 524288 /* Intersection */) { + return ts.some(type.types, check); } + return false; } } // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set. @@ -29133,46 +33470,47 @@ var ts; function appendTypeParameters(typeParameters, declarations) { for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { var declaration = declarations_2[_i]; - var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); - typeParameters = ts.appendIfUnique(typeParameters, tp); + typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration))); } return typeParameters; } // Return the outer type parameters of a node or undefined if the node has no outer type parameters. function getOuterTypeParameters(node, includeThisTypes) { while (true) { - node = node.parent; + node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead if (!node) { return undefined; } switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 152 /* MethodSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 280 /* JSDocFunctionType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 235 /* TypeAliasDeclaration */: - case 290 /* JSDocTemplateTag */: - case 176 /* MappedType */: - case 170 /* ConditionalType */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 153 /* MethodSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 287 /* JSDocFunctionType */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 240 /* TypeAliasDeclaration */: + case 300 /* JSDocTemplateTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 179 /* MappedType */: + case 173 /* ConditionalType */: var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 176 /* MappedType */) { + if (node.kind === 179 /* MappedType */) { return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter))); } - else if (node.kind === 170 /* ConditionalType */) { + else if (node.kind === 173 /* ConditionalType */) { return ts.concatenate(outerTypeParameters, getInferTypeParameters(node)); } - var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node) || ts.emptyArray); + var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node)); var thisType = includeThisTypes && - (node.kind === 233 /* ClassDeclaration */ || node.kind === 203 /* ClassExpression */ || node.kind === 234 /* InterfaceDeclaration */) && + (node.kind === 238 /* ClassDeclaration */ || node.kind === 207 /* ClassExpression */ || node.kind === 239 /* InterfaceDeclaration */) && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType; return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } @@ -29180,7 +33518,7 @@ var ts; } // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { - var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 234 /* InterfaceDeclaration */); + var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -29189,12 +33527,12 @@ var ts; var result; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var node = _a[_i]; - if (node.kind === 234 /* InterfaceDeclaration */ || node.kind === 233 /* ClassDeclaration */ || - node.kind === 203 /* ClassExpression */ || node.kind === 235 /* TypeAliasDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 238 /* ClassDeclaration */ || + node.kind === 207 /* ClassExpression */ || + ts.isTypeAlias(node)) { var declaration = node; - if (declaration.typeParameters) { - result = appendTypeParameters(result, declaration.typeParameters); - } + result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration)); } } return result; @@ -29218,22 +33556,14 @@ var ts; if (isValidBaseType(type) && getSignaturesOfType(type, 1 /* Construct */).length > 0) { return true; } - if (type.flags & 1081344 /* TypeVariable */) { + if (type.flags & 2162688 /* TypeVariable */) { var constraint = getBaseConstraintOfType(type); - return constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); + return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } return false; } function getBaseTypeNodeOfClass(type) { - var decl = type.symbol.valueDeclaration; - if (ts.isInJavaScriptFile(decl)) { - // Prefer an @augments tag because it may have type parameters. - var tag = ts.getJSDocAugmentsTag(decl); - if (tag) { - return tag.class; - } - } - return ts.getClassExtendsHeritageClauseElement(decl); + return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -29256,31 +33586,31 @@ var ts; function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { var decl = type.symbol.valueDeclaration; - var extended = ts.getClassExtendsHeritageClauseElement(decl); + var extended = ts.getEffectiveBaseTypeNode(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) { - return unknownType; + return errorType; } var baseConstructorType = checkExpression(baseTypeNode.expression); if (extended && baseTypeNode !== extended) { ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag checkExpression(extended.expression); } - if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */)) { + if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */)) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. resolveStructuredTypeMembers(baseConstructorType); } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = unknownType; + return type.resolvedBaseConstructorType = errorType; } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); - return type.resolvedBaseConstructorType = unknownType; + return type.resolvedBaseConstructorType = errorType; } type.resolvedBaseConstructorType = baseConstructorType; } @@ -29289,7 +33619,7 @@ var ts; function getBaseTypes(type) { if (!type.resolvedBaseTypes) { if (type.objectFlags & 8 /* Tuple */) { - type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters))]; + type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray))]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { if (type.symbol.flags & 32 /* Class */) { @@ -29308,7 +33638,7 @@ var ts; function resolveBaseTypesOfClass(type) { type.resolvedBaseTypes = ts.resolvingEmptyArray; var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type)); - if (!(baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1 /* Any */))) { + if (!(baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 1 /* Any */))) { return type.resolvedBaseTypes = ts.emptyArray; } var baseTypeNode = getBaseTypeNodeOfClass(type); @@ -29336,7 +33666,7 @@ var ts; } baseType = getReturnTypeOfSignature(constructors[0]); } - if (baseType === unknownType) { + if (baseType === errorType) { return type.resolvedBaseTypes = ts.emptyArray; } if (!isValidBaseType(baseType)) { @@ -29370,18 +33700,18 @@ var ts; // A valid base type is `any`, any non-generic object type or intersection of non-generic // object types. function isValidBaseType(type) { - return type.flags & (65536 /* Object */ | 134217728 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) || - type.flags & 262144 /* Intersection */ && !ts.forEach(type.types, function (t) { return !isValidBaseType(t); }); + return !!(type.flags & (131072 /* Object */ | 16777216 /* NonPrimitive */ | 1 /* Any */)) && !isGenericMappedType(type) || + !!(type.flags & 524288 /* Intersection */) && ts.every(type.types, isValidBaseType); } function resolveBaseTypesOfInterface(type) { type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray; for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 234 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { + if (declaration.kind === 239 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) { for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) { var node = _c[_b]; var baseType = getTypeFromTypeNode(node); - if (baseType !== unknownType) { + if (baseType !== errorType) { if (isValidBaseType(baseType)) { if (type !== baseType && !hasBaseType(baseType, type)) { if (type.resolvedBaseTypes === ts.emptyArray) { @@ -29413,7 +33743,7 @@ var ts; function isThislessInterface(symbol) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 234 /* InterfaceDeclaration */) { + if (declaration.kind === 239 /* InterfaceDeclaration */) { if (declaration.flags & 64 /* ContainsThis */) { return false; } @@ -29454,7 +33784,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(32768 /* TypeParameter */); + type.thisType = createType(65536 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; @@ -29468,14 +33798,14 @@ var ts; // Note that we use the links object as the target here because the symbol object is used as the unique // identity for resolution of the 'type' property in SymbolLinks. if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) { - return unknownType; + return errorType; } var declaration = ts.find(symbol.declarations, function (d) { - return d.kind === 291 /* JSDocTypedefTag */ || d.kind === 235 /* TypeAliasDeclaration */; + return ts.isJSDocTypeAlias(d) || d.kind === 240 /* TypeAliasDeclaration */; }); - var typeNode = declaration.kind === 291 /* JSDocTypedefTag */ ? declaration.typeExpression : declaration.type; + var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type; // If typeNode is missing, we will error in checkJSDocTypedefTag. - var type = typeNode ? getTypeFromTypeNode(typeNode) : unknownType; + var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType; if (popTypeResolution()) { var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); if (typeParameters) { @@ -29487,27 +33817,38 @@ var ts; } } else { - type = unknownType; + type = errorType; error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } links.declaredType = type; } return links.declaredType; } + function isStringConcatExpression(expr) { + if (expr.kind === 9 /* StringLiteral */) { + return true; + } + else if (expr.kind === 202 /* BinaryExpression */) { + return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right); + } + return false; + } function isLiteralEnumMember(member) { var expr = member.initializer; if (!expr) { - return !(member.flags & 2097152 /* Ambient */); + return !(member.flags & 4194304 /* Ambient */); } switch (expr.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: return true; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; case 71 /* Identifier */: return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText); + case 202 /* BinaryExpression */: + return isStringConcatExpression(expr); default: return false; } @@ -29520,7 +33861,7 @@ var ts; var hasNonLiteralMember = false; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; if (member.initializer && member.initializer.kind === 9 /* StringLiteral */) { @@ -29535,7 +33876,7 @@ var ts; return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */; } function getBaseTypeOfEnumLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; + return type.flags & 512 /* EnumLiteral */ && !(type.flags & 262144 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type; } function getDeclaredTypeOfEnum(symbol) { var links = getSymbolLinks(symbol); @@ -29547,10 +33888,10 @@ var ts; var memberTypeList = []; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (declaration.kind === 236 /* EnumDeclaration */) { + if (declaration.kind === 241 /* EnumDeclaration */) { for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) { var member = _c[_b]; - var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); + var memberType = getLiteralType(getEnumMemberValue(member), enumCount, getSymbolOfNode(member)); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; memberTypeList.push(memberType); } @@ -29558,14 +33899,14 @@ var ts; } if (memberTypeList.length) { var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined); - if (enumType_1.flags & 131072 /* Union */) { - enumType_1.flags |= 256 /* EnumLiteral */; + if (enumType_1.flags & 262144 /* Union */) { + enumType_1.flags |= 512 /* EnumLiteral */; enumType_1.symbol = symbol; } return links.declaredType = enumType_1; } } - var enumType = createType(16 /* Enum */); + var enumType = createType(32 /* Enum */); enumType.symbol = symbol; return links.declaredType = enumType; } @@ -29582,7 +33923,7 @@ var ts; function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - var type = createType(32768 /* TypeParameter */); + var type = createType(65536 /* TypeParameter */); type.symbol = symbol; links.declaredType = type; } @@ -29596,7 +33937,7 @@ var ts; return links.declaredType; } function getDeclaredTypeOfSymbol(symbol) { - return tryGetDeclaredTypeOfSymbol(symbol) || unknownType; + return tryGetDeclaredTypeOfSymbol(symbol) || errorType; } function tryGetDeclaredTypeOfSymbol(symbol) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -29627,6 +33968,7 @@ var ts; function isThislessType(node) { switch (node.kind) { case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 122 /* BooleanKeyword */: @@ -29636,11 +33978,11 @@ var ts; case 140 /* UndefinedKeyword */: case 95 /* NullKeyword */: case 131 /* NeverKeyword */: - case 177 /* LiteralType */: + case 180 /* LiteralType */: return true; - case 166 /* ArrayType */: + case 167 /* ArrayType */: return isThislessType(node.elementType); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; @@ -29664,9 +34006,10 @@ var ts; */ function isThislessFunctionLikeDeclaration(node) { var returnType = ts.getEffectiveReturnTypeNode(node); - return (node.kind === 154 /* Constructor */ || (returnType && isThislessType(returnType))) && + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + return (node.kind === 155 /* Constructor */ || (!!returnType && isThislessType(returnType))) && node.parameters.every(isThislessVariableLikeDeclaration) && - (!node.typeParameters || node.typeParameters.every(isThislessTypeParameter)); + typeParameters.every(isThislessTypeParameter); } /** * Returns true if the class or interface member given by the symbol is free of "this" references. The @@ -29680,12 +34023,12 @@ var ts; var declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return isThislessVariableLikeDeclaration(declaration); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: return isThislessFunctionLikeDeclaration(declaration); } } @@ -29715,6 +34058,9 @@ var ts; var symbol = type.symbol; var members = getMembersOfSymbol(symbol); type.declaredProperties = getNamedMembers(members); + // Start with signatures at empty array in case of recursive types + type.declaredCallSignatures = ts.emptyArray; + type.declaredConstructSignatures = ts.emptyArray; type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */); @@ -29726,7 +34072,7 @@ var ts; * Indicates whether a type can be used as a late-bound name. */ function isTypeUsableAsLateBoundName(type) { - return !!(type.flags & 1120 /* StringOrNumberLiteralOrUnique */); + return !!(type.flags & 2240 /* StringOrNumberLiteralOrUnique */); } /** * Indicates whether a declaration name is definitely late-bindable. @@ -29741,12 +34087,17 @@ var ts; && ts.isEntityNameExpression(node.expression) && isTypeUsableAsLateBoundName(checkComputedPropertyName(node)); } + function isLateBoundName(name) { + return name.charCodeAt(0) === 95 /* _ */ && + name.charCodeAt(1) === 95 /* _ */ && + name.charCodeAt(2) === 64 /* at */; + } /** * Indicates whether a declaration has a late-bindable dynamic name. */ function hasLateBindableName(node) { var name = ts.getNameOfDeclaration(node); - return name && isLateBindableName(name); + return !!name && isLateBindableName(name); } /** * Indicates whether a declaration has a dynamic name that cannot be late-bound. @@ -29764,12 +34115,13 @@ var ts; * Gets the symbolic name for a late-bound member from its type. */ function getLateBoundNameFromType(type) { - if (type.flags & 1024 /* UniqueESSymbol */) { + if (type.flags & 2048 /* UniqueESSymbol */) { return "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol); } - if (type.flags & 96 /* StringOrNumberLiteral */) { + if (type.flags & 192 /* StringOrNumberLiteral */) { return ts.escapeLeadingUnderscores("" + type.value); } + return ts.Debug.fail(); } /** * Adds a declaration to a late-bound dynamic member. This performs the same function for @@ -29787,8 +34139,7 @@ var ts; symbol.declarations.push(member); } if (symbolFlags & 67216319 /* Value */) { - var valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || valueDeclaration.kind !== member.kind) { + if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) { symbol.valueDeclaration = member; } } @@ -29844,16 +34195,12 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_3 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + var name_2 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); } - var symbolLinks_1 = getSymbolLinks(lateSymbol); - if (!symbolLinks_1.nameType) { - // Retain link to name type so that it can be reused later - symbolLinks_1.nameType = type; - } + lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); if (lateSymbol.parent) { ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one"); @@ -29883,8 +34230,8 @@ var ts; var decl = _a[_i]; var members = ts.getMembersOfDeclaration(decl); if (members) { - for (var _b = 0, members_3 = members; _b < members_3.length; _b++) { - var member = members_3[_b]; + for (var _b = 0, members_4 = members; _b < members_4.length; _b++) { + var member = members_4[_b]; if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); } @@ -29936,7 +34283,7 @@ var ts; return needApparentType ? getApparentType(ref) : ref; } } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } return needApparentType ? getApparentType(type) : type; @@ -30016,11 +34363,33 @@ var ts; return createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); } + function getExpandedParameters(sig) { + if (sig.hasRestParameter) { + var restIndex_1 = sig.parameters.length - 1; + var restParameter = sig.parameters[restIndex_1]; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var elementTypes = restType.typeArguments || ts.emptyArray; + var minLength_1 = restType.target.minLength; + var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; + var restParams = ts.map(elementTypes, function (t, i) { + var name = getParameterNameAtPosition(sig, restIndex_1 + i); + var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : + i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); + symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; + return symbol; + }); + return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams); + } + } + return sig.parameters; + } function getDefaultConstructSignatures(classType) { var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJavaScriptFile(baseTypeNode); @@ -30092,6 +34461,7 @@ var ts; if (unionSignatures.length > 1) { var thisParameter = signature.thisParameter; if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { + // TODO: GH#18217 We tested that *some* has thisParameter and now act as if *all* do var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return sig.thisParameter ? getTypeOfSymbol(sig.thisParameter) : anyType; }), 2 /* Subtype */); thisParameter = createSymbolWithType(signature.thisParameter, thisType); } @@ -30159,7 +34529,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_3 = function (i) { + var _loop_5 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -30182,7 +34552,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_3(i); + _loop_5(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -30192,6 +34562,7 @@ var ts; function resolveAnonymousTypeMembers(type) { var symbol = type.symbol; if (type.target) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false); var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper); var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper); @@ -30200,6 +34571,7 @@ var ts; setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } else if (symbol.flags & 2048 /* TypeLiteral */) { + setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var members = getMembersOfSymbol(symbol); var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */)); var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */)); @@ -30218,7 +34590,7 @@ var ts; if (symbol.flags & 32 /* Class */) { var classType = getDeclaredTypeOfClassOrInterface(symbol); var baseConstructorType = getBaseConstructorTypeOfClass(classType); - if (baseConstructorType.flags & (65536 /* Object */ | 262144 /* Intersection */ | 1081344 /* TypeVariable */)) { + if (baseConstructorType.flags & (131072 /* Object */ | 524288 /* Intersection */ | 2162688 /* TypeVariable */)) { members = ts.createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } @@ -30258,6 +34630,7 @@ var ts; var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; + inferredProp.nameType = prop.nameType; inferredProp.propertyType = getTypeOfSymbol(prop); inferredProp.mappedType = type.mappedType; members.set(prop.escapedName, inferredProp); @@ -30268,6 +34641,7 @@ var ts; function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; + var numberIndexInfo; // Resolve upfront such that recursive references see an empty object type. setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type, @@ -30277,35 +34651,30 @@ var ts; var templateType = getTemplateTypeFromMappedType(type.target || type); var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T' var templateModifiers = getMappedTypeModifiers(type); - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + var include = keyofStringsOnly ? 64 /* StringLiteral */ : 2240 /* StringOrNumberLiteralOrUnique */; + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // We have a { [P in keyof T]: X } for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) { - var propertySymbol = _a[_i]; - addMemberForKeyType(getLiteralTypeFromPropertyName(propertySymbol), propertySymbol); + var prop = _a[_i]; + addMemberForKeyType(getLiteralTypeFromPropertyName(prop, include), /*_index*/ undefined, prop); } if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) { addMemberForKeyType(stringType); } + if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) { + addMemberForKeyType(numberType); + } } else { // First, if the constraint type is a type parameter, obtain the base constraint. Then, // if the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. // Finally, iterate over the constituents of the resulting iteration type. - var keyType = constraintType.flags & 7372800 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; - var iterationType = keyType.flags & 524288 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; + var keyType = constraintType.flags & 14745600 /* InstantiableNonPrimitive */ ? getApparentType(constraintType) : constraintType; + var iterationType = keyType.flags & 1048576 /* Index */ ? getIndexType(getApparentType(keyType.type)) : keyType; forEachType(iterationType, addMemberForKeyType); } - setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); - function addMemberForKeyType(t, propertySymbolOrIndex) { - var propertySymbol; - // forEachType delegates to forEach, which calls with a numeric second argument - // the type system currently doesn't catch this incompatibility, so we annotate - // the function ourselves to indicate the runtime behavior and deal with it here - if (typeof propertySymbolOrIndex === "object") { - propertySymbol = propertySymbolOrIndex; - } + setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); + function addMemberForKeyType(t, _index, origin) { // Create a mapper from T to the current iteration type constituent. Then, if the // mapped type is itself an instantiated type, combine the iteration mapper with the // instantiation mapper. @@ -30313,7 +34682,7 @@ var ts; var propType = instantiateType(templateType, templateMapper); // If the current iteration type constituent is a string literal type, create a property. // Otherwise, for type string create a string index signature. - if (t.flags & 32 /* StringLiteral */) { + if (t.flags & 2240 /* StringOrNumberLiteralOrUnique */) { var propName = getLateBoundNameFromType(t); var modifiersProp = getPropertyOfType(modifiersType, propName); var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ || @@ -30327,16 +34696,19 @@ var ts; prop.type = strictNullChecks && isOptional && !isTypeAssignableTo(undefinedType, propType) ? getOptionalType(propType) : strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */ ? getTypeWithFacts(propType, 131072 /* NEUndefined */) : propType; - if (propertySymbol) { - prop.syntheticOrigin = propertySymbol; - prop.declarations = propertySymbol.declarations; + if (origin) { + prop.syntheticOrigin = origin; + prop.declarations = origin.declarations; } prop.nameType = t; members.set(propName, prop); } - else if (t.flags & (1 /* Any */ | 2 /* String */)) { + else if (t.flags & (1 /* Any */ | 4 /* String */)) { stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); } + else if (t.flags & 8 /* Number */) { + numberIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */)); + } } } function getTypeParameterFromMappedType(type) { @@ -30345,23 +34717,29 @@ var ts; } function getConstraintTypeFromMappedType(type) { return type.constraintType || - (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || unknownType); + (type.constraintType = instantiateType(getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)), type.mapper || identityMapper) || errorType); } function getTemplateTypeFromMappedType(type) { return type.templateType || (type.templateType = type.declaration.type ? instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper || identityMapper) : - unknownType); + errorType); + } + function getConstraintDeclarationForMappedType(type) { + return type.declaration.typeParameter.constraint; + } + function isMappedTypeWithKeyofConstraintDeclaration(type) { + var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217 + return constraintDeclaration.kind === 177 /* TypeOperator */ && + constraintDeclaration.operator === 128 /* KeyOfKeyword */; } function getModifiersTypeFromMappedType(type) { if (!type.modifiersType) { - var constraintDeclaration = type.declaration.typeParameter.constraint; - if (constraintDeclaration.kind === 174 /* TypeOperator */ && - constraintDeclaration.operator === 128 /* KeyOfKeyword */) { + if (isMappedTypeWithKeyofConstraintDeclaration(type)) { // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves // 'keyof T' to a literal union type and we can't recover T from that type. - type.modifiersType = instantiateType(getTypeFromTypeNode(constraintDeclaration.type), type.mapper || identityMapper); + type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper || identityMapper); } else { // Otherwise, get the declared constraint type, and if the constraint type is a type parameter, @@ -30369,8 +34747,8 @@ var ts; // the modifiers type is T. Otherwise, the modifiers type is {}. var declaredType = getTypeFromMappedTypeNode(type.declaration); var constraint = getConstraintTypeFromMappedType(declaredType); - var extendedConstraint = constraint && constraint.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; - type.modifiersType = extendedConstraint && extendedConstraint.flags & 524288 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; + var extendedConstraint = constraint && constraint.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint; + type.modifiersType = extendedConstraint && extendedConstraint.flags & 1048576 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper || identityMapper) : emptyObjectType; } } return type.modifiersType; @@ -30393,11 +34771,11 @@ var ts; return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */); } function isGenericMappedType(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && isGenericIndexType(getConstraintTypeFromMappedType(type)); + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type)); } function resolveStructuredTypeMembers(type) { if (!type.members) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { if (type.objectFlags & 4 /* Reference */) { resolveTypeReferenceMembers(type); } @@ -30414,10 +34792,10 @@ var ts; resolveMappedTypeMembers(type); } } - else if (type.flags & 131072 /* Union */) { + else if (type.flags & 262144 /* Union */) { resolveUnionTypeMembers(type); } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { resolveIntersectionTypeMembers(type); } } @@ -30425,7 +34803,7 @@ var ts; } /** Return properties of an object type or an empty array for other types */ function getPropertiesOfObjectType(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { return resolveStructuredTypeMembers(type).properties; } return ts.emptyArray; @@ -30434,7 +34812,7 @@ var ts; * return the symbol for that property. Otherwise return undefined. */ function getPropertyOfObjectType(type, name) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -30458,7 +34836,7 @@ var ts; } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { break; } } @@ -30468,13 +34846,24 @@ var ts; } function getPropertiesOfType(type) { type = getApparentType(type); - return type.flags & 393216 /* UnionOrIntersection */ ? + return type.flags & 786432 /* UnionOrIntersection */ ? getPropertiesOfUnionOrIntersectionType(type) : getPropertiesOfObjectType(type); } + function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) { + return obj.properties.some(function (property) { + var name = property.name && ts.getTextOfPropertyName(property.name); + var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); + if (expected && typeIsLiteralType(expected)) { + var actual = getTypeOfNode(property); + return !!actual && !isTypeIdenticalTo(actual, expected); + } + return false; + }); + } function getAllPossiblePropertiesOfTypes(types) { var unionType = getUnionType(types); - if (!(unionType.flags & 131072 /* Union */)) { + if (!(unionType.flags & 262144 /* Union */)) { return getAugmentedPropertiesOfType(unionType); } var props = ts.createSymbolTable(); @@ -30493,30 +34882,27 @@ var ts; return ts.arrayFrom(props.values()); } function getConstraintOfType(type) { - return type.flags & 32768 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : - type.flags & 1048576 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : - type.flags & 2097152 /* Conditional */ ? getConstraintOfConditionalType(type) : + return type.flags & 65536 /* TypeParameter */ ? getConstraintOfTypeParameter(type) : + type.flags & 2097152 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) : + type.flags & 4194304 /* Conditional */ ? getConstraintOfConditionalType(type) : getBaseConstraintOfType(type); } function getConstraintOfTypeParameter(typeParameter) { return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getSimplifiedIndexedAccessType(type); - if (transformed) { - return transformed; - } - var baseObjectType = getBaseConstraintOfType(type.objectType); - var baseIndexType = getBaseConstraintOfType(type.indexType); - if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { - // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. - // to avoid this, return `undefined`. - return undefined; - } - return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; + var objectType = getBaseConstraintOfType(type.objectType) || type.objectType; + var indexType = getBaseConstraintOfType(type.indexType) || type.indexType; + var constraint = !isGenericObjectType(objectType) && !isGenericIndexType(indexType) ? getIndexedAccessType(objectType, indexType) : undefined; + return constraint && constraint !== errorType ? constraint : undefined; } function getDefaultConstraintOfConditionalType(type) { - return getUnionType([getTrueTypeFromConditionalType(type), getFalseTypeFromConditionalType(type)]); + if (!type.resolvedDefaultConstraint) { + var rootTrueType = type.root.trueType; + var rootTrueConstraint = rootTrueType.flags & 8388608 /* Substitution */ ? rootTrueType.substitute : rootTrueType; + type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + } + return type.resolvedDefaultConstraint; } function getConstraintOfDistributiveConditionalType(type) { // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained @@ -30525,10 +34911,13 @@ var ts; // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. if (type.root.isDistributive) { - var constraint = getConstraintOfType(type.checkType); + var constraint = getConstraintOfType(getSimplifiedType(type.checkType)); if (constraint) { - var mapper = createTypeMapper([type.root.checkType], [constraint]); - return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + if (!(instantiated.flags & 32768 /* Never */)) { + return instantiated; + } } } return undefined; @@ -30536,20 +34925,54 @@ var ts; function getConstraintOfConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } - function getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type) { - if (type.flags & (7372800 /* InstantiableNonPrimitive */ | 393216 /* UnionOrIntersection */)) { - var constraint = getResolvedBaseConstraint(type); - if (constraint !== noConstraintType && constraint !== circularConstraintType) { - return constraint; + function getUnionConstraintOfIntersection(type, targetIsUnion) { + var constraints; + var hasDisjointDomainType = false; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 15794176 /* Instantiable */) { + // We keep following constraints as long as we have an instantiable type that is known + // not to be circular or infinite (hence we stop on index access types). + var constraint = getConstraintOfType(t); + while (constraint && constraint.flags & (65536 /* TypeParameter */ | 1048576 /* Index */ | 4194304 /* Conditional */)) { + constraint = getConstraintOfType(constraint); + } + if (constraint) { + // A constraint that isn't a union type implies that the final type would be a non-union + // type as well. Since non-union constraints are of no interest, we can exit here. + if (!(constraint.flags & 262144 /* Union */)) { + return undefined; + } + constraints = ts.append(constraints, constraint); + } + } + else if (t.flags & 16809468 /* DisjointDomains */) { + hasDisjointDomainType = true; } } + // If the target is a union type or if we are intersecting with types belonging to one of the + // disjoint domans, we may end up producing a constraint that hasn't been examined before. + if (constraints && (targetIsUnion || hasDisjointDomainType)) { + if (hasDisjointDomainType) { + // We add any types belong to one of the disjoint domans because they might cause the final + // intersection operation to reduce the union constraints. + for (var _b = 0, _c = type.types; _b < _c.length; _b++) { + var t = _c[_b]; + if (t.flags & 16809468 /* DisjointDomains */) { + constraints = ts.append(constraints, t); + } + } + } + return getIntersectionType(constraints); + } + return undefined; } function getBaseConstraintOfType(type) { - var constraint = getBaseConstraintOfInstantiableNonPrimitiveUnionOrIntersection(type); - if (!constraint && type.flags & 524288 /* Index */) { - return stringType; + if (type.flags & (14745600 /* InstantiableNonPrimitive */ | 786432 /* UnionOrIntersection */)) { + var constraint = getResolvedBaseConstraint(type); + return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined; } - return constraint; + return type.flags & 1048576 /* Index */ ? keyofConstraintType : undefined; } /** * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined` @@ -30567,63 +34990,60 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var circular; - if (!type.resolvedBaseConstraint) { - var constraint = getBaseConstraint(type); - type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); + return type.resolvedBaseConstraint || + (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type)); + function getImmediateBaseConstraint(t) { + if (!t.immediateBaseConstraint) { + if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { + return circularConstraintType; + } + var result = computeBaseConstraint(getSimplifiedType(t)); + if (!popTypeResolution()) { + result = circularConstraintType; + } + t.immediateBaseConstraint = result || noConstraintType; + } + return t.immediateBaseConstraint; } - return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { - circular = true; - return undefined; - } - var result = computeBaseConstraint(t); - if (!popTypeResolution()) { - circular = true; - return undefined; - } - return result; + var c = getImmediateBaseConstraint(t); + return c !== noConstraintType && c !== circularConstraintType ? c : undefined; } function computeBaseConstraint(t) { - if (t.flags & 32768 /* TypeParameter */) { + if (t.flags & 65536 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); return t.isThisType || !constraint ? constraint : getBaseConstraint(constraint); } - if (t.flags & 393216 /* UnionOrIntersection */) { + if (t.flags & 786432 /* UnionOrIntersection */) { var types = t.types; var baseTypes = []; for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { - var type_2 = types_4[_i]; - var baseType = getBaseConstraint(type_2); + var type_3 = types_4[_i]; + var baseType = getBaseConstraint(type_3); if (baseType) { baseTypes.push(baseType); } } - return t.flags & 131072 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : - t.flags & 262144 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : + return t.flags & 262144 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) : + t.flags & 524288 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) : undefined; } - if (t.flags & 524288 /* Index */) { - return stringType; + if (t.flags & 1048576 /* Index */) { + return keyofConstraintType; } - if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getSimplifiedIndexedAccessType(t); - if (transformed) { - return getBaseConstraint(transformed); - } + if (t.flags & 2097152 /* IndexedAccess */) { 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; + return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } - if (t.flags & 2097152 /* Conditional */) { + if (t.flags & 4194304 /* Conditional */) { var constraint = getConstraintOfConditionalType(t); return constraint && getBaseConstraint(constraint); } - if (t.flags & 4194304 /* Substitution */) { + if (t.flags & 8388608 /* Substitution */) { return getBaseConstraint(t.substitute); } if (isGenericMappedType(t)) { @@ -30684,18 +35104,20 @@ var ts; * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type) { - var t = type.flags & 7897088 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; - return t.flags & 262144 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : - t.flags & 524322 /* StringLike */ ? globalStringType : - t.flags & 84 /* NumberLike */ ? globalNumberType : - t.flags & 136 /* BooleanLike */ ? globalBooleanType : - t.flags & 1536 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : - t.flags & 134217728 /* NonPrimitive */ ? emptyObjectType : - t; + var t = type.flags & 15794176 /* Instantiable */ ? getBaseConstraintOfType(type) || emptyObjectType : type; + return t.flags & 524288 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : + t.flags & 68 /* StringLike */ ? globalStringType : + t.flags & 168 /* NumberLike */ ? globalNumberType : + t.flags & 272 /* BooleanLike */ ? globalBooleanType : + t.flags & 3072 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) : + t.flags & 16777216 /* NonPrimitive */ ? emptyObjectType : + t.flags & 1048576 /* Index */ ? keyofConstraintType : + t; } function createUnionOrIntersectionProperty(containingType, name) { var props; - var isUnion = containingType.flags & 131072 /* Union */; + var indexTypes; + var isUnion = containingType.flags & 262144 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = isUnion ? 0 /* None */ : 16777216 /* Optional */; @@ -30704,7 +35126,7 @@ var ts; for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var current = _a[_i]; var type = getApparentType(current); - if (type !== unknownType) { + if (type !== errorType) { var prop = getPropertyOfType(type, name); var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { @@ -30715,41 +35137,65 @@ var ts; (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); - if (!isMethodLike(prop)) { + if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } } else if (isUnion) { - checkFlags |= 16 /* Partial */; + var index = !isLateBoundName(name) && ((isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */)) || getIndexInfoOfType(type, 0 /* String */)); + if (index) { + checkFlags |= index.isReadonly ? 8 /* Readonly */ : 0; + indexTypes = ts.append(indexTypes, index.type); + } + else { + checkFlags |= 16 /* Partial */; + } } } } if (!props) { return undefined; } - if (props.length === 1 && !(checkFlags & 16 /* Partial */)) { + if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } - var propTypes = []; - var declarations = []; + var declarations; var commonType; + var nameType; + var propTypes = []; + var first = true; + var commonValueDeclaration; + var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (prop.declarations) { - ts.addRange(declarations, prop.declarations); + if (!commonValueDeclaration) { + commonValueDeclaration = prop.valueDeclaration; } + else if (prop.valueDeclaration !== commonValueDeclaration) { + hasNonUniformValueDeclaration = true; + } + declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (!commonType) { + if (first) { commonType = type; + nameType = prop.nameType; + first = false; } - else if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; + else { + if (type !== commonType) { + checkFlags |= 32 /* HasNonUniformType */; + } } propTypes.push(type); } + ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; + if (!hasNonUniformValueDeclaration && commonValueDeclaration) { + result.valueDeclaration = commonValueDeclaration; + } result.declarations = declarations; + result.nameType = nameType; result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } @@ -30784,7 +35230,7 @@ var ts; */ function getPropertyOfType(type, name) { type = getApparentType(type); - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); var symbol = resolved.members.get(name); if (symbol && symbolIsValue(symbol)) { @@ -30798,13 +35244,13 @@ var ts; } return getPropertyOfObjectType(globalObjectType, name); } - if (type.flags & 393216 /* UnionOrIntersection */) { + if (type.flags & 786432 /* UnionOrIntersection */) { return getPropertyOfUnionOrIntersectionType(type, name); } return undefined; } function getSignaturesOfStructuredType(type, kind) { - if (type.flags & 458752 /* StructuredType */) { + if (type.flags & 917504 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures; } @@ -30818,7 +35264,7 @@ var ts; return getSignaturesOfStructuredType(getApparentType(type), kind); } function getIndexInfoOfStructuredType(type, kind) { - if (type.flags & 458752 /* StructuredType */) { + if (type.flags & 917504 /* StructuredType */) { var resolved = resolveStructuredTypeMembers(type); return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo; } @@ -30856,10 +35302,10 @@ var ts; // type checking functions). function getTypeParametersFromDeclaration(declaration) { var result; - ts.forEach(ts.getEffectiveTypeParameterDeclarations(declaration), function (node) { - var tp = getDeclaredTypeOfTypeParameter(node.symbol); - result = ts.appendIfUnique(result, tp); - }); + for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) { + var node = _a[_i]; + result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol)); + } return result; } function symbolsToArray(symbols) { @@ -30872,23 +35318,13 @@ var ts; return result; } function isJSDocOptionalParameter(node) { - if (ts.isInJavaScriptFile(node)) { - if (node.type && node.type.kind === 279 /* JSDocOptionalType */) { - return true; - } - var paramTags = ts.getJSDocParameterTags(node); - if (paramTags) { - for (var _i = 0, paramTags_1 = paramTags; _i < paramTags_1.length; _i++) { - var paramTag = paramTags_1[_i]; - if (paramTag.isBracketed) { - return true; - } - if (paramTag.typeExpression) { - return paramTag.typeExpression.type.kind === 279 /* JSDocOptionalType */; - } - } - } - } + return ts.isInJavaScriptFile(node) && ( + // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType + node.type && node.type.kind === 286 /* JSDocOptionalType */ + || ts.getJSDocParameterTags(node).some(function (_a) { + var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + })); } function tryFindAmbientModule(moduleName, withAugmentations) { if (ts.isExternalModuleNameRelative(moduleName)) { @@ -30899,14 +35335,14 @@ var ts; return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol; } function isOptionalParameter(node) { - if (ts.hasQuestionToken(node) || isJSDocOptionalParameter(node)) { + if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) { return true; } if (node.initializer) { var signature = getSignatureFromDeclaration(node.parent); var parameterIndex = node.parent.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); - return parameterIndex >= signature.minArgumentCount; + return parameterIndex >= getMinArgumentCount(signature); } var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); if (iife) { @@ -30916,6 +35352,13 @@ var ts; } return false; } + function isOptionalJSDocParameterTag(node) { + if (!ts.isJSDocParameterTag(node)) { + return false; + } + var isBracketed = node.isBracketed, typeExpression = node.typeExpression; + return isBracketed || !!typeExpression && typeExpression.type.kind === 286 /* JSDocOptionalType */; + } function createTypePredicateFromTypePredicateNode(node) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); @@ -30948,14 +35391,6 @@ var ts; } return minTypeArgumentCount; } - /** - * Fill in default types for unsupplied type arguments. If `typeArguments` is undefined - * when a default type is supplied, a new array will be created and returned. - * - * @param typeArguments The supplied type arguments. - * @param typeParameters The requested type parameters. - * @param minTypeArgumentCount The minimum number of required type arguments. - */ function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) { var numTypeParameters = ts.length(typeParameters); if (numTypeParameters) { @@ -30973,7 +35408,7 @@ var ts; for (var i = numTypeArguments; i < numTypeParameters; i++) { var mapper = createTypeMapper(typeParameters, typeArguments); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); - if (defaultType && isTypeIdenticalTo(defaultType, emptyObjectType) && isJavaScriptImplicitAny) { + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } typeArguments[i] = defaultType ? instantiateType(defaultType, mapper) : getDefaultTypeArgumentType(isJavaScriptImplicitAny); @@ -30990,16 +35425,21 @@ var ts; var hasLiteralTypes = false; var minArgumentCount = 0; var thisParameter = void 0; - var hasThisParameter = void 0; + var hasThisParameter = false; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); - var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); + var isUntypedSignatureInJSFile = !iife && + ts.isInJavaScriptFile(declaration) && + ts.isValueSignatureDeclaration(declaration) && + !ts.hasJSDocParameterTags(declaration) && + !ts.getJSDocType(declaration); // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct // signature. for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; + var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type; // Include parameter symbol instead of property symbol in the signature if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) { var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 67216319 /* Value */, undefined, undefined, /*isUse*/ false); @@ -31012,29 +35452,30 @@ var ts; else { parameters.push(paramSymbol); } - if (param.type && param.type.kind === 177 /* LiteralType */) { + if (type && type.kind === 180 /* LiteralType */) { hasLiteralTypes = true; } // Record a new minimum argument count if this is not an optional parameter - var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || - iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param) || - isUntypedSignatureInJSFile; + var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || + param.initializer || param.questionToken || param.dotDotDotToken || + iife && parameters.length > iife.arguments.length && !type || + isUntypedSignatureInJSFile || + isJSDocOptionalParameter(param); if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } } // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation - if ((declaration.kind === 155 /* GetAccessor */ || declaration.kind === 156 /* SetAccessor */) && + if ((declaration.kind === 156 /* GetAccessor */ || declaration.kind === 157 /* SetAccessor */) && !hasNonBindableDynamicName(declaration) && (!hasThisParameter || !thisParameter)) { - var otherKind = declaration.kind === 155 /* GetAccessor */ ? 156 /* SetAccessor */ : 155 /* GetAccessor */; + var otherKind = declaration.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind); if (other) { thisParameter = getAnnotatedAccessorThisParameter(other); } } - var classType = declaration.kind === 154 /* Constructor */ ? + var classType = declaration.kind === 155 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); @@ -31051,7 +35492,7 @@ var ts; * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...` */ function maybeAddJsSyntheticRestParameter(declaration, parameters) { - if (!containsArgumentsReference(declaration)) { + if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) { return false; } var lastParam = ts.lastOrUndefined(declaration.parameters); @@ -31059,9 +35500,8 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args"); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; - syntheticArgsSymbol.isRestParameter = true; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. parameters.pop(); @@ -31071,7 +35511,7 @@ var ts; } function getSignatureReturnTypeFromDeclaration(declaration, isJSConstructSignature, classType) { if (isJSConstructSignature) { - return getTypeFromTypeNode(declaration.parameters[0].type); + return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217 } else if (classType) { return classType; @@ -31082,14 +35522,23 @@ var ts; } // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. - if (declaration.kind === 155 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { - var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 156 /* SetAccessor */); + if (declaration.kind === 156 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) { + var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 157 /* SetAccessor */); return getAnnotatedAccessorType(setter); } + var typeFromTag = getReturnTypeOfTypeTag(declaration); + if (typeFromTag) { + return typeFromTag; + } if (ts.nodeIsMissing(declaration.body)) { return anyType; } } + function getReturnTypeOfTypeTag(node) { + var typeTag = ts.isInJavaScriptFile(node) ? ts.getJSDocTypeTag(node) : undefined; + var signatures = typeTag && typeTag.typeExpression && getSignaturesOfType(getTypeFromTypeNode(typeTag.typeExpression), 0 /* Call */); + return signatures && signatures.length === 1 ? getReturnTypeOfSignature(signatures[0]) : undefined; + } function containsArgumentsReference(declaration) { var links = getNodeLinks(declaration); if (links.containsArgumentsReference === undefined) { @@ -31107,14 +35556,14 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.escapedText === "arguments" && ts.isExpressionNode(node); - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return node.name.kind === 146 /* ComputedPropertyName */ + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return node.name.kind === 147 /* ComputedPropertyName */ && traverse(node.name); default: - return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && ts.forEachChild(node, traverse); + return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } } } @@ -31123,33 +35572,19 @@ var ts; return ts.emptyArray; var result = []; for (var i = 0; i < symbol.declarations.length; i++) { - var node = symbol.declarations[i]; - switch (node.kind) { - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 280 /* JSDocFunctionType */: - // Don't include signature if node is the implementation of an overloaded function. A node is considered - // an implementation node if it has a body and the previous node is of the same kind and immediately - // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). - if (i > 0 && node.body) { - var previous = symbol.declarations[i - 1]; - if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { - break; - } - } - result.push(getSignatureFromDeclaration(node)); + var decl = symbol.declarations[i]; + if (!ts.isFunctionLike(decl)) + continue; + // Don't include signature if node is the implementation of an overloaded function. A node is considered + // an implementation node if it has a body and the previous node is of the same kind and immediately + // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). + if (i > 0 && decl.body) { + var previous = symbol.declarations[i - 1]; + if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { + continue; + } } + result.push(getSignatureFromDeclaration(decl)); } return result; } @@ -31181,9 +35616,9 @@ var ts; signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate; } else { - var declaration = signature.declaration; - signature.resolvedTypePredicate = declaration && declaration.type && declaration.type.kind === 160 /* TypePredicate */ ? - createTypePredicateFromTypePredicateNode(declaration.type) : + var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration); + signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? + createTypePredicateFromTypePredicateNode(type) : noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); @@ -31193,7 +35628,7 @@ var ts; function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { - return unknownType; + return errorType; } var type = void 0; if (signature.target) { @@ -31226,16 +35661,16 @@ var ts; return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0; } function getRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { - var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); - if (ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType) { - return type.typeArguments[0]; - } - } - return anyType; + return tryGetRestTypeOfSignature(signature) || anyType; + } + function tryGetRestTypeOfSignature(signature) { + var type = getTypeOfRestParameter(signature); + return type && getIndexTypeOfType(type, 1 /* Number */); } function getSignatureInstantiation(signature, typeArguments, isJavascript) { - typeArguments = fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript); + return getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript)); + } + function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) { var instantiations = signature.instantiations || (signature.instantiations = ts.createMap()); var id = getTypeListId(typeArguments); var instantiation = instantiations.get(id); @@ -31288,7 +35723,7 @@ var ts; // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - var isConstructor = signature.declaration.kind === 154 /* Constructor */ || signature.declaration.kind === 158 /* ConstructSignature */; + var isConstructor = signature.declaration.kind === 155 /* Constructor */ || signature.declaration.kind === 159 /* ConstructSignature */; // TODO: GH#18217 var type = createObjectType(16 /* Anonymous */); type.members = emptySymbols; type.properties = ts.emptyArray; @@ -31307,10 +35742,10 @@ var ts; if (indexSymbol) { for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - var node = decl; + var node = ts.cast(decl, ts.isIndexSignatureDeclaration); if (node.parameters.length === 1) { var parameter = node.parameters[0]; - if (parameter && parameter.type && parameter.type.kind === syntaxKind) { + if (parameter.type && parameter.type.kind === syntaxKind) { return node; } } @@ -31329,44 +35764,54 @@ var ts; return undefined; } function getConstraintDeclaration(type) { - return type.symbol && ts.getDeclarationOfKind(type.symbol, 147 /* TypeParameter */).constraint; + var decl = type.symbol && ts.getDeclarationOfKind(type.symbol, 148 /* TypeParameter */); + return decl && decl.constraint; } function getInferredTypeParameterConstraint(typeParameter) { var inferences; if (typeParameter.symbol) { for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - // When an 'infer T' declaration is immediately contained in a type reference node - // (such as 'Foo'), T's constraint is inferred from the constraint of the - // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are - // present, we form an intersection of the inferred constraint types. - if (declaration.parent.kind === 171 /* InferType */ && declaration.parent.parent.kind === 161 /* TypeReference */) { - var typeReference = declaration.parent.parent; - var typeParameters = getTypeParametersForTypeReference(typeReference); - if (typeParameters) { - var index = typeReference.typeArguments.indexOf(declaration.parent); - if (index < typeParameters.length) { - var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); - if (declaredConstraint) { - // Type parameter constraints can reference other type parameters so - // constraints need to be instantiated. If instantiation produces the - // type parameter itself, we discard that inference. For example, in - // type Foo = [T, U]; - // type Bar = T extends Foo ? Foo : T; - // the instantiated constraint for U is X, so we discard that inference. - var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); - var constraint = instantiateType(declaredConstraint, mapper); - if (constraint !== typeParameter) { - inferences = ts.append(inferences, constraint); + if (declaration.parent.kind === 174 /* InferType */) { + // When an 'infer T' declaration is immediately contained in a type reference node + // (such as 'Foo'), T's constraint is inferred from the constraint of the + // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are + // present, we form an intersection of the inferred constraint types. + var grandParent = declaration.parent.parent; + if (grandParent.kind === 162 /* TypeReference */) { + var typeReference = grandParent; + var typeParameters = getTypeParametersForTypeReference(typeReference); + if (typeParameters) { + var index = typeReference.typeArguments.indexOf(declaration.parent); + if (index < typeParameters.length) { + var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); + if (declaredConstraint) { + // Type parameter constraints can reference other type parameters so + // constraints need to be instantiated. If instantiation produces the + // type parameter itself, we discard that inference. For example, in + // type Foo = [T, U]; + // type Bar = T extends Foo ? Foo : T; + // the instantiated constraint for U is X, so we discard that inference. + var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters)); + var constraint = instantiateType(declaredConstraint, mapper); + if (constraint !== typeParameter) { + inferences = ts.append(inferences, constraint); + } } } } } + // When an 'infer T' declaration is immediately contained in a rest parameter + // declaration, we infer an 'unknown[]' constraint. + else if (grandParent.kind === 149 /* Parameter */ && grandParent.dotDotDotToken) { + inferences = ts.append(inferences, createArrayType(unknownType)); + } } } } return inferences && getIntersectionType(inferences); } + /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */ function getConstraintFromTypeParameter(typeParameter) { if (!typeParameter.constraint) { if (typeParameter.target) { @@ -31382,7 +35827,7 @@ var ts; return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint; } function getParentSymbolOfTypeParameter(typeParameter) { - return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 147 /* TypeParameter */).parent); + return getSymbolOfNode(ts.getDeclarationOfKind(typeParameter.symbol, 148 /* TypeParameter */).parent); } function getTypeListId(types) { var result = ""; @@ -31419,7 +35864,7 @@ var ts; result |= type.flags; } } - return result & 117440512 /* PropagatingFlags */; + return result & 939524096 /* PropagatingFlags */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); @@ -31456,7 +35901,7 @@ var ts; var isJs = ts.isInJavaScriptFile(node); var isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { - var missingAugmentsTag = isJs && node.parent.kind !== 285 /* JSDocAugmentsTag */; + var missingAugmentsTag = isJs && node.parent.kind !== 293 /* JSDocAugmentsTag */; var diag = minTypeArgumentCount === typeParameters.length ? missingAugmentsTag ? ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag @@ -31468,7 +35913,7 @@ var ts; error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) - return unknownType; + return errorType; } } // In a type reference, the outer type parameters of the referenced class or interface are automatically @@ -31477,7 +35922,7 @@ var ts; var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgs, typeParameters, minTypeArgumentCount, isJs)); return createTypeReference(type, typeArguments); } - return checkNoTypeArguments(node, symbol) ? type : unknownType; + return checkNoTypeArguments(node, symbol) ? type : errorType; } function getTypeAliasInstantiation(symbol, typeArguments) { var type = getDeclaredTypeOfSymbol(symbol); @@ -31505,17 +35950,17 @@ var ts; error(node, minTypeArgumentCount === typeParameters.length ? ts.Diagnostics.Generic_type_0_requires_1_type_argument_s : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length); - return unknownType; + return errorType; } return getTypeAliasInstantiation(symbol, typeArguments); } - return checkNoTypeArguments(node, symbol) ? type : unknownType; + return checkNoTypeArguments(node, symbol) ? type : errorType; } function getTypeReferenceName(node) { switch (node.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // We only support expressions that are simple qualified names. For other // expressions this produces undefined. var expr = node.expression; @@ -31535,7 +35980,7 @@ var ts; function getTypeReferenceType(node, symbol) { var typeArguments = typeArgumentsFromTypeReferenceNode(node); // Do unconditionally so we mark type arguments as referenced. if (symbol === unknownSymbol) { - return unknownType; + return errorType; } var type = getTypeReferenceTypeWorker(node, symbol, typeArguments); if (type) { @@ -31545,27 +35990,42 @@ var ts; var res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & 32768 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : - unknownType; + res.flags & 65536 /* TypeParameter */ ? getConstrainedTypeVariable(res, node) : res : + errorType; } if (!(symbol.flags & 67216319 /* Value */ && isJSDocTypeReference(node))) { - return unknownType; + return errorType; } - // A jsdoc TypeReference may have resolved to a value (as opposed to a type). If - // the symbol is a constructor function, return the inferred class type; otherwise, - // the type of this reference is just the type of the value we resolved to. - var assignedType = getAssignedClassType(symbol); - var valueType = getTypeOfSymbol(symbol); - var referenceType = valueType.symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); - if (referenceType || assignedType) { - return referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType; + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; } // Resolve the type reference as a Type for the purpose of reporting errors. resolveTypeReferenceName(getTypeReferenceName(node), 67901928 /* Type */); - return valueType; + return getTypeOfSymbol(symbol); + } + /** + * A jsdoc TypeReference may have resolved to a value (as opposed to a type). If + * the symbol is a constructor function, return the inferred class type; otherwise, + * the type of this reference is just the type of the value we resolved to. + */ + function getJSDocTypeReference(node, symbol, typeArguments) { + var assignedType = getAssignedClassType(symbol); + var valueType = getTypeOfSymbol(symbol); + var referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (referenceType || assignedType) { + // TODO: GH#18217 (should the `|| assignedType` be at a lower precedence?) + return (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType); + } } function getTypeReferenceTypeWorker(node, symbol, typeArguments) { if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { + if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration.parent)) { + var jsdocType = getJSDocTypeReference(node, symbol, typeArguments); + if (jsdocType) { + return jsdocType; + } + } return getTypeFromClassOrInterfaceReference(node, symbol, typeArguments); } if (symbol.flags & 524288 /* TypeAlias */) { @@ -31578,13 +36038,13 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { - var result = createType(4194304 /* Substitution */); + var result = createType(8388608 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; return result; } function isUnaryTupleTypeNode(node) { - return node.kind === 167 /* TupleType */ && node.elementTypes.length === 1; + return node.kind === 168 /* TupleType */ && node.elementTypes.length === 1; } function getImpliedConstraint(typeVariable, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(typeVariable, checkNode.elementTypes[0], extendsNode.elementTypes[0]) : @@ -31593,9 +36053,9 @@ var ts; } function getConstrainedTypeVariable(typeVariable, node) { var constraints; - while (ts.isPartOfTypeNode(node)) { + while (node && !ts.isStatement(node) && node.kind !== 289 /* JSDocComment */) { var parent = node.parent; - if (parent.kind === 170 /* ConditionalType */ && node === parent.trueType) { + if (parent.kind === 173 /* ConditionalType */ && node === parent.trueType) { var constraint = getImpliedConstraint(typeVariable, parent.checkType, parent.extendsType); if (constraint) { constraints = ts.append(constraints, constraint); @@ -31606,11 +36066,11 @@ var ts; return constraints ? getSubstitutionType(typeVariable, getIntersectionType(ts.append(constraints, typeVariable))) : typeVariable; } function isJSDocTypeReference(node) { - return node.flags & 1048576 /* JSDoc */ && node.kind === 161 /* TypeReference */; + return !!(node.flags & 2097152 /* JSDoc */) && node.kind === 162 /* TypeReference */; } function checkNoTypeArguments(node, symbol) { if (node.typeArguments) { - error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : ts.declarationNameToString(node.typeName)); + error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : "(anonymous)"); return false; } return true; @@ -31653,7 +36113,7 @@ var ts; var indexed = getTypeFromTypeNode(typeArgs[0]); var target = getTypeFromTypeNode(typeArgs[1]); var index = createIndexInfo(target, /*isReadonly*/ false); - return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType && index, indexed === numberType && index); + return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined); } return anyType; } @@ -31664,7 +36124,7 @@ var ts; } function getTypeFromJSDocNullableTypeNode(node) { var type = getTypeFromTypeNode(node.type); - return strictNullChecks ? getNullableType(type, 8192 /* Null */) : type; + return strictNullChecks ? getNullableType(type, 16384 /* Null */) : type; } function getTypeFromTypeReference(node) { var links = getNodeLinks(node); @@ -31697,7 +36157,7 @@ var ts; // The expression is processed as an identifier expression (section 4.3) // or property access expression(section 4.10), // the widened type(section 3.9) of which becomes the result. - links.resolvedType = getWidenedType(checkExpression(node.exprName)); + links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName))); } return links.resolvedType; } @@ -31707,9 +36167,9 @@ var ts; for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { var declaration = declarations_3[_i]; switch (declaration.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: return declaration; } } @@ -31718,7 +36178,7 @@ var ts; return arity ? emptyGenericType : emptyObjectType; } var type = getDeclaredTypeOfSymbol(symbol); - if (!(type.flags & 65536 /* Object */)) { + if (!(type.flags & 131072 /* Object */)) { error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol)); return arity ? emptyGenericType : emptyObjectType; } @@ -31748,6 +36208,9 @@ var ts; function getGlobalTemplateStringsArrayType() { return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; } + function getGlobalImportMetaType() { + return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType; + } function getGlobalESSymbolConstructorSymbol(reportErrors) { return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors)); } @@ -31786,6 +36249,9 @@ var ts; var symbol = getGlobalSymbol(name, 67901928 /* Type */, /*diagnostic*/ undefined); return symbol && getTypeOfGlobalSymbol(symbol, arity); } + function getGlobalExtractSymbol() { + return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217 + } /** * Instantiates a global type that is generic with some element type, and returns that instantiation. */ @@ -31824,18 +36290,26 @@ var ts; // // Note that the generic type created by this function has no symbol associated with it. The same // is true for each of the synthesized type parameters. - function createTupleTypeOfArity(arity) { - var typeParameters = []; + function createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var typeParameters; var properties = []; - for (var i = 0; i < arity; i++) { - var typeParameter = createType(32768 /* TypeParameter */); - typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */, "" + i); - property.type = typeParameter; - properties.push(property); + var maxLength = hasRestElement ? arity - 1 : arity; + if (arity) { + typeParameters = new Array(arity); + for (var i = 0; i < arity; i++) { + var typeParameter = typeParameters[i] = createType(65536 /* TypeParameter */); + if (i < maxLength) { + var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); + property.type = typeParameter; + properties.push(property); + } + } } + var literalTypes = []; + for (var i = minLength; i <= maxLength; i++) + literalTypes.push(getLiteralType(i)); var lengthSymbol = createSymbol(4 /* Property */, "length"); - lengthSymbol.type = getLiteralType(arity); + lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes); properties.push(lengthSymbol); var type = createObjectType(8 /* Tuple */ | 4 /* Reference */); type.typeParameters = typeParameters; @@ -31845,7 +36319,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(32768 /* TypeParameter */); + type.thisType = createType(65536 /* TypeParameter */); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -31853,38 +36327,75 @@ var ts; type.declaredConstructSignatures = ts.emptyArray; type.declaredStringIndexInfo = undefined; type.declaredNumberIndexInfo = undefined; + type.minLength = minLength; + type.hasRestElement = hasRestElement; + type.associatedNames = associatedNames; return type; } - function getTupleTypeOfArity(arity) { - return tupleTypes[arity] || (tupleTypes[arity] = createTupleTypeOfArity(arity)); + function getTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames) { + var key = arity + (hasRestElement ? "+" : ",") + minLength + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : ""); + var type = tupleTypes.get(key); + if (!type) { + tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, associatedNames)); + } + return type; } - function createTupleType(elementTypes) { - return createTypeReference(getTupleTypeOfArity(elementTypes.length), elementTypes); + function createTupleType(elementTypes, minLength, hasRestElement, associatedNames) { + if (minLength === void 0) { minLength = elementTypes.length; } + if (hasRestElement === void 0) { hasRestElement = false; } + var arity = elementTypes.length; + if (arity === 1 && hasRestElement) { + return createArrayType(elementTypes[0]); + } + var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, associatedNames); + return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType; } function getTypeFromTupleTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = createTupleType(ts.map(node.elementTypes, getTypeFromTypeNode)); + var lastElement = ts.lastOrUndefined(node.elementTypes); + var restElement_1 = lastElement && lastElement.kind === 170 /* RestType */ ? lastElement : undefined; + var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 169 /* OptionalType */ && n !== restElement_1; }) + 1; + var elementTypes = ts.map(node.elementTypes, function (n) { + var type = getTypeFromTypeNode(n); + return n === restElement_1 && getIndexTypeOfType(type, 1 /* Number */) || type; + }); + links.resolvedType = createTupleType(elementTypes, minLength, !!restElement_1); } return links.resolvedType; } + function getTypeFromOptionalTypeNode(node) { + var type = getTypeFromTypeNode(node.type); + return strictNullChecks ? getOptionalType(type) : type; + } function getTypeId(type) { return type.id; } function containsType(types, type) { return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0; } - // Return true if the given intersection type contains (a) more than one unit type or (b) an object - // type and a nullable type (null or undefined). + // Return true if the given intersection type contains + // more than one unit type or, + // an object type and a nullable type (null or undefined), or + // a string-like type and a type known to be non-string-like, or + // a number-like type and a type known to be non-number-like, or + // a symbol-like type and a type known to be non-symbol-like, or + // a void-like type and a type known to be non-void-like, or + // a non-primitive type and a type known to be primitive. function isEmptyIntersectionType(type) { var combined = 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 13536 /* Unit */ && combined & 13536 /* Unit */) { + if (t.flags & 27072 /* Unit */ && combined & 27072 /* Unit */) { return true; } combined |= t.flags; - if (combined & 12288 /* Nullable */ && combined & (65536 /* Object */ | 134217728 /* NonPrimitive */)) { + if (combined & 24576 /* Nullable */ && combined & (131072 /* Object */ | 16777216 /* NonPrimitive */) || + combined & 16777216 /* NonPrimitive */ && combined & (16809468 /* DisjointDomains */ & ~16777216 /* NonPrimitive */) || + combined & 68 /* StringLike */ && combined & (16809468 /* DisjointDomains */ & ~68 /* StringLike */) || + combined & 168 /* NumberLike */ && combined & (16809468 /* DisjointDomains */ & ~168 /* NumberLike */) || + combined & 3072 /* ESSymbolLike */ && combined & (16809468 /* DisjointDomains */ & ~3072 /* ESSymbolLike */) || + combined & 12288 /* VoidLike */ && combined & (16809468 /* DisjointDomains */ & ~12288 /* VoidLike */)) { return true; } } @@ -31892,41 +36403,31 @@ var ts; } function addTypeToUnion(typeSet, includes, type) { var flags = type.flags; - if (flags & 131072 /* Union */) { - includes = addTypesToUnion(typeSet, includes, type.types); + if (flags & 262144 /* Union */) { + return addTypesToUnion(typeSet, includes, type.types); } - else if (flags & 1 /* Any */) { - includes |= 1 /* Any */; - if (type === wildcardType) - includes |= 4096 /* Wildcard */; - } - else if (!strictNullChecks && flags & 12288 /* Nullable */) { - if (flags & 4096 /* Undefined */) - includes |= 2 /* Undefined */; - if (flags & 8192 /* Null */) - includes |= 4 /* Null */; - if (!(flags & 16777216 /* ContainsWideningType */)) - includes |= 16 /* NonWideningType */; - } - else if (!(flags & 16384 /* Never */ || flags & 262144 /* Intersection */ && isEmptyIntersectionType(type))) { - // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are - // another form of 'never' (in that they have an empty value domain). We could in theory turn - // intersections of unit types into 'never' upon construction, but deferring the reduction makes it - // easier to reason about their origin. - if (flags & 2 /* String */) - includes |= 32 /* String */; - if (flags & 4 /* Number */) - includes |= 64 /* Number */; - if (flags & 512 /* ESSymbol */) - includes |= 128 /* ESSymbol */; - if (flags & 1120 /* StringOrNumberLiteralOrUnique */) - includes |= 256 /* LiteralOrUniqueESSymbol */; - var len = typeSet.length; - var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); - if (index < 0) { - if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); + // We ignore 'never' types in unions. Likewise, we ignore intersections of unit types as they are + // another form of 'never' (in that they have an empty value domain). We could in theory turn + // intersections of unit types into 'never' upon construction, but deferring the reduction makes it + // easier to reason about their origin. + if (!(flags & 32768 /* Never */ || flags & 524288 /* Intersection */ && isEmptyIntersectionType(type))) { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; + } + else if (!strictNullChecks && flags & 24576 /* Nullable */) { + if (!(flags & 134217728 /* ContainsWideningType */)) + includes |= 134217728 /* NonWideningType */; + } + else { + var len = typeSet.length; + var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues); + if (index < 0) { + if (!(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.splice(~index, 0, type); + } } } } @@ -31963,11 +36464,11 @@ var ts; } function isSetOfLiteralsFromSameEnum(types) { var first = types[0]; - if (first.flags & 256 /* EnumLiteral */) { + if (first.flags & 512 /* EnumLiteral */) { var firstEnum = getParentOfSymbol(first.symbol); for (var i = 1; i < types.length; i++) { var other = types[i]; - if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + if (!(other.flags & 512 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { return false; } } @@ -31992,10 +36493,10 @@ var ts; while (i > 0) { i--; var t = types[i]; - var remove = t.flags & 32 /* StringLiteral */ && includes & 32 /* String */ || - t.flags & 64 /* NumberLiteral */ && includes & 64 /* Number */ || - t.flags & 1024 /* UniqueESSymbol */ && includes & 128 /* ESSymbol */ || - t.flags & 96 /* StringOrNumberLiteral */ && t.flags & 8388608 /* FreshLiteral */ && containsType(types, t.regularType); + var remove = t.flags & 64 /* StringLiteral */ && includes & 4 /* String */ || + t.flags & 128 /* NumberLiteral */ && includes & 8 /* Number */ || + t.flags & 2048 /* UniqueESSymbol */ && includes & 1024 /* ESSymbol */ || + t.flags & 192 /* StringOrNumberLiteral */ && t.flags & 33554432 /* FreshLiteral */ && containsType(types, t.regularType); if (remove) { ts.orderedRemoveItemAt(types, i); } @@ -32018,12 +36519,12 @@ var ts; } var typeSet = []; var includes = addTypesToUnion(typeSet, 0, types); - if (includes & 1 /* Any */) { - return includes & 4096 /* Wildcard */ ? wildcardType : anyType; + if (includes & 3 /* AnyOrUnknown */) { + return includes & 1 /* Any */ ? includes & 268435456 /* Wildcard */ ? wildcardType : anyType : unknownType; } switch (unionReduction) { case 1 /* Literal */: - if (includes & 256 /* LiteralOrUniqueESSymbol */) { + if (includes & 2240 /* StringOrNumberLiteralOrUnique */) { removeRedundantLiteralTypes(typeSet, includes); } break; @@ -32032,11 +36533,11 @@ var ts; break; } if (typeSet.length === 0) { - return includes & 4 /* Null */ ? includes & 16 /* NonWideningType */ ? nullType : nullWideningType : - includes & 2 /* Undefined */ ? includes & 16 /* NonWideningType */ ? undefinedType : undefinedWideningType : + return includes & 16384 /* Null */ ? includes & 134217728 /* NonWideningType */ ? nullType : nullWideningType : + includes & 8192 /* Undefined */ ? includes & 134217728 /* NonWideningType */ ? undefinedType : undefinedWideningType : neverType; } - return getUnionTypeFromSortedList(typeSet, aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & 16749629 /* NotUnit */ ? 0 : 67108864 /* UnionOfUnitTypes */, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures) { var first; @@ -32073,7 +36574,7 @@ var ts; : !ts.isIdentifierTypePredicate(b); } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) { + function getUnionTypeFromSortedList(types, unionOfUnitTypes, aliasSymbol, aliasTypeArguments) { if (types.length === 0) { return neverType; } @@ -32083,8 +36584,8 @@ var ts; var id = getTypeListId(types); var type = unionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(131072 /* Union */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 24576 /* Nullable */); + type = createType(262144 /* Union */ | propagatedFlags | unionOfUnitTypes); unionTypes.set(id, type); type.types = types; /* @@ -32101,35 +36602,29 @@ var ts; function getTypeFromUnionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } function addTypeToIntersection(typeSet, includes, type) { var flags = type.flags; - if (flags & 262144 /* Intersection */) { - includes = addTypesToIntersection(typeSet, includes, type.types); + if (flags & 524288 /* Intersection */) { + return addTypesToIntersection(typeSet, includes, type.types); } - else if (flags & 1 /* Any */) { - includes |= 1 /* Any */; - if (type === wildcardType) - includes |= 4096 /* Wildcard */; + if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { + includes |= 536870912 /* EmptyObject */; } - else if (flags & 16384 /* Never */) { - includes |= 8 /* Never */; - } - else if (ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type)) { - includes |= 1024 /* EmptyObject */; - } - else if ((strictNullChecks || !(flags & 12288 /* Nullable */)) && !ts.contains(typeSet, type)) { - if (flags & 65536 /* Object */) { - includes |= 512 /* ObjectType */; + else { + includes |= flags & ~939524096 /* ConstructionFlags */; + if (flags & 3 /* AnyOrUnknown */) { + if (type === wildcardType) + includes |= 268435456 /* Wildcard */; } - if (flags & 131072 /* Union */) { - includes |= 2048 /* Union */; - } - if (!(flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */ && - type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & 24576 /* Nullable */)) && !ts.contains(typeSet, type) && + !(flags & 131072 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && + containsIdenticalType(typeSet, type))) { typeSet.push(type); } } @@ -32144,6 +36639,44 @@ var ts; } return includes; } + function removeRedundantPrimitiveTypes(types, includes) { + var i = types.length; + while (i > 0) { + i--; + var t = types[i]; + var remove = t.flags & 4 /* String */ && includes & 64 /* StringLiteral */ || + t.flags & 8 /* Number */ && includes & 128 /* NumberLiteral */ || + t.flags & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */; + if (remove) { + ts.orderedRemoveItemAt(types, i); + } + } + } + // When intersecting unions of unit types we can simply intersect based on type identity. + // Here we remove all unions of unit types from the given list and replace them with a + // a single union containing an intersection of the unit types. + function intersectUnionsOfUnitTypes(types) { + var unionIndex = ts.findIndex(types, function (t) { return (t.flags & 67108864 /* UnionOfUnitTypes */) !== 0; }); + var unionType = types[unionIndex]; + var intersection = unionType.types; + var i = types.length - 1; + var _loop_6 = function () { + var t = types[i]; + if (t.flags & 67108864 /* UnionOfUnitTypes */) { + intersection = ts.filter(intersection, function (u) { return containsType(t.types, u); }); + ts.orderedRemoveItemAt(types, i); + } + i--; + }; + while (i > unionIndex) { + _loop_6(); + } + if (intersection === unionType.types) { + return false; + } + types[unionIndex] = getUnionTypeFromSortedList(intersection, unionType.flags & 67108864 /* UnionOfUnitTypes */); + return true; + } // We normalize combinations of intersection and union types based on the distributive property of the '&' // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection // types with union type constituents into equivalent union types with intersection type constituents and @@ -32155,35 +36688,49 @@ var ts; // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution // for intersections of types with signatures can be deterministic. function getIntersectionType(types, aliasSymbol, aliasTypeArguments) { - if (types.length === 0) { - return emptyObjectType; - } var typeSet = []; var includes = addTypesToIntersection(typeSet, 0, types); - if (includes & 8 /* Never */) { + if (includes & 32768 /* Never */) { return neverType; } if (includes & 1 /* Any */) { - return includes & 4096 /* Wildcard */ ? wildcardType : anyType; + return includes & 268435456 /* Wildcard */ ? wildcardType : anyType; } - if (includes & 1024 /* EmptyObject */ && !(includes & 512 /* ObjectType */)) { + if (!strictNullChecks && includes & 24576 /* Nullable */) { + return includes & 8192 /* Undefined */ ? undefinedType : nullType; + } + if (includes & 4 /* String */ && includes & 64 /* StringLiteral */ || + includes & 8 /* Number */ && includes & 128 /* NumberLiteral */ || + includes & 1024 /* ESSymbol */ && includes & 2048 /* UniqueESSymbol */) { + removeRedundantPrimitiveTypes(typeSet, includes); + } + if (includes & 536870912 /* EmptyObject */ && !(includes & 131072 /* Object */)) { typeSet.push(emptyObjectType); } + if (typeSet.length === 0) { + return unknownType; + } if (typeSet.length === 1) { return typeSet[0]; } - if (includes & 2048 /* Union */) { + if (includes & 262144 /* Union */) { + if (includes & 67108864 /* UnionOfUnitTypes */ && intersectUnionsOfUnitTypes(typeSet)) { + // When the intersection creates a reduced set (which might mean that *all* union types have + // disappeared), we restart the operation to get a new set of combined flags. Once we have + // reduced we'll never reduce again, so this occurs at most once. + return getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + } // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain. - var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 131072 /* Union */) !== 0; }); + var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 262144 /* Union */) !== 0; }); var unionType = typeSet[unionIndex_1]; return getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments); } var id = getTypeListId(typeSet); var type = intersectionTypes.get(id); if (!type) { - var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 12288 /* Nullable */); - type = createType(262144 /* Intersection */ | propagatedFlags); + var propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ 24576 /* Nullable */); + type = createType(524288 /* Intersection */ | propagatedFlags); intersectionTypes.set(id, type); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. @@ -32194,46 +36741,67 @@ var ts; function getTypeFromIntersectionTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), getAliasSymbolForTypeNode(node), getAliasTypeArgumentsForTypeNode(node)); + var aliasSymbol = getAliasSymbolForTypeNode(node); + links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } - function getIndexTypeForGenericType(type) { - if (!type.resolvedIndexType) { - type.resolvedIndexType = createType(524288 /* Index */); - type.resolvedIndexType.type = type; - } - return type.resolvedIndexType; + function createIndexType(type, stringsOnly) { + var result = createType(1048576 /* Index */); + result.type = type; + result.stringsOnly = stringsOnly; + return result; } - function getLiteralTypeFromPropertyName(prop) { - var links = getSymbolLinks(getLateBoundSymbol(prop)); - if (!links.nameType) { - if (links.target && links.target !== unknownSymbol && links.target !== resolvingSymbol) { - ts.Debug.assert(links.target.escapedName === prop.escapedName || links.target.escapedName === "__computed" /* Computed */, "Target symbol and symbol do not have the same name"); - links.nameType = getLiteralTypeFromPropertyName(links.target); + function getIndexTypeForGenericType(type, stringsOnly) { + return stringsOnly ? + type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) : + type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false)); + } + function getLiteralTypeFromPropertyName(prop, include) { + if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { + var type = getLateBoundSymbol(prop).nameType; + if (!type && !ts.isKnownSymbol(prop)) { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && ts.isNumericLiteral(name) ? getLiteralType(+name.text) : + name && name.kind === 147 /* ComputedPropertyName */ && ts.isNumericLiteral(name.expression) ? getLiteralType(+name.expression.text) : + getLiteralType(ts.symbolName(prop)); } - else { - links.nameType = ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? - neverType : - getLiteralType(ts.symbolName(prop)); + if (type && type.flags & include) { + return type; } } - return links.nameType; + return neverType; } - function getLiteralTypeFromPropertyNames(type) { - return getUnionType(ts.map(getPropertiesOfType(type), getLiteralTypeFromPropertyName)); + function getLiteralTypeFromPropertyNames(type, include) { + return getUnionType(ts.map(getPropertiesOfType(type), function (t) { return getLiteralTypeFromPropertyName(t, include); })); } - function getIndexType(type) { - return type.flags & 262144 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t); })) : - maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type) : - ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : - type === wildcardType ? wildcardType : - type.flags & 1 /* Any */ || getIndexInfoOfType(type, 0 /* String */) ? stringType : - getLiteralTypeFromPropertyNames(type); + function getNonEnumNumberIndexInfo(type) { + var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */); + return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined; + } + function getIndexType(type, stringsOnly) { + if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; } + return type.flags & 262144 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + type.flags & 524288 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly); })) : + maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) : + ts.getObjectFlags(type) & 32 /* Mapped */ ? getConstraintTypeFromMappedType(type) : + type === wildcardType ? wildcardType : + type.flags & 1 /* Any */ ? keyofConstraintType : + stringsOnly ? getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */) : + getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromPropertyNames(type, 2048 /* UniqueESSymbol */)]) : + getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromPropertyNames(type, 64 /* StringLiteral */ | 2048 /* UniqueESSymbol */)]) : + getLiteralTypeFromPropertyNames(type, 2240 /* StringOrNumberLiteralOrUnique */); + } + function getExtractStringType(type) { + if (keyofStringsOnly) { + return type; + } + var extractTypeAlias = getGlobalExtractSymbol(); + return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType; } function getIndexTypeOrString(type) { - var indexType = getIndexType(type); - return indexType.flags & 16384 /* Never */ ? stringType : indexType; + var indexType = getExtractStringType(getIndexType(type)); + return indexType.flags & 32768 /* Never */ ? stringType : indexType; } function getTypeFromTypeOperatorNode(node) { var links = getNodeLinks(node); @@ -32245,20 +36813,20 @@ var ts; case 141 /* UniqueKeyword */: links.resolvedType = node.type.kind === 138 /* SymbolKeyword */ ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent)) - : unknownType; + : errorType; break; } } - return links.resolvedType; + return links.resolvedType; // TODO: GH#18217 } function createIndexedAccessType(objectType, indexType) { - var type = createType(1048576 /* IndexedAccess */); + var type = createType(2097152 /* IndexedAccess */); type.objectType = objectType; type.indexType = indexType; return type; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol) { - var accessExpression = accessNode && accessNode.kind === 184 /* ElementAccessExpression */ ? accessNode : undefined; + var accessExpression = accessNode && accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode : undefined; var propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : @@ -32270,7 +36838,7 @@ var ts; markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); - return unknownType; + return errorType; } if (cacheSymbol) { getNodeLinks(accessNode).resolvedSymbol = prop; @@ -32278,72 +36846,101 @@ var ts; } return getTypeOfSymbol(prop); } + if (isTupleType(objectType)) { + var restType = getRestTypeOfTupleType(objectType); + if (restType && isNumericLiteralName(propName) && +propName >= 0) { + return restType; + } + } } - if (!(indexType.flags & 12288 /* Nullable */) && isTypeAssignableToKind(indexType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */)) { + if (!(indexType.flags & 24576 /* Nullable */) && isTypeAssignableToKind(indexType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */)) { if (isTypeAny(objectType)) { return objectType; } - var indexInfo = isTypeAssignableToKind(indexType, 84 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || + var indexInfo = isTypeAssignableToKind(indexType, 168 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || getIndexInfoOfType(objectType, 0 /* String */) || undefined; if (indexInfo) { - if (accessExpression && indexInfo.isReadonly && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) { + if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + } + else 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 indexInfo.type; } + if (indexType.flags & 32768 /* Never */) { + return neverType; + } if (accessExpression && !isConstEnumObjectType(objectType)) { if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (getIndexTypeOfType(objectType, 1 /* Number */)) { error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number); } else { - error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + var suggestion = void 0; + if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) { + if (suggestion !== undefined) { + error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion); + } + } + else { + error(accessExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(objectType)); + } } } return anyType; } } if (accessNode) { - var indexNode = accessNode.kind === 184 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; - if (indexType.flags & (32 /* StringLiteral */ | 64 /* NumberLiteral */)) { + var indexNode = accessNode.kind === 188 /* ElementAccessExpression */ ? accessNode.argumentExpression : accessNode.indexType; + if (indexType.flags & (64 /* StringLiteral */ | 128 /* NumberLiteral */)) { error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } - else if (indexType.flags & (2 /* String */ | 4 /* Number */)) { + else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); } else { error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); } - return unknownType; } - return anyType; + return errorType; } function isGenericObjectType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */ | 536870912 /* GenericMappedType */); + return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 134217728 /* GenericMappedType */); } function isGenericIndexType(type) { - return maybeTypeOfKind(type, 7372800 /* InstantiableNonPrimitive */ | 524288 /* Index */); + return maybeTypeOfKind(type, 14745600 /* InstantiableNonPrimitive */ | 1048576 /* Index */); } // 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 & 65536 /* Object */ && !isGenericMappedType(type)) { + if (type.flags & 131072 /* Object */ && !isGenericMappedType(type)) { var t = resolveStructuredTypeMembers(type); return t.properties.length === 0 && t.callSignatures.length === 0 && t.constructSignatures.length === 0 && - t.stringIndexInfo && !t.numberIndexInfo; + !!t.stringIndexInfo && !t.numberIndexInfo; } return false; } function isMappedTypeToNever(type) { - return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedType(type) { + return type.flags & 2097152 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type) : type; } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return - // undefined if no transformation is possible. + // the type itself if no transformation is possible. function getSimplifiedIndexedAccessType(type) { - var objectType = type.objectType; - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType)) { + if (type.simplified) { + return type.simplified === circularConstraintType ? type : type.simplified; + } + type.simplified = circularConstraintType; + // We recursively simplify the object type as it may in turn be an indexed access type. For example, with + // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type. + var objectType = getSimplifiedType(type.objectType); + if (objectType.flags & 524288 /* Intersection */ && isGenericObjectType(objectType)) { // 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 @@ -32360,8 +36957,8 @@ var ts; regularTypes.push(t); } } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + return type.simplified = getUnionType([ + getSimplifiedType(getIndexedAccessType(getIntersectionType(regularTypes), type.indexType)), getIntersectionType(stringIndexTypes) ]); } @@ -32371,22 +36968,23 @@ var ts; // eventually anyway, but it easier to reason about. if (ts.some(objectType.types, isMappedTypeToNever)) { var nonNeverTypes = ts.filter(objectType.types, function (t) { return !isMappedTypeToNever(t); }); - return getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); + return type.simplified = getSimplifiedType(getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType)); } } // If the object type is a mapped type { [P in K]: E }, where K is generic, 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. + // construct the type Box. We do not further simplify the result because mapped types can be recursive + // and we might never terminate. if (isGenericMappedType(objectType)) { - return substituteIndexedMappedType(objectType, type); + return type.simplified = substituteIndexedMappedType(objectType, type); } - if (objectType.flags & 32768 /* TypeParameter */) { - var constraint = getConstraintFromTypeParameter(objectType); + if (objectType.flags & 65536 /* TypeParameter */) { + var constraint = getConstraintOfTypeParameter(objectType); if (constraint && isGenericMappedType(constraint)) { - return substituteIndexedMappedType(constraint, type); + return type.simplified = substituteIndexedMappedType(constraint, type); } } - return undefined; + return type.simplified = type; } function substituteIndexedMappedType(objectType, type) { var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); @@ -32402,8 +37000,8 @@ var ts; // 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 === 184 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { - if (objectType.flags & 1 /* Any */) { + if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 188 /* ElementAccessExpression */) && isGenericObjectType(objectType)) { + if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; } // Defer the operation by creating an indexed access type. @@ -32418,13 +37016,13 @@ var ts; // We treat boolean as different from other unions to improve errors; // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'. var apparentObjectType = getApparentType(objectType); - if (indexType.flags & 131072 /* Union */ && !(indexType.flags & 8 /* Boolean */)) { + if (indexType.flags & 262144 /* Union */ && !(indexType.flags & 16 /* Boolean */)) { var propTypes = []; for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) { var t = _a[_i]; var propType = getPropertyTypeForIndexType(apparentObjectType, t, accessNode, /*cacheSymbol*/ false); - if (propType === unknownType) { - return unknownType; + if (propType === errorType) { + return errorType; } propTypes.push(propType); } @@ -32438,7 +37036,7 @@ var ts; var objectType = getTypeFromTypeNode(node.objectType); var indexType = getTypeFromTypeNode(node.indexType); var resolved = getIndexedAccessType(objectType, indexType, node); - links.resolvedType = resolved.flags & 1048576 /* IndexedAccess */ && + links.resolvedType = resolved.flags & 2097152 /* IndexedAccess */ && resolved.objectType === objectType && resolved.indexType === indexType ? getConstrainedTypeVariable(resolved, node) : resolved; @@ -32451,7 +37049,7 @@ var ts; var type = createObjectType(32 /* Mapped */, node.symbol); type.declaration = node; type.aliasSymbol = getAliasSymbolForTypeNode(node); - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol); links.resolvedType = type; // Eagerly resolve the constraint type which forces an error if the constraint type circularly // references itself through one or more type aliases. @@ -32460,7 +37058,7 @@ var ts; return links.resolvedType; } function getActualTypeVariable(type) { - return type.flags & 4194304 /* Substitution */ ? type.typeVariable : type; + return type.flags & 8388608 /* Substitution */ ? type.typeVariable : type; } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); @@ -32471,15 +37069,21 @@ var ts; // If this is a distributive conditional type and the check type is generic we need to defer // resolution of the conditional type such that a later instantiation will properly distribute // over union types. - if (!root.isDistributive || !maybeTypeOfKind(checkType, 7897088 /* Instantiable */)) { - var combinedMapper = void 0; - if (root.inferTypeParameters) { - var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 15794176 /* Instantiable */); + var combinedMapper; + if (root.inferTypeParameters) { + var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); + if (!isDeferred) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. inferTypes(context.inferences, checkType, extendsType, 32 /* NoConstraints */ | 64 /* AlwaysStrict */); - combinedMapper = combineTypeMappers(mapper, context); + } + combinedMapper = combineTypeMappers(mapper, context); + } + if (!isDeferred) { + if (extendsType.flags & 3 /* AnyOrUnknown */) { + return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { @@ -32504,13 +37108,14 @@ var ts; } // Return a deferred type for a check that is neither definitely true nor definitely false var erasedCheckType = getActualTypeVariable(checkType); - var result = createType(2097152 /* Conditional */); + var result = createType(4194304 /* Conditional */); result.root = root; result.checkType = erasedCheckType; result.extendsType = extendsType; result.mapper = mapper; + result.combinedMapper = combinedMapper; result.aliasSymbol = root.aliasSymbol; - result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); + result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } function getTrueTypeFromConditionalType(type) { @@ -32530,24 +37135,39 @@ var ts; } return result; } + function isPossiblyReferencedInConditionalType(tp, node) { + if (isTypeParameterPossiblyReferenced(tp, node)) { + return true; + } + while (node) { + if (node.kind === 173 /* ConditionalType */) { + if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { + return true; + } + } + node = node.parent; + } + return false; + } function getTypeFromConditionalTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { var checkType = getTypeFromTypeNode(node.checkType); - var aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + var aliasSymbol = getAliasSymbolForTypeNode(node); + var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true); - var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); }); + var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isPossiblyReferencedInConditionalType(tp, node); }); var root = { node: node, checkType: checkType, extendsType: getTypeFromTypeNode(node.extendsType), trueType: getTypeFromTypeNode(node.trueType), falseType: getTypeFromTypeNode(node.falseType), - isDistributive: !!(checkType.flags & 32768 /* TypeParameter */), + isDistributive: !!(checkType.flags & 65536 /* TypeParameter */), inferTypeParameters: getInferTypeParameters(node), outerTypeParameters: outerTypeParameters, instantiations: undefined, - aliasSymbol: getAliasSymbolForTypeNode(node), + aliasSymbol: aliasSymbol, aliasTypeArguments: aliasTypeArguments }; links.resolvedType = getConditionalType(root, /*mapper*/ undefined); @@ -32565,6 +37185,78 @@ var ts; } return links.resolvedType; } + function getIdentifierChain(node) { + if (ts.isIdentifier(node)) { + return [node]; + } + else { + return ts.append(getIdentifierChain(node.left), node.right); + } + } + function getTypeFromImportTypeNode(node) { + var links = getNodeLinks(node); + if (!links.resolvedType) { + if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments + error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + if (!ts.isLiteralImportTypeNode(node)) { + error(node.argument, ts.Diagnostics.String_literal_expected); + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var targetMeaning = node.isTypeOf ? 67216319 /* Value */ : 67901928 /* Type */; + // TODO: Future work: support unions/generics/whatever via a deferred import-type + var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal); + if (!innerModuleSymbol) { + links.resolvedSymbol = unknownSymbol; + return links.resolvedType = errorType; + } + var moduleSymbol_1 = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false); + if (!ts.nodeIsMissing(node.qualifier)) { + var nameStack = getIdentifierChain(node.qualifier); + var currentNamespace = moduleSymbol_1; + var current = void 0; + while (current = nameStack.shift()) { + var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning; + var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning); + if (!next) { + error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current)); + return links.resolvedType = errorType; + } + getNodeLinks(current).resolvedSymbol = next; + getNodeLinks(current.parent).resolvedSymbol = next; + currentNamespace = next; + } + resolveImportSymbolType(node, links, currentNamespace, targetMeaning); + } + else { + if (moduleSymbol_1.flags & targetMeaning) { + resolveImportSymbolType(node, links, moduleSymbol_1, targetMeaning); + } + else { + var errorMessage = targetMeaning === 67216319 /* Value */ + ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here + : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0; + error(node, errorMessage, node.argument.literal.text); + links.resolvedSymbol = unknownSymbol; + links.resolvedType = errorType; + } + } + } + return links.resolvedType; // TODO: GH#18217 + } + function resolveImportSymbolType(node, links, symbol, meaning) { + var resolvedSymbol = resolveSymbol(symbol); + links.resolvedSymbol = resolvedSymbol; + if (meaning === 67216319 /* Value */) { + return links.resolvedType = getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias + } + else { + return links.resolvedType = getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol + } + } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) { var links = getNodeLinks(node); if (!links.resolvedType) { @@ -32576,7 +37268,7 @@ var ts; else { var type = createObjectType(16 /* Anonymous */, node.symbol); type.aliasSymbol = aliasSymbol; - type.aliasTypeArguments = getAliasTypeArgumentsForTypeNode(node); + type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol); if (ts.isJSDocTypeLiteral(node) && node.isArrayType) { type = createArrayType(type); } @@ -32586,10 +37278,9 @@ var ts; return links.resolvedType; } function getAliasSymbolForTypeNode(node) { - return node.parent.kind === 235 /* TypeAliasDeclaration */ ? getSymbolOfNode(node.parent) : undefined; + return ts.isTypeAlias(node.parent) ? getSymbolOfNode(node.parent) : undefined; } - function getAliasTypeArgumentsForTypeNode(node) { - var symbol = getAliasSymbolForTypeNode(node); + function getTypeArgumentsForAliasSymbol(symbol) { return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined; } /** @@ -32601,19 +37292,22 @@ var ts; if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) { return anyType; } - if (left.flags & 16384 /* Never */) { + if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) { + return unknownType; + } + if (left.flags & 32768 /* Never */) { return right; } - if (right.flags & 16384 /* Never */) { + if (right.flags & 32768 /* Never */) { return left; } - if (left.flags & 131072 /* Union */) { + if (left.flags & 262144 /* Union */) { return mapType(left, function (t) { return getSpreadType(t, right, symbol, typeFlags, objectFlags); }); } - if (right.flags & 131072 /* Union */) { + if (right.flags & 262144 /* Union */) { return mapType(right, function (t) { return getSpreadType(left, t, symbol, typeFlags, objectFlags); }); } - if (right.flags & (136 /* BooleanLike */ | 84 /* NumberLike */ | 524322 /* StringLike */ | 272 /* EnumLike */ | 134217728 /* NonPrimitive */)) { + if (right.flags & (272 /* BooleanLike */ | 168 /* NumberLike */ | 68 /* StringLike */ | 544 /* EnumLike */ | 16777216 /* NonPrimitive */ | 1048576 /* Index */)) { return left; } var members = ts.createSymbolTable(); @@ -32658,6 +37352,7 @@ var ts; result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; + result.nameType = leftProp.nameType; members.set(leftProp.escapedName, result); } } @@ -32666,7 +37361,7 @@ var ts; } } var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getNonReadonlyIndexSignature(stringIndexInfo), getNonReadonlyIndexSignature(numberIndexInfo)); - spread.flags |= typeFlags | 33554432 /* ContainsObjectLiteral */; + spread.flags |= typeFlags | 268435456 /* ContainsObjectLiteral */; spread.objectFlags |= objectFlags | (128 /* ObjectLiteral */ | 1024 /* ContainsSpread */); return spread; } @@ -32678,6 +37373,7 @@ var ts; var result = createSymbol(flags, prop.escapedName); result.type = getTypeOfSymbol(prop); result.declarations = prop.declarations; + result.nameType = prop.nameType; result.syntheticOrigin = prop; return result; } @@ -32697,9 +37393,9 @@ var ts; return type; } function getFreshTypeOfLiteralType(type) { - if (type.flags & 96 /* StringOrNumberLiteral */ && !(type.flags & 8388608 /* FreshLiteral */)) { + if (type.flags & 192 /* StringOrNumberLiteral */ && !(type.flags & 33554432 /* FreshLiteral */)) { if (!type.freshType) { - var freshType = createLiteralType(type.flags | 8388608 /* FreshLiteral */, type.value, type.symbol); + var freshType = createLiteralType(type.flags | 33554432 /* FreshLiteral */, type.value, type.symbol); freshType.regularType = type; type.freshType = freshType; } @@ -32708,7 +37404,9 @@ var ts; return type; } function getRegularTypeOfLiteralType(type) { - return type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? type.regularType : type; + return type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? type.regularType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)) : + type; } function getLiteralType(value, enumId, symbol) { // We store all literal types in a single map with keys of the form '#NNN' and '@SSS', @@ -32719,7 +37417,7 @@ var ts; var key = enumId ? enumId + qualifier + value : qualifier + value; var type = literalTypes.get(key); if (!type) { - var flags = (typeof value === "number" ? 64 /* NumberLiteral */ : 32 /* StringLiteral */) | (enumId ? 256 /* EnumLiteral */ : 0); + var flags = (typeof value === "number" ? 128 /* NumberLiteral */ : 64 /* StringLiteral */) | (enumId ? 512 /* EnumLiteral */ : 0); literalTypes.set(key, type = createLiteralType(flags, value, symbol)); } return type; @@ -32732,7 +37430,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(1024 /* UniqueESSymbol */); + var type = createType(2048 /* UniqueESSymbol */); type.symbol = symbol; return type; } @@ -32747,14 +37445,14 @@ var ts; function getThisType(node) { var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; - if (parent && (ts.isClassLike(parent) || parent.kind === 234 /* InterfaceDeclaration */)) { + if (parent && (ts.isClassLike(parent) || parent.kind === 239 /* InterfaceDeclaration */)) { if (!ts.hasModifier(container, 32 /* Static */) && - (container.kind !== 154 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { + (container.kind !== 155 /* Constructor */ || ts.isNodeDescendantOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface); - return unknownType; + return errorType; } function getTypeFromThisTypeNode(node) { var links = getNodeLinks(node); @@ -32766,9 +37464,11 @@ var ts; function getTypeFromTypeNode(node) { switch (node.kind) { case 119 /* AnyKeyword */: - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return anyType; + case 142 /* UnknownKeyword */: + return unknownType; case 137 /* StringKeyword */: return stringType; case 134 /* NumberKeyword */: @@ -32787,61 +37487,67 @@ var ts; return neverType; case 135 /* ObjectKeyword */: return node.flags & 65536 /* JavaScriptFile */ ? anyType : nonPrimitiveType; - case 173 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: return getTypeFromThisTypeNode(node); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return getTypeFromLiteralTypeNode(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return getTypeFromTypeReference(node); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return booleanType; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return getTypeFromTypeReference(node); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return getTypeFromTypeQueryNode(node); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return getTypeFromArrayTypeNode(node); - case 167 /* TupleType */: + case 168 /* TupleType */: return getTypeFromTupleTypeNode(node); - case 168 /* UnionType */: + case 169 /* OptionalType */: + return getTypeFromOptionalTypeNode(node); + case 171 /* UnionType */: return getTypeFromUnionTypeNode(node); - case 169 /* IntersectionType */: + case 172 /* IntersectionType */: return getTypeFromIntersectionTypeNode(node); - case 277 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return getTypeFromJSDocNullableTypeNode(node); - case 279 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return addOptionality(getTypeFromTypeNode(node.type)); - case 172 /* ParenthesizedType */: - case 278 /* JSDocNonNullableType */: - case 274 /* JSDocTypeExpression */: + case 175 /* ParenthesizedType */: + case 170 /* RestType */: + case 285 /* JSDocNonNullableType */: + case 281 /* JSDocTypeExpression */: return getTypeFromTypeNode(node.type); - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return getTypeFromJSDocVariadicType(node); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 165 /* TypeLiteral */: - case 283 /* JSDocTypeLiteral */: - case 280 /* JSDocFunctionType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 166 /* TypeLiteral */: + case 290 /* JSDocTypeLiteral */: + case 287 /* JSDocFunctionType */: + case 291 /* JSDocSignature */: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return getTypeFromTypeOperatorNode(node); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return getTypeFromIndexedAccessTypeNode(node); - case 176 /* MappedType */: + case 179 /* MappedType */: return getTypeFromMappedTypeNode(node); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return getTypeFromConditionalTypeNode(node); - case 171 /* InferType */: + case 174 /* InferType */: return getTypeFromInferTypeNode(node); + case 181 /* ImportType */: + return getTypeFromImportTypeNode(node); // This function assumes that an identifier or qualified name is a type expression // Callers should first ensure this by calling isTypeNode case 71 /* Identifier */: - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return (symbol && getDeclaredTypeOfSymbol(symbol)); // TODO: GH#18217 default: - return unknownType; + return errorType; } } function instantiateList(items, mapper, instantiator) { @@ -32918,10 +37624,10 @@ var ts; return function (t) { return t === source ? target : baseMapper(t); }; } function wildcardMapper(type) { - return type.flags & 32768 /* TypeParameter */ ? wildcardType : type; + return type.flags & 65536 /* TypeParameter */ ? wildcardType : type; } function cloneTypeParameter(typeParameter) { - var result = createType(32768 /* TypeParameter */); + var result = createType(65536 /* TypeParameter */); result.symbol = typeParameter.symbol; result.target = typeParameter; return result; @@ -32967,7 +37673,7 @@ var ts; } function instantiateSymbol(symbol, mapper) { var links = getSymbolLinks(symbol); - if (links.type && !maybeTypeOfKind(links.type, 65536 /* Object */ | 7897088 /* Instantiable */)) { + if (links.type && !maybeTypeOfKind(links.type, 131072 /* Object */ | 15794176 /* Instantiable */)) { // If the type of the symbol is already resolved, and if that type could not possibly // be affected by instantiation, simply return the symbol itself. return symbol; @@ -32981,7 +37687,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -32989,8 +37695,8 @@ var ts; if (symbol.valueDeclaration) { result.valueDeclaration = symbol.valueDeclaration; } - if (symbol.isRestParameter) { - result.isRestParameter = symbol.isRestParameter; + if (symbol.nameType) { + result.nameType = symbol.nameType; } return result; } @@ -33005,10 +37711,24 @@ var ts; // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. var declaration_1 = symbol.declarations[0]; - var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true) || ts.emptyArray; + if (ts.isInJavaScriptFile(declaration_1)) { + var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag); + if (paramTag) { + var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag); + if (paramSymbol) { + declaration_1 = paramSymbol.valueDeclaration; + } + } + } + var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true); + if (isJavaScriptConstructor(declaration_1)) { + var templateTagParameters = getTypeParametersFromDeclaration(declaration_1); + outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters); + } + typeParameters = outerTypeParameters || ts.emptyArray; typeParameters = symbol.flags & 2048 /* TypeLiteral */ && !target.aliasTypeArguments ? - ts.filter(outerTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : - outerTypeParameters; + ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) : + typeParameters; links.outerTypeParameters = typeParameters; if (typeParameters.length) { links.instantiations = ts.createMap(); @@ -33032,27 +37752,32 @@ var ts; } return type; } + function maybeTypeParameterReference(node) { + return !(node.kind === 146 /* QualifiedName */ || + node.parent.kind === 162 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName); + } function isTypeParameterPossiblyReferenced(tp, node) { // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks // between the node and the type parameter declaration, if the node contains actual references to the // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced. if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { - var container_2 = tp.symbol.declarations[0].parent; - if (ts.findAncestor(node, function (n) { return n.kind === 211 /* Block */ ? "quit" : n === container_2; })) { - return ts.forEachChild(node, containsReference); + var container_3 = tp.symbol.declarations[0].parent; + if (ts.findAncestor(node, function (n) { return n.kind === 216 /* Block */ ? "quit" : n === container_3; })) { + return !!ts.forEachChild(node, containsReference); } } return true; function containsReference(node) { switch (node.kind) { - case 173 /* ThisType */: - return tp.isThisType; + case 176 /* ThisType */: + return !!tp.isThisType; case 71 /* Identifier */: - return !tp.isThisType && ts.isPartOfTypeNode(node) && getTypeFromTypeNode(node) === tp; - case 164 /* TypeQuery */: + return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) && + getTypeFromTypeNode(node) === tp; + case 165 /* TypeQuery */: return true; } - return ts.forEachChild(node, containsReference); + return !!ts.forEachChild(node, containsReference); } } function instantiateMappedType(type, mapper) { @@ -33062,9 +37787,9 @@ var ts; // homomorphic mapped types we leave primitive types alone. For example, when T is instantiated to a // union type A | undefined, we produce { [P in keyof A]: X } | undefined. var constraintType = getConstraintTypeFromMappedType(type); - if (constraintType.flags & 524288 /* Index */) { + if (constraintType.flags & 1048576 /* Index */) { var typeVariable_1 = constraintType.type; - if (typeVariable_1.flags & 32768 /* TypeParameter */) { + if (typeVariable_1.flags & 65536 /* TypeParameter */) { var mappedTypeVariable = instantiateType(typeVariable_1, mapper); if (typeVariable_1 !== mappedTypeVariable) { return mapType(mappedTypeVariable, function (t) { @@ -33079,7 +37804,7 @@ var ts; return instantiateAnonymousType(type, mapper); } function isMappableType(type) { - return type.flags & (1 /* Any */ | 7372800 /* InstantiableNonPrimitive */ | 65536 /* Object */ | 262144 /* Intersection */); + return type.flags & (3 /* AnyOrUnknown */ | 14745600 /* InstantiableNonPrimitive */ | 131072 /* Object */ | 524288 /* Intersection */); } function instantiateAnonymousType(type, mapper) { var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol); @@ -33117,7 +37842,7 @@ var ts; if (root.isDistributive) { var checkType_1 = root.checkType; var instantiatedType = mapper(checkType_1); - if (checkType_1 !== instantiatedType && instantiatedType.flags & (131072 /* Union */ | 16384 /* Never */)) { + if (checkType_1 !== instantiatedType && instantiatedType.flags & (262144 /* Union */ | 32768 /* Never */)) { return mapType(instantiatedType, function (t) { return getConditionalType(root, createReplacementMapper(checkType_1, t, mapper)); }); } } @@ -33125,10 +37850,10 @@ var ts; } function instantiateType(type, mapper) { if (type && mapper && mapper !== identityMapper) { - if (type.flags & 32768 /* TypeParameter */) { + if (type.flags & 65536 /* TypeParameter */) { return mapper(type); } - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { if (type.objectFlags & 16 /* Anonymous */) { // If the anonymous type originates in a declaration of a function, method, class, or // interface, in an object type literal, or in an object literal expression, we may need @@ -33145,33 +37870,33 @@ var ts; return newTypeArguments !== typeArguments ? createTypeReference(type.target, newTypeArguments) : type; } } - if (type.flags & 131072 /* Union */ && !(type.flags & 16382 /* Primitive */)) { + if (type.flags & 262144 /* Union */ && !(type.flags & 32764 /* Primitive */)) { var types = type.types; var newTypes = instantiateTypes(types, mapper); return newTypes !== types ? getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; } - if (type.flags & 262144 /* Intersection */) { + if (type.flags & 524288 /* Intersection */) { var types = type.types; var newTypes = instantiateTypes(types, mapper); return newTypes !== types ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) : type; } - if (type.flags & 524288 /* Index */) { + if (type.flags & 1048576 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); } - if (type.flags & 1048576 /* IndexedAccess */) { + if (type.flags & 2097152 /* IndexedAccess */) { return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper)); } - if (type.flags & 2097152 /* Conditional */) { + if (type.flags & 4194304 /* Conditional */) { return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper)); } - if (type.flags & 4194304 /* Substitution */) { + if (type.flags & 8388608 /* Substitution */) { return instantiateType(type.typeVariable, mapper); } } return type; } function getWildcardInstantiation(type) { - return type.flags & (16382 /* Primitive */ | 1 /* Any */ | 16384 /* Never */) ? type : + return type.flags & (32764 /* Primitive */ | 3 /* AnyOrUnknown */ | 32768 /* Never */) ? type : type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); } function instantiateIndexInfo(info, mapper) { @@ -33180,34 +37905,38 @@ var ts; // Returns true if the given expression contains (at any level of nesting) a function or arrow expression // that is subject to contextual typing. function isContextSensitive(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: return isContextSensitiveFunctionLikeDeclaration(node); - case 182 /* ObjectLiteralExpression */: - return ts.forEach(node.properties, isContextSensitive); - case 181 /* ArrayLiteralExpression */: - return ts.forEach(node.elements, isContextSensitive); - case 199 /* ConditionalExpression */: + case 186 /* ObjectLiteralExpression */: + return ts.some(node.properties, isContextSensitive); + case 185 /* ArrayLiteralExpression */: + return ts.some(node.elements, isContextSensitive); + case 203 /* ConditionalExpression */: return isContextSensitive(node.whenTrue) || isContextSensitive(node.whenFalse); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return node.operatorToken.kind === 54 /* BarBarToken */ && (isContextSensitive(node.left) || isContextSensitive(node.right)); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return isContextSensitive(node.initializer); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isContextSensitive(node.expression); - case 261 /* JsxAttributes */: - return ts.forEach(node.properties, isContextSensitive); - case 260 /* JsxAttribute */: + case 266 /* JsxAttributes */: + return ts.some(node.properties, isContextSensitive); + case 265 /* JsxAttribute */: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - return node.initializer && isContextSensitive(node.initializer); - case 263 /* JsxExpression */: + var initializer = node.initializer; + return !!initializer && isContextSensitive(initializer); + } + case 268 /* JsxExpression */: { // It is possible to that node.expression is undefined (e.g
) - return node.expression && isContextSensitive(node.expression); + var expression = node.expression; + return !!expression && isContextSensitive(expression); + } } return false; } @@ -33217,10 +37946,10 @@ var ts; return false; } // Functions with any parameters that lack type annotations are context sensitive. - if (ts.forEach(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { + if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) { return true; } - if (node.kind !== 191 /* ArrowFunction */) { + if (node.kind !== 195 /* 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); @@ -33229,13 +37958,15 @@ var ts; } } // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - return node.body.kind === 211 /* Block */ ? false : isContextSensitive(node.body); + var body = node.body; + return body.kind === 216 /* Block */ ? false : isContextSensitive(body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { - return (isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); + return (ts.isInJavaScriptFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && + isContextSensitiveFunctionLikeDeclaration(func); } function getTypeWithoutSignatures(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { var result = createObjectType(16 /* Anonymous */, type.symbol); @@ -33246,7 +37977,7 @@ var ts; return result; } } - else if (type.flags & 262144 /* Intersection */) { + else if (type.flags & 524288 /* Intersection */) { return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures)); } return type; @@ -33276,9 +38007,9 @@ var ts; // Note that this check ignores type parameters and only considers the // inheritance hierarchy. function isTypeDerivedFrom(source, target) { - return source.flags & 131072 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : - target.flags & 131072 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : - source.flags & 7372800 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : + return source.flags & 262144 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) : + target.flags & 262144 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) : + source.flags & 14745600 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || emptyObjectType, target) : target === globalObjectType || target === globalFunctionType ? isTypeSubtypeOf(source, target) : hasBaseType(source, getTargetType(target)); } @@ -33298,8 +38029,206 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject); + } + /** + * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to + * attempt to issue more specific errors on, for example, specific object literal properties or tuple members. + */ + function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) { + if (isTypeAssignableTo(source, target)) + return true; + if (!elaborateError(expr, source, target)) { + return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); + } + return false; + } + function elaborateError(node, source, target) { + if (!node) + return false; + switch (node.kind) { + case 268 /* JsxExpression */: + case 193 /* ParenthesizedExpression */: + return elaborateError(node.expression, source, target); + case 202 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 58 /* EqualsToken */: + case 26 /* CommaToken */: + return elaborateError(node.right, source, target); + } + break; + case 186 /* ObjectLiteralExpression */: + return elaborateObjectLiteral(node, source, target); + case 185 /* ArrayLiteralExpression */: + return elaborateArrayLiteral(node, source, target); + case 266 /* JsxAttributes */: + return elaborateJsxAttributes(node, source, target); + } + return false; + } + /** + * For every element returned from the iterator, checks that element to issue an error on a property of that element's type + * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` + * Otherwise, we issue an error on _every_ element which fail the assignability check + */ + function elaborateElementwise(iterator, source, target) { + // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span + var reportedError = false; + for (var status = iterator.next(); !status.done; status = iterator.next()) { + var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage; + var sourcePropType = getIndexedAccessType(source, nameType); + var targetPropType = getIndexedAccessType(target, nameType); + if (!isTypeAssignableTo(sourcePropType, targetPropType)) { + var elaborated = next && elaborateError(next, sourcePropType, targetPropType); + if (elaborated) { + reportedError = true; + } + else { + // Issue error on the prop itself, since the prop couldn't elaborate the error + var resultObj = {}; + // Use the expression type, if available + var specificSource = next ? checkExpressionForMutableLocation(next, 0 /* Normal */, sourcePropType) : sourcePropType; + var result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + if (result && specificSource !== sourcePropType) { + // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType + checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + } + if (resultObj.error) { + var reportedDiag = resultObj.error; + var propertyName = isTypeUsableAsLateBoundName(nameType) ? getLateBoundNameFromType(nameType) : undefined; + var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined; + var issuedElaboration = false; + if (!targetProp) { + var indexInfo = isTypeAssignableToKind(nameType, 168 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) || + getIndexInfoOfType(target, 0 /* String */) || + undefined; + if (indexInfo && indexInfo.declaration) { + issuedElaboration = true; + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature)); + } + } + if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) { + addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0], ts.Diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName && !(nameType.flags & 2048 /* UniqueESSymbol */) ? ts.unescapeLeadingUnderscores(propertyName) : typeToString(nameType), typeToString(target))); + } + } + reportedError = true; + } + } + } + return reportedError; + } + function generateJsxAttributes(node) { + var _i, _a, prop; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + prop = _a[_i]; + if (ts.isJsxSpreadAttribute(prop)) + return [3 /*break*/, 3]; + return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }]; + case 2: + _b.sent(); + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateJsxAttributes(node, source, target) { + return elaborateElementwise(generateJsxAttributes(node), source, target); + } + function generateLimitedTupleElements(node, target) { + var len, i, elem, nameType; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + len = ts.length(node.elements); + if (!len) + return [2 /*return*/]; + i = 0; + _a.label = 1; + case 1: + if (!(i < len)) return [3 /*break*/, 4]; + // Skip elements which do not exist in the target - a length error on the tuple overall is likely better than an error on a mismatched index signature + if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i))) + return [3 /*break*/, 3]; + elem = node.elements[i]; + if (ts.isOmittedExpression(elem)) + return [3 /*break*/, 3]; + nameType = getLiteralType(i); + return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/]; + } + }); + } + function elaborateArrayLiteral(node, source, target) { + if (isTupleLikeType(source)) { + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + } + return false; + } + function generateObjectLiteralElements(node) { + var _i, _a, prop, type, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!ts.length(node.properties)) + return [2 /*return*/]; + _i = 0, _a = node.properties; + _c.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 8]; + prop = _a[_i]; + if (ts.isSpreadAssignment(prop)) + return [3 /*break*/, 7]; + type = getLiteralTypeFromPropertyName(getSymbolOfNode(prop), 2240 /* StringOrNumberLiteralOrUnique */); + if (!type || (type.flags & 32768 /* Never */)) { + return [3 /*break*/, 7]; + } + _b = prop.kind; + switch (_b) { + case 157 /* SetAccessor */: return [3 /*break*/, 2]; + case 156 /* GetAccessor */: return [3 /*break*/, 2]; + case 154 /* MethodDeclaration */: return [3 /*break*/, 2]; + case 274 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2]; + case 273 /* PropertyAssignment */: return [3 /*break*/, 4]; + } + return [3 /*break*/, 6]; + case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }]; + case 3: + _c.sent(); + return [3 /*break*/, 7]; + case 4: return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: type, errorMessage: isComputedNonLiteralName(prop.name) ? ts.Diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1 : undefined }]; + case 5: + _c.sent(); + return [3 /*break*/, 7]; + case 6: + ts.Debug.assertNever(prop); + _c.label = 7; + case 7: + _i++; + return [3 /*break*/, 1]; + case 8: return [2 /*return*/]; + } + }); + } + function elaborateObjectLiteral(node, source, target) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target); } /** * This is *not* a bi-directional relationship. @@ -33320,16 +38249,23 @@ var ts; if (source === target) { return -1 /* True */; } - if (!target.hasRestParameter && source.minArgumentCount > target.parameters.length) { + var targetCount = getParameterCount(target); + if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; } if (source.typeParameters && source.typeParameters !== target.typeParameters) { target = getCanonicalSignature(target); source = instantiateSignatureInContextOf(source, target, /*contextualMapper*/ undefined, compareTypes); } + var sourceCount = getParameterCount(source); + var sourceGenericRestType = getGenericRestType(source); + var targetGenericRestType = sourceGenericRestType ? getGenericRestType(target) : undefined; + if (sourceGenericRestType && !(targetGenericRestType && sourceCount === targetCount)) { + return 0 /* False */; + } var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; - var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 153 /* MethodDeclaration */ && - kind !== 152 /* MethodSignature */ && kind !== 154 /* Constructor */; + var strictVariance = !callbackCheck && strictFunctionTypes && kind !== 154 /* MethodDeclaration */ && + kind !== 153 /* MethodSignature */ && kind !== 155 /* Constructor */; var result = -1 /* True */; var sourceThisType = getThisTypeOfSignature(source); if (sourceThisType && sourceThisType !== voidType) { @@ -33347,14 +38283,11 @@ var ts; result &= related; } } - var sourceMax = getNumNonRestParameters(source); - var targetMax = getNumNonRestParameters(target); - var checkCount = getNumParametersToCheckForSignatureRelatability(source, sourceMax, target, targetMax); - var sourceParams = source.parameters; - var targetParams = target.parameters; - for (var i = 0; i < checkCount; i++) { - var sourceType = i < sourceMax ? getTypeOfParameter(sourceParams[i]) : getRestTypeOfSignature(source); - var targetType = i < targetMax ? getTypeOfParameter(targetParams[i]) : getRestTypeOfSignature(target); + var paramCount = Math.max(sourceCount, targetCount); + var lastIndex = paramCount - 1; + for (var i = 0; i < paramCount; i++) { + var sourceType = i === lastIndex && sourceGenericRestType || getTypeAtPosition(source, i); + var targetType = i === lastIndex && targetGenericRestType || getTypeAtPosition(target, i); // In order to ensure that any generic type Foo is at least co-variant with respect to T no matter // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions, // they naturally relate only contra-variantly). However, if the source and target parameters both have @@ -33366,13 +38299,14 @@ var ts; var sourceSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(sourceType)); var targetSig = callbackCheck ? undefined : getSingleCallSignature(getNonNullableType(targetType)); var callbacks = sourceSig && targetSig && !signatureHasTypePredicate(sourceSig) && !signatureHasTypePredicate(targetSig) && - (getFalsyFlags(sourceType) & 12288 /* Nullable */) === (getFalsyFlags(targetType) & 12288 /* Nullable */); + (getFalsyFlags(sourceType) & 24576 /* Nullable */) === (getFalsyFlags(targetType) & 24576 /* Nullable */); var related = callbacks ? + // TODO: GH#18217 It will work if they're both `undefined`, but not if only one is compareSignaturesRelated(targetSig, sourceSig, strictVariance ? 2 /* Strict */ : 1 /* Bivariant */, /*ignoreReturnTypes*/ false, reportErrors, errorReporter, compareTypes) : !callbackCheck && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors); if (!related) { if (reportErrors) { - errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.symbolName(sourceParams[i < sourceMax ? i : sourceMax]), ts.symbolName(targetParams[i < targetMax ? i : targetMax])); + errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i))); } return 0 /* False */; } @@ -33389,7 +38323,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -33447,30 +38381,6 @@ var ts; } return false; } - function getNumNonRestParameters(signature) { - var numParams = signature.parameters.length; - return signature.hasRestParameter ? - numParams - 1 : - numParams; - } - function getNumParametersToCheckForSignatureRelatability(source, sourceNonRestParamCount, target, targetNonRestParamCount) { - if (source.hasRestParameter === target.hasRestParameter) { - if (source.hasRestParameter) { - // If both have rest parameters, get the max and add 1 to - // compensate for the rest parameter. - return Math.max(sourceNonRestParamCount, targetNonRestParamCount) + 1; - } - else { - return Math.min(sourceNonRestParamCount, targetNonRestParamCount); - } - } - else { - // Return the count for whichever signature doesn't have rest parameters. - return source.hasRestParameter ? - targetNonRestParamCount : - sourceNonRestParamCount; - } - } function isEmptyResolvedType(t) { return t.properties.length === 0 && t.callSignatures.length === 0 && @@ -33479,10 +38389,10 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 65536 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : - type.flags & 134217728 /* NonPrimitive */ ? true : - type.flags & 131072 /* Union */ ? ts.forEach(type.types, isEmptyObjectType) : - type.flags & 262144 /* Intersection */ ? !ts.forEach(type.types, function (t) { return !isEmptyObjectType(t); }) : + return type.flags & 131072 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + type.flags & 16777216 /* NonPrimitive */ ? true : + type.flags & 262144 /* Union */ ? ts.some(type.types, isEmptyObjectType) : + type.flags & 524288 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : false; } function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) { @@ -33491,11 +38401,11 @@ var ts; } var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); var relation = enumRelation.get(id); - if (relation !== undefined) { - return relation; + if (relation !== undefined && !(relation === 2 /* Failed */ && errorReporter)) { + return relation === 1 /* Succeeded */; } if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) { - enumRelation.set(id, false); + enumRelation.set(id, 3 /* FailedAndReported */); return false; } var targetEnumType = getTypeOfSymbol(targetSymbol); @@ -33506,55 +38416,58 @@ var ts; if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); + enumRelation.set(id, 3 /* FailedAndReported */); + } + else { + enumRelation.set(id, 2 /* Failed */); } - enumRelation.set(id, false); return false; } } } - enumRelation.set(id, true); + enumRelation.set(id, 1 /* Succeeded */); return true; } function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { var s = source.flags; var t = target.flags; - if (t & 1 /* Any */ || s & 16384 /* Never */ || source === wildcardType) + if (t & 3 /* AnyOrUnknown */ || s & 32768 /* Never */ || source === wildcardType) return true; - if (t & 16384 /* Never */) + if (t & 32768 /* Never */) return false; - if (s & 524322 /* StringLike */ && t & 2 /* String */) + if (s & 68 /* StringLike */ && t & 4 /* String */) return true; - if (s & 32 /* StringLiteral */ && s & 256 /* EnumLiteral */ && - t & 32 /* StringLiteral */ && !(t & 256 /* EnumLiteral */) && + if (s & 64 /* StringLiteral */ && s & 512 /* EnumLiteral */ && + t & 64 /* StringLiteral */ && !(t & 512 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 84 /* NumberLike */ && t & 4 /* Number */) + if (s & 168 /* NumberLike */ && t & 8 /* Number */) return true; - if (s & 64 /* NumberLiteral */ && s & 256 /* EnumLiteral */ && - t & 64 /* NumberLiteral */ && !(t & 256 /* EnumLiteral */) && + if (s & 128 /* NumberLiteral */ && s & 512 /* EnumLiteral */ && + t & 128 /* NumberLiteral */ && !(t & 512 /* EnumLiteral */) && source.value === target.value) return true; - if (s & 136 /* BooleanLike */ && t & 8 /* Boolean */) + if (s & 272 /* BooleanLike */ && t & 16 /* Boolean */) return true; - if (s & 1536 /* ESSymbolLike */ && t & 512 /* ESSymbol */) + if (s & 3072 /* ESSymbolLike */ && t & 1024 /* ESSymbol */) return true; - if (s & 16 /* Enum */ && t & 16 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 256 /* EnumLiteral */ && t & 256 /* EnumLiteral */) { - if (s & 131072 /* Union */ && t & 131072 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) + if (s & 512 /* EnumLiteral */ && t & 512 /* EnumLiteral */) { + if (s & 262144 /* Union */ && t & 262144 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; - if (s & 224 /* Literal */ && t & 224 /* Literal */ && + if (s & 448 /* Literal */ && t & 448 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter)) return true; } - if (s & 4096 /* Undefined */ && (!strictNullChecks || t & (4096 /* Undefined */ | 2048 /* Void */))) + if (s & 8192 /* Undefined */ && (!strictNullChecks || t & (8192 /* Undefined */ | 4096 /* Void */))) return true; - if (s & 8192 /* Null */ && (!strictNullChecks || t & 8192 /* Null */)) + if (s & 16384 /* Null */ && (!strictNullChecks || t & 16384 /* Null */)) return true; - if (s & 65536 /* Object */ && t & 134217728 /* NonPrimitive */) + if (s & 131072 /* Object */ && t & 16777216 /* NonPrimitive */) return true; - if (s & 1024 /* UniqueESSymbol */ || t & 1024 /* UniqueESSymbol */) + if (s & 2048 /* UniqueESSymbol */ || t & 2048 /* UniqueESSymbol */) return false; if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) @@ -33562,30 +38475,30 @@ var ts; // Type number or any numeric literal type is assignable to any numeric enum type or any // numeric enum literal type. This rule exists for backwards compatibility reasons because // bit-flag enum types sometimes look like literal enum types with numeric literal values. - if (s & (4 /* Number */ | 64 /* NumberLiteral */) && !(s & 256 /* EnumLiteral */) && (t & 16 /* Enum */ || t & 64 /* NumberLiteral */ && t & 256 /* EnumLiteral */)) + if (s & (8 /* Number */ | 128 /* NumberLiteral */) && !(s & 512 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 128 /* NumberLiteral */ && t & 512 /* EnumLiteral */)) return true; } return false; } function isTypeRelatedTo(source, target, relation) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { + if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 8388608 /* FreshLiteral */) { + if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } if (source === target || - relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || relation !== identityRelation && isSimpleTypeRelatedTo(source, target, relation)) { return true; } - if (source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */) { + if (source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */) { var related = relation.get(getRelationKey(source, target, relation)); if (related !== undefined) { return related === 1 /* Succeeded */; } } - if (source.flags & 8355840 /* StructuredOrInstantiable */ || target.flags & 8355840 /* StructuredOrInstantiable */) { + if (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */) { return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined); } return false; @@ -33603,7 +38516,7 @@ var ts; * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used. * @param containingMessageChain A chain of errors to prepend any new errors found. */ - function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain) { + function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; var maybeKeys; var sourceStack; @@ -33625,18 +38538,24 @@ var ts; errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); - } - // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement - if (headMessage && errorNode && !result && source.symbol) { - var links = getSymbolLinks(source.symbol); - if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { - var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); - if (helpfulRetry) { - // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import - diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + var relatedInformation = void 0; + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + var diag_1 = ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead); + relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it + } } } + var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation); + if (errorOutputContainer) { + errorOutputContainer.error = diag; + } + diagnostics.add(diag); // TODO: GH#18217 } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { @@ -33674,7 +38593,7 @@ var ts; } } function isUnionOrIntersectionTypeWithoutNullableConstituents(type) { - if (!(type.flags & 393216 /* UnionOrIntersection */)) { + if (!(type.flags & 786432 /* UnionOrIntersection */)) { return false; } // at this point we know that this is union or intersection type possibly with nullable constituents. @@ -33682,7 +38601,7 @@ var ts; var seenNonNullable = false; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var t = _a[_i]; - if (t.flags & 12288 /* Nullable */) { + if (t.flags & 24576 /* Nullable */) { continue; } if (seenNonNullable) { @@ -33699,29 +38618,52 @@ var ts; * * Ternary.False if they are not related. */ function isRelatedTo(source, target, reportErrors, headMessage) { - if (source.flags & 96 /* StringOrNumberLiteral */ && source.flags & 8388608 /* FreshLiteral */) { + if (reportErrors === void 0) { reportErrors = false; } + if (source.flags & 192 /* StringOrNumberLiteral */ && source.flags & 33554432 /* FreshLiteral */) { source = source.regularType; } - if (target.flags & 96 /* StringOrNumberLiteral */ && target.flags & 8388608 /* FreshLiteral */) { + if (target.flags & 192 /* StringOrNumberLiteral */ && target.flags & 33554432 /* FreshLiteral */) { target = target.regularType; } - if (source.flags & 4194304 /* Substitution */) { + if (source.flags & 8388608 /* Substitution */) { source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; } - if (target.flags & 4194304 /* Substitution */) { + if (target.flags & 8388608 /* Substitution */) { target = target.typeVariable; } + if (source.flags & 2097152 /* IndexedAccess */) { + source = getSimplifiedType(source); + } + if (target.flags & 2097152 /* IndexedAccess */) { + target = getSimplifiedType(target); + } + // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. + // If so, reporting the `null` and `undefined` in the type is hardly useful. + // First, see if we're even relating an object type to a union. + // Then see if the target is stripped down to a single non-union type. + // Note + // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), + // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable`" + // when dealing with generics. + // * We also don't deal with primitive source types, since we already halt elaboration below. + if (target.flags & 262144 /* Union */ && source.flags & 131072 /* Object */ && + target.types.length <= 3 && maybeTypeOfKind(target, 24576 /* Nullable */)) { + var nullStrippedTarget = extractTypesOfKind(target, ~24576 /* Nullable */); + if (!(nullStrippedTarget.flags & (262144 /* Union */ | 32768 /* Never */))) { + target = nullStrippedTarget; + } + } // both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases if (source === target) return -1 /* True */; if (relation === identityRelation) { return isIdenticalTo(source, target); } - if (relation === comparableRelation && !(target.flags & 16384 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || + if (relation === comparableRelation && !(target.flags & 32768 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - if (isObjectLiteralType(source) && source.flags & 8388608 /* FreshLiteral */) { - var discriminantType = target.flags & 131072 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; + if (isObjectLiteralType(source) && source.flags & 33554432 /* FreshLiteral */) { + var discriminantType = target.flags & 262144 /* Union */ ? findMatchingDiscriminantType(source, target) : undefined; if (hasExcessProperties(source, target, discriminantType, reportErrors)) { if (reportErrors) { reportRelationError(headMessage, source, target); @@ -33737,8 +38679,8 @@ var ts; } } if (relation !== comparableRelation && - !(source.flags & 393216 /* UnionOrIntersection */) && - !(target.flags & 131072 /* Union */) && + !(source.flags & 786432 /* UnionOrIntersection */) && + !(target.flags & 262144 /* Union */) && !isIntersectionConstituent && source !== globalObjectType && (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)) && @@ -33764,20 +38706,20 @@ var ts; // Note that these checks are specifically ordered to produce correct results. In particular, // we need to deconstruct unions before intersections (because unions are always at the top), // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { result = relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */)); + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */)); } else { - if (target.flags & 131072 /* Union */) { - result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 16382 /* Primitive */) && !(target.flags & 16382 /* Primitive */)); + if (target.flags & 262144 /* Union */) { + result = typeRelatedToSomeType(source, target, reportErrors && !(source.flags & 32764 /* Primitive */) && !(target.flags & 32764 /* Primitive */)); } - else if (target.flags & 262144 /* Intersection */) { + else if (target.flags & 524288 /* Intersection */) { isIntersectionConstituent = true; result = typeRelatedToEachType(source, target, reportErrors); } - else if (source.flags & 262144 /* Intersection */) { + else if (source.flags & 524288 /* Intersection */) { // Check to see if any constituents of the intersection are immediately related to the target. // // Don't report errors though. Checking whether a constituent is related to the source is not actually @@ -33793,20 +38735,47 @@ var ts; // breaking the intersection apart. result = someTypeRelatedToType(source, target, /*reportErrors*/ false); } - if (!result && (source.flags & 8355840 /* StructuredOrInstantiable */ || target.flags & 8355840 /* StructuredOrInstantiable */)) { + if (!result && (source.flags & 16711680 /* StructuredOrInstantiable */ || target.flags & 16711680 /* StructuredOrInstantiable */)) { if (result = recursiveTypeRelatedTo(source, target, reportErrors)) { errorInfo = saveErrorInfo; } } } + if (!result && source.flags & 524288 /* Intersection */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + var constraint = getUnionConstraintOfIntersection(source, !!(target.flags & 262144 /* Union */)); + if (constraint) { + if (result = isRelatedTo(constraint, target, reportErrors)) { + errorInfo = saveErrorInfo; + } + } + } isIntersectionConstituent = saveIsIntersectionConstituent; if (!result && reportErrors) { - if (source.flags & 65536 /* Object */ && target.flags & 16382 /* Primitive */) { + if (source.flags & 131072 /* Object */ && target.flags & 32764 /* Primitive */) { tryElaborateErrorsForPrimitivesAndObjects(source, target); } - else if (source.symbol && source.flags & 65536 /* Object */ && globalObjectType === source) { + else if (source.symbol && source.flags & 131072 /* Object */ && globalObjectType === source) { reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); } + else if (ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && target.flags & 524288 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return result; + } + } reportRelationError(headMessage, source, target); } return result; @@ -33814,27 +38783,27 @@ var ts; function isIdenticalTo(source, target) { var result; var flags = source.flags & target.flags; - if (flags & 65536 /* Object */) { + if (flags & 131072 /* Object */) { return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false); } - if (flags & (131072 /* Union */ | 262144 /* Intersection */)) { + if (flags & (262144 /* Union */ | 524288 /* Intersection */)) { if (result = eachTypeRelatedToSomeType(source, target)) { if (result &= eachTypeRelatedToSomeType(target, source)) { return result; } } } - if (flags & 524288 /* Index */) { + if (flags & 1048576 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - if (flags & 1048576 /* IndexedAccess */) { + if (flags & 2097152 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { if (result &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { return result; } } } - if (flags & 2097152 /* Conditional */) { + if (flags & 4194304 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { if (result = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { @@ -33847,13 +38816,13 @@ var ts; } } } - if (flags & 4194304 /* Substitution */) { + if (flags & 8388608 /* Substitution */) { return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false); } return 0 /* False */; } function hasExcessProperties(source, target, discriminant, reportErrors) { - if (maybeTypeOfKind(target, 65536 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (maybeTypeOfKind(target, 131072 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { @@ -33863,13 +38832,14 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_4 = function (prop) { + var _loop_7 = function (prop) { if (!isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. - ts.Debug.assert(!!errorNode); + if (!errorNode) + return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode)) { // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. @@ -33883,8 +38853,9 @@ var ts; var propDeclaration = prop.valueDeclaration; ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike); errorNode = propDeclaration; - if (ts.isIdentifier(propDeclaration.name)) { - suggestion = getSuggestionForNonexistentProperty(propDeclaration.name, target); + var name = propDeclaration.name; + if (ts.isIdentifier(name)) { + suggestion = getSuggestionForNonexistentProperty(name, target); } } if (suggestion !== undefined) { @@ -33900,9 +38871,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_4(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -33922,7 +38893,7 @@ var ts; } function typeRelatedToSomeType(source, target, reportErrors) { var targetTypes = target.types; - if (target.flags & 131072 /* Union */ && containsType(targetTypes, source)) { + if (target.flags & 262144 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { @@ -33933,11 +38904,35 @@ var ts; } } if (reportErrors) { - var discriminantType = findMatchingDiscriminantType(source, target); - isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + var bestMatchingType = findMatchingDiscriminantType(source, target) || + findMatchingTypeReferenceOrTypeAliasReference(source, target) || + findBestTypeForObjectLiteral(source, target); + isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; } + function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) { + var sourceObjectFlags = ts.getObjectFlags(source); + if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 262144 /* Union */) { + return ts.find(unionTarget.types, function (target) { + if (target.flags & 131072 /* Object */) { + var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target); + if (overlapObjFlags & 4 /* Reference */) { + return source.target === target.target; + } + if (overlapObjFlags & 16 /* Anonymous */) { + return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol; + } + } + return false; + }); + } + } + function findBestTypeForObjectLiteral(source, unionTarget) { + if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) { + return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); }); + } + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { var match; @@ -33980,7 +38975,7 @@ var ts; } function someTypeRelatedToType(source, target, reportErrors) { var sourceTypes = source.types; - if (source.flags & 131072 /* Union */ && containsType(sourceTypes, target)) { + if (source.flags & 262144 /* Union */ && containsType(sourceTypes, target)) { return -1 /* True */; } var len = sourceTypes.length; @@ -34069,9 +39064,8 @@ var ts; var related = relation.get(id); if (related !== undefined) { if (reportErrors && related === 2 /* Failed */) { - // We are elaborating errors and the cached result is an unreported failure. Record the result as a reported - // failure and continue computing the relation such that errors get reported. - relation.set(id, 3 /* FailedAndReported */); + // We are elaborating errors and the cached result is an unreported failure. The result will be reported + // as a failure, and should be updated as a reported failure by the bottom of this function. } else { return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; @@ -34132,7 +39126,7 @@ var ts; var result; var originalErrorInfo; var saveErrorInfo = errorInfo; - if (target.flags & 32768 /* TypeParameter */) { + if (target.flags & 65536 /* TypeParameter */) { // A source type { [P in keyof T]: X } is related to a target type T if X is related to T[P]. if (ts.getObjectFlags(source) & 32 /* Mapped */ && getConstraintTypeFromMappedType(source) === getIndexType(target)) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { @@ -34144,25 +39138,28 @@ var ts; } } } - else if (target.flags & 524288 /* Index */) { + else if (target.flags & 1048576 /* Index */) { // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 524288 /* Index */) { + if (source.flags & 1048576 /* Index */) { if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) { return result; } } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the - // constraint of T. - var constraint = getConstraintForRelation(target.type); - if (constraint) { - if (result = isRelatedTo(source, getIndexType(constraint), reportErrors)) { - return result; + // simplified form of T or, if T doesn't simplify, the constraint of T. + if (relation !== definitelyAssignableRelation) { + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + if (result = isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors)) { + return result; + } } } } - else if (target.flags & 1048576 /* IndexedAccess */) { - // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of T. + else if (target.flags & 2097152 /* IndexedAccess */) { + // A type S is related to a type T[K] if S is related to C, where C is the + // constraint of T[K] var constraint = getConstraintForRelation(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -34176,7 +39173,7 @@ var ts; var template = getTemplateTypeFromMappedType(target); var modifiers = getMappedTypeModifiers(target); if (!(modifiers & 8 /* ExcludeOptional */)) { - if (template.flags & 1048576 /* IndexedAccess */ && template.objectType === source && + if (template.flags & 2097152 /* IndexedAccess */ && template.objectType === source && template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } @@ -34191,32 +39188,9 @@ var ts; } } } - if (source.flags & 32768 /* TypeParameter */) { - var constraint = getConstraintForRelation(source); - // A type parameter with no constraint is not related to the non-primitive object type. - if (constraint || !(target.flags & 134217728 /* NonPrimitive */)) { - if (!constraint || constraint.flags & 1 /* Any */) { - constraint = emptyObjectType; - } - // Report constraint errors only if the constraint is not the empty object type - var reportConstraintErrors = reportErrors && constraint !== emptyObjectType; - if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - } - else if (source.flags & 1048576 /* IndexedAccess */) { - // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. - var constraint = getConstraintForRelation(source); - if (constraint) { - if (result = isRelatedTo(constraint, target, reportErrors)) { - errorInfo = saveErrorInfo; - return result; - } - } - else if (target.flags & 1048576 /* IndexedAccess */) { + if (source.flags & 2162688 /* TypeVariable */) { + if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { + // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { result &= isRelatedTo(source.indexType, target.indexType, reportErrors); } @@ -34225,11 +39199,35 @@ var ts; return result; } } + var constraint = getConstraintForRelation(source); + if (!constraint || (source.flags & 65536 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + // A type variable with no constraint is not related to the non-primitive object type. + if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~16777216 /* NonPrimitive */))) { + errorInfo = saveErrorInfo; + return result; + } + } + else { + var instantiated = getTypeWithThisArgument(constraint, source); + if (result = isRelatedTo(instantiated, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } } - else if (source.flags & 2097152 /* Conditional */) { - if (target.flags & 2097152 /* Conditional */) { - if (isTypeIdenticalTo(source.checkType, target.checkType) && - isTypeIdenticalTo(source.extendsType, target.extendsType)) { + else if (source.flags & 1048576 /* Index */) { + if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) { + errorInfo = saveErrorInfo; + return result; + } + } + else if (source.flags & 4194304 /* Conditional */) { + if (target.flags & 4194304 /* Conditional */) { + // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo(source.extendsType, target.extendsType) && + (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } @@ -34292,14 +39290,14 @@ var ts; } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - var sourceIsPrimitive = !!(source.flags & 16382 /* Primitive */); + var sourceIsPrimitive = !!(source.flags & 32764 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); } // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (65536 /* Object */ | 262144 /* Intersection */) && target.flags & 65536 /* Object */) { + if (source.flags & (131072 /* Object */ | 524288 /* Intersection */) && target.flags & 131072 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo && !sourceIsPrimitive; // An empty object type is related to any mapped type that includes a '?' modifier. @@ -34342,10 +39340,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_1; - if (result_1 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_2; + if (result_2 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_1 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_2 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -34354,7 +39352,7 @@ var ts; if (relation === identityRelation) { return propertiesIdenticalTo(source, target); } - var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source); + var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { @@ -34377,6 +39375,33 @@ var ts; } } var result = -1 /* True */; + if (isTupleType(target)) { + var targetRestType = getRestTypeOfTupleType(target); + if (targetRestType) { + if (!isTupleType(source)) { + return 0 /* False */; + } + var sourceRestType = getRestTypeOfTupleType(source); + if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) { + if (reportErrors) { + reportError(ts.Diagnostics.Rest_signatures_are_incompatible); + } + return 0 /* False */; + } + var targetCount = getTypeReferenceArity(target) - 1; + var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0); + for (var i = targetCount; i < sourceCount; i++) { + var related = isRelatedTo(source.typeArguments[i], targetRestType, reportErrors); + if (!related) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i); + } + return 0 /* False */; + } + result &= related; + } + } + } var properties = getPropertiesOfObjectType(target); for (var _b = 0, properties_3 = properties; _b < properties_3.length; _b++) { var targetProp = properties_3[_b]; @@ -34389,13 +39414,14 @@ var ts; var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */) { + var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; + if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } return 0 /* False */; } - if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { + if (hasDifferingDeclarations) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); @@ -34453,14 +39479,14 @@ var ts; * and no required properties, call/construct signatures or index signatures */ function isWeakType(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo && resolved.properties.length > 0 && ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); }); } - if (type.flags & 262144 /* Intersection */) { + if (type.flags & 524288 /* Intersection */) { return ts.every(type.types, isWeakType); } return false; @@ -34476,7 +39502,7 @@ var ts; return false; } function propertiesIdenticalTo(source, target) { - if (!(source.flags & 65536 /* Object */ && target.flags & 65536 /* Object */)) { + if (!(source.flags & 131072 /* Object */ && target.flags & 131072 /* Object */)) { return 0 /* False */; } var sourceProperties = getPropertiesOfObjectType(source); @@ -34544,7 +39570,7 @@ var ts; // in the context of the target signature before checking the relationship. Ideally we'd do // this regardless of the number of signatures, but the potential costs are prohibitive due // to the quadratic nature of the logic below. - var eraseGenerics = relation === comparableRelation || compilerOptions.noStrictGenericChecks; + var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks; result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors); } else { @@ -34600,8 +39626,7 @@ var ts; continue; } // Skip over symbol-named members - var nameType = getLiteralTypeFromPropertyName(prop); - if (nameType !== undefined && !(isRelatedTo(nameType, stringType) || isRelatedTo(nameType, numberType))) { + if (prop.nameType && prop.nameType.flags & 2048 /* UniqueESSymbol */) { continue; } if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) { @@ -34629,7 +39654,7 @@ var ts; return indexTypesIdenticalTo(source, target, kind); } var targetInfo = getIndexInfoOfType(target, kind); - if (!targetInfo || targetInfo.type.flags & 1 /* Any */ && !sourceIsPrimitive) { + if (!targetInfo || targetInfo.type.flags & 3 /* AnyOrUnknown */ && !sourceIsPrimitive) { // Index signature of type any permits assignment from everything but primitives return -1 /* True */; } @@ -34641,7 +39666,7 @@ var ts; 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); + return (kind === 0 /* String */ && isRelatedTo(getTemplateTypeFromMappedType(source), targetInfo.type, reportErrors)); // TODO: GH#18217 } if (isObjectTypeWithInferableIndex(source)) { var related = -1 /* True */; @@ -34751,17 +39776,17 @@ var ts; // See comment at call in recursiveTypeRelatedTo for when this case matters. function hasCovariantVoidArgument(type, variances) { for (var i = 0; i < variances.length; i++) { - if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 2048 /* Void */) { + if (variances[i] === 1 /* Covariant */ && type.typeArguments[i].flags & 4096 /* Void */) { return true; } } return false; } function isUnconstrainedTypeParameter(type) { - return type.flags & 32768 /* TypeParameter */ && !getConstraintFromTypeParameter(type); + return type.flags & 65536 /* TypeParameter */ && !getConstraintOfTypeParameter(type); } function isTypeReferenceWithGenericArguments(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && ts.some(type.typeArguments, function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); }); } /** * getTypeReferenceId(A) returns "111=0-12=1" @@ -34851,13 +39876,13 @@ var ts; // levels, but unequal at some level beyond that. function isDeeplyNestedType(type, stack, depth) { // We track all object types that have an associated symbol (representing the origin of the type) - if (depth >= 5 && type.flags & 65536 /* Object */) { + if (depth >= 5 && type.flags & 131072 /* Object */) { var symbol = type.symbol; if (symbol) { var count = 0; for (var i = 0; i < depth; i++) { var t = stack[i]; - if (t.flags & 65536 /* Object */ && t.symbol === symbol) { + if (t.flags & 131072 /* Object */ && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -34898,20 +39923,26 @@ var ts; return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } function isMatchingSignature(source, target, partialMatch) { + var sourceParameterCount = getParameterCount(source); + var targetParameterCount = getParameterCount(target); + var sourceMinArgumentCount = getMinArgumentCount(source); + var targetMinArgumentCount = getMinArgumentCount(target); + var sourceHasRestParameter = hasEffectiveRestParameter(source); + var targetHasRestParameter = hasEffectiveRestParameter(target); // A source signature matches a target signature if the two signatures have the same number of required, // optional, and rest parameters. - if (source.parameters.length === target.parameters.length && - source.minArgumentCount === target.minArgumentCount && - source.hasRestParameter === target.hasRestParameter) { + if (sourceParameterCount === targetParameterCount && + sourceMinArgumentCount === targetMinArgumentCount && + sourceHasRestParameter === targetHasRestParameter) { return true; } // A source signature partially matches a target signature if the target signature has no fewer required // parameters and no more overall parameters than the source signature (where a signature with a rest // parameter is always considered to have more overall parameters than one without). - var sourceRestCount = source.hasRestParameter ? 1 : 0; - var targetRestCount = target.hasRestParameter ? 1 : 0; - if (partialMatch && source.minArgumentCount <= target.minArgumentCount && (sourceRestCount > targetRestCount || - sourceRestCount === targetRestCount && source.parameters.length >= target.parameters.length)) { + var sourceRestCount = sourceHasRestParameter ? 1 : 0; + var targetRestCount = targetHasRestParameter ? 1 : 0; + if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount && (sourceRestCount > targetRestCount || + sourceRestCount === targetRestCount && sourceParameterCount >= targetParameterCount)) { return true; } return false; @@ -34953,10 +39984,10 @@ var ts; } } } - var targetLen = target.parameters.length; + var targetLen = getParameterCount(target); for (var i = 0; i < targetLen; i++) { - var s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfParameter(source.parameters[i]); - var t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfParameter(target.parameters[i]); + var s = getTypeAtPosition(source, i); + var t = getTypeAtPosition(target, i); var related = compareTypes(s, t); if (!related) { return 0 /* False */; @@ -34976,9 +40007,6 @@ var ts; function compareTypePredicatesIdentical(source, target, compareTypes) { return source === undefined || target === undefined || !typePredicateKindsMatch(source, target) ? 0 /* False */ : compareTypes(source.type, target.type); } - function isRestParameterIndex(signature, parameterIndex) { - return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; - } function literalTypesWithSameBaseType(types) { var commonBaseType; for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { @@ -35005,9 +40033,9 @@ var ts; if (!strictNullChecks) { return getSupertypeOrUnion(types); } - var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 12288 /* Nullable */); }); + var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 24576 /* Nullable */); }); return primaryTypes.length ? - getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 12288 /* Nullable */) : + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 24576 /* Nullable */) : getUnionType(types, 2 /* Subtype */); } // Return the leftmost type for which no type to the right is a subtype. @@ -35015,48 +40043,56 @@ var ts; return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; }); } function isArrayType(type) { - return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; + return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalArrayType; } function isArrayLikeType(type) { // A type is array-like if it is a reference to the global Array or global ReadonlyArray type, // or if it is not the undefined or null type and if it is assignable to ReadonlyArray return ts.getObjectFlags(type) & 4 /* Reference */ && (type.target === globalArrayType || type.target === globalReadonlyArrayType) || - !(type.flags & 12288 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); + !(type.flags & 24576 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType); } function isEmptyArrayLiteralType(type) { var elementType = isArrayType(type) ? type.typeArguments[0] : undefined; return elementType === undefinedWideningType || elementType === implicitNeverType; } function isTupleLikeType(type) { - return !!getPropertyOfType(type, "0"); + return isTupleType(type) || !!getPropertyOfType(type, "0"); + } + function getTupleElementType(type, index) { + return isTupleType(type) ? + index < getLengthOfTupleType(type) ? type.typeArguments[index] : getRestTypeOfTupleType(type) : + getTypeOfPropertyOfType(type, "" + index); + } + function isNeitherUnitTypeNorNever(type) { + return !(type.flags & (27072 /* Unit */ | 32768 /* Never */)); } function isUnitType(type) { - return !!(type.flags & 13536 /* Unit */); + return !!(type.flags & 27072 /* Unit */); } function isLiteralType(type) { - return type.flags & 8 /* Boolean */ ? true : - type.flags & 131072 /* Union */ ? type.flags & 256 /* EnumLiteral */ ? true : !ts.forEach(type.types, function (t) { return !isUnitType(t); }) : + return type.flags & 16 /* Boolean */ ? true : + type.flags & 262144 /* Union */ ? type.flags & 512 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) : isUnitType(type); } function getBaseTypeOfLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : + return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 64 /* StringLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ ? numberType : + type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) : type; } function getWidenedLiteralType(type) { - return type.flags & 256 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 32 /* StringLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? stringType : - type.flags & 64 /* NumberLiteral */ && type.flags & 8388608 /* FreshLiteral */ ? numberType : - type.flags & 128 /* BooleanLiteral */ ? booleanType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : + return type.flags & 512 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : + type.flags & 64 /* StringLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? stringType : + type.flags & 128 /* NumberLiteral */ && type.flags & 33554432 /* FreshLiteral */ ? numberType : + type.flags & 256 /* BooleanLiteral */ ? booleanType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) : type; } function getWidenedUniqueESSymbolType(type) { - return type.flags & 1024 /* UniqueESSymbol */ ? esSymbolType : - type.flags & 131072 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : + return type.flags & 2048 /* UniqueESSymbol */ ? esSymbolType : + type.flags & 262144 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) : type; } function getWidenedLiteralLikeTypeForContextualType(type, contextualType) { @@ -35072,6 +40108,12 @@ var ts; function isTupleType(type) { return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */); } + function getRestTypeOfTupleType(type) { + return type.target.hasRestElement ? type.typeArguments[type.target.typeParameters.length - 1] : undefined; + } + function getLengthOfTupleType(type) { + return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0); + } function getFalsyFlagsOfTypes(types) { var result = 0; for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { @@ -35084,27 +40126,27 @@ var ts; // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns // no flags for all other types (including non-falsy literal types). function getFalsyFlags(type) { - return type.flags & 131072 /* Union */ ? getFalsyFlagsOfTypes(type.types) : - type.flags & 32 /* StringLiteral */ ? type.value === "" ? 32 /* StringLiteral */ : 0 : - type.flags & 64 /* NumberLiteral */ ? type.value === 0 ? 64 /* NumberLiteral */ : 0 : - type.flags & 128 /* BooleanLiteral */ ? type === falseType ? 128 /* BooleanLiteral */ : 0 : - type.flags & 14574 /* PossiblyFalsy */; + return type.flags & 262144 /* Union */ ? getFalsyFlagsOfTypes(type.types) : + type.flags & 64 /* StringLiteral */ ? type.value === "" ? 64 /* StringLiteral */ : 0 : + type.flags & 128 /* NumberLiteral */ ? type.value === 0 ? 128 /* NumberLiteral */ : 0 : + type.flags & 256 /* BooleanLiteral */ ? type === falseType ? 256 /* BooleanLiteral */ : 0 : + type.flags & 29148 /* PossiblyFalsy */; } function removeDefinitelyFalsyTypes(type) { - return getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ ? - filterType(type, function (t) { return !(getFalsyFlags(t) & 14560 /* DefinitelyFalsy */); }) : + return getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ ? + filterType(type, function (t) { return !(getFalsyFlags(t) & 29120 /* DefinitelyFalsy */); }) : type; } function extractDefinitelyFalsyTypes(type) { return mapType(type, getDefinitelyFalsyPartOfType); } function getDefinitelyFalsyPartOfType(type) { - return type.flags & 2 /* String */ ? emptyStringType : - type.flags & 4 /* Number */ ? zeroType : - type.flags & 8 /* Boolean */ || type === falseType ? falseType : - type.flags & (2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */) || - type.flags & 32 /* StringLiteral */ && type.value === "" || - type.flags & 64 /* NumberLiteral */ && type.value === 0 ? type : + return type.flags & 4 /* String */ ? emptyStringType : + type.flags & 8 /* Number */ ? zeroType : + type.flags & 16 /* Boolean */ || type === falseType ? falseType : + type.flags & (4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */) || + type.flags & 64 /* StringLiteral */ && type.value === "" || + type.flags & 128 /* NumberLiteral */ && type.value === 0 ? type : neverType; } /** @@ -35113,15 +40155,15 @@ var ts; * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both */ function getNullableType(type, flags) { - var missing = (flags & ~type.flags) & (4096 /* Undefined */ | 8192 /* Null */); + var missing = (flags & ~type.flags) & (8192 /* Undefined */ | 16384 /* Null */); return missing === 0 ? type : - missing === 4096 /* Undefined */ ? getUnionType([type, undefinedType]) : - missing === 8192 /* Null */ ? getUnionType([type, nullType]) : + missing === 8192 /* Undefined */ ? getUnionType([type, undefinedType]) : + missing === 16384 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]); } function getOptionalType(type) { ts.Debug.assert(strictNullChecks); - return type.flags & 4096 /* Undefined */ ? type : getUnionType([type, undefinedType]); + return type.flags & 8192 /* Undefined */ ? type : getUnionType([type, undefinedType]); } function getGlobalNonNullableTypeInstantiation(type) { if (!deferredGlobalNonNullableTypeAlias) { @@ -35131,7 +40173,7 @@ var ts; if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) { return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]); } - return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higherorder behavior + return getTypeWithFacts(type, 524288 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior } function getNonNullableType(type) { return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type; @@ -35153,6 +40195,9 @@ var ts; if (source.valueDeclaration) { symbol.valueDeclaration = source.valueDeclaration; } + if (source.nameType) { + symbol.nameType = source.nameType; + } return symbol; } function transformTypeOfMembers(type, f) { @@ -35171,7 +40216,7 @@ var ts; * Leave signatures alone since they are not subject to the check. */ function getRegularTypeOfObjectLiteral(type) { - if (!(isObjectLiteralType(type) && type.flags & 8388608 /* FreshLiteral */)) { + if (!(isObjectLiteralType(type) && type.flags & 33554432 /* FreshLiteral */)) { return type; } var regularType = type.regularType; @@ -35181,13 +40226,13 @@ var ts; var resolved = type; var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral); var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo); - regularNew.flags = resolved.flags & ~8388608 /* FreshLiteral */; + regularNew.flags = resolved.flags & ~33554432 /* FreshLiteral */; regularNew.objectFlags |= 128 /* ObjectLiteral */; type.regularType = regularNew; return regularNew; } function createWideningContext(parent, propertyName, siblings) { - return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedPropertyNames: undefined }; + return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined }; } function getSiblingsOfContext(context) { if (!context.siblings) { @@ -35207,55 +40252,54 @@ var ts; } return context.siblings; } - function getPropertyNamesOfContext(context) { - if (!context.resolvedPropertyNames) { + function getPropertiesOfContext(context) { + if (!context.resolvedProperties) { var names = ts.createMap(); for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) { var t = _a[_i]; if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) { for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) { var prop = _c[_b]; - names.set(prop.escapedName, true); + names.set(prop.escapedName, prop); } } } - context.resolvedPropertyNames = ts.arrayFrom(names.keys()); + context.resolvedProperties = ts.arrayFrom(names.values()); } - return context.resolvedPropertyNames; + return context.resolvedProperties; } function getWidenedProperty(prop, context) { + if (!(prop.flags & 4 /* Property */)) { + // Since get accessors already widen their return value there is no need to + // widen accessor based properties here. + return prop; + } var original = getTypeOfSymbol(prop); var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined); var widened = getWidenedTypeWithContext(original, propContext); return widened === original ? prop : createSymbolWithType(prop, widened); } - function getUndefinedProperty(name) { - var cached = undefinedProperties.get(name); + function getUndefinedProperty(prop) { + var cached = undefinedProperties.get(prop.escapedName); if (cached) { return cached; } - var result = createSymbol(4 /* Property */ | 16777216 /* Optional */, name); - result.type = undefinedType; - var associatedKeyType = getLiteralType(ts.unescapeLeadingUnderscores(name)); - if (associatedKeyType.flags & 32 /* StringLiteral */) { - result.nameType = associatedKeyType; - } - undefinedProperties.set(name, result); + var result = createSymbolWithType(prop, undefinedType); + result.flags |= 16777216 /* Optional */; + undefinedProperties.set(prop.escapedName, result); return result; } function getWidenedTypeOfObjectLiteral(type, context) { var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) { var prop = _a[_i]; - // Since get accessors already widen their return value there is no need to - // widen accessor based properties here. - members.set(prop.escapedName, prop.flags & 4 /* Property */ ? getWidenedProperty(prop, context) : prop); + members.set(prop.escapedName, getWidenedProperty(prop, context)); } if (context) { - for (var _b = 0, _c = getPropertyNamesOfContext(context); _b < _c.length; _b++) { - var name = _c[_b]; - if (!members.has(name)) { - members.set(name, getUndefinedProperty(name)); + for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) { + var prop = _c[_b]; + if (!members.has(prop.escapedName)) { + members.set(prop.escapedName, getUndefinedProperty(prop)); } } } @@ -35267,16 +40311,16 @@ var ts; return getWidenedTypeWithContext(type, /*context*/ undefined); } function getWidenedTypeWithContext(type, context) { - if (type.flags & 50331648 /* RequiresWidening */) { - if (type.flags & 12288 /* Nullable */) { + if (type.flags & 402653184 /* RequiresWidening */) { + if (type.flags & 24576 /* Nullable */) { return anyType; } if (isObjectLiteralType(type)) { return getWidenedTypeOfObjectLiteral(type, context); } - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types); - var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 12288 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); + var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 24576 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); }); // Widening an empty object literal transitions from a highly restrictive type to // a highly inclusive one. For that reason we perform subtype reduction here if the // union includes empty object types (e.g. reducing {} | string to just {}). @@ -35301,8 +40345,8 @@ var ts; */ function reportWideningErrorsInType(type) { var errorReported = false; - if (type.flags & 16777216 /* ContainsWideningType */) { - if (type.flags & 131072 /* Union */) { + if (type.flags & 134217728 /* ContainsWideningType */) { + if (type.flags & 262144 /* Union */) { if (ts.some(type.types, isEmptyObjectType)) { errorReported = true; } @@ -35327,7 +40371,7 @@ var ts; for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { var p = _e[_d]; var t = getTypeOfSymbol(p); - if (t.flags & 16777216 /* ContainsWideningType */) { + if (t.flags & 134217728 /* ContainsWideningType */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -35342,32 +40386,33 @@ var ts; var typeAsString = typeToString(getWidenedType(type)); var diagnostic; switch (declaration.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 202 /* BinaryExpression */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: diagnostic = ts.Diagnostics.Member_0_implicitly_has_an_1_type; break; - case 148 /* Parameter */: + case 149 /* Parameter */: diagnostic = declaration.dotDotDotToken ? ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : ts.Diagnostics.Parameter_0_implicitly_has_an_1_type; break; - case 180 /* BindingElement */: + case 184 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; break; - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: if (!declaration.name) { error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } diagnostic = ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type; break; - case 176 /* MappedType */: + case 179 /* MappedType */: error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type); return; default: @@ -35376,7 +40421,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && noImplicitAny && type.flags & 16777216 /* ContainsWideningType */) { + if (produceDiagnostics && noImplicitAny && type.flags & 134217728 /* ContainsWideningType */) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -35384,24 +40429,22 @@ var ts; } } function forEachMatchingParameterType(source, target, callback) { - var sourceMax = source.parameters.length; - var targetMax = target.parameters.length; - var count; - if (source.hasRestParameter && target.hasRestParameter) { - count = Math.max(sourceMax, targetMax); - } - else if (source.hasRestParameter) { - count = targetMax; - } - else if (target.hasRestParameter) { - count = sourceMax; - } - else { - count = Math.min(sourceMax, targetMax); - } - for (var i = 0; i < count; i++) { + var sourceCount = getParameterCount(source); + var targetCount = getParameterCount(target); + var sourceHasRest = hasEffectiveRestParameter(source); + var targetHasRest = hasEffectiveRestParameter(target); + var maxCount = sourceHasRest && targetHasRest ? Math.max(sourceCount, targetCount) : + sourceHasRest ? targetCount : + targetHasRest ? sourceCount : + Math.min(sourceCount, targetCount); + var targetGenericRestType = getGenericRestType(target); + var paramCount = targetGenericRestType ? Math.min(targetCount - 1, maxCount) : maxCount; + for (var i = 0; i < paramCount; i++) { callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i)); } + if (targetGenericRestType) { + callback(getRestTypeAtPosition(source, paramCount), targetGenericRestType); + } } function createInferenceContext(typeParameters, signature, flags, compareTypes, baseInferences) { var inferences = baseInferences ? baseInferences.map(cloneInferenceInfo) : typeParameters.map(createInferenceInfo); @@ -35449,26 +40492,26 @@ var ts; // results for union and intersection types for performance reasons. function couldContainTypeVariables(type) { var objectFlags = ts.getObjectFlags(type); - return !!(type.flags & 7897088 /* Instantiable */ || + return !!(type.flags & 15794176 /* Instantiable */ || objectFlags & 4 /* Reference */ && ts.forEach(type.typeArguments, couldContainTypeVariables) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */) || objectFlags & 32 /* Mapped */ || - type.flags & 393216 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); + type.flags & 786432 /* UnionOrIntersection */ && couldUnionOrIntersectionContainTypeVariables(type)); } function couldUnionOrIntersectionContainTypeVariables(type) { if (type.couldContainTypeVariables === undefined) { - type.couldContainTypeVariables = ts.forEach(type.types, couldContainTypeVariables); + type.couldContainTypeVariables = ts.some(type.types, couldContainTypeVariables); } return type.couldContainTypeVariables; } function isTypeParameterAtTopLevel(type, typeParameter) { - return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); + return type === typeParameter || !!(type.flags & 786432 /* UnionOrIntersection */) && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { - if (!(t.flags & 32 /* StringLiteral */)) { + if (!(t.flags & 64 /* StringLiteral */)) { return; } var name = ts.escapeLeadingUnderscores(t.value); @@ -35480,7 +40523,7 @@ var ts; } members.set(name, literalProp); }); - var indexInfo = type.flags & 2 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; + var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined; return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined); } /** @@ -35508,7 +40551,7 @@ var ts; // is incomplete and we can't infer a meaningful input type. for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; - if (getTypeOfSymbol(prop).flags & 67108864 /* ContainsAnyFunctionType */) { + if (getTypeOfSymbol(prop).flags & 536870912 /* ContainsAnyFunctionType */) { return undefined; } } @@ -35528,7 +40571,7 @@ var ts; return getTypeFromInference(inference); } function getUnmatchedProperty(source, target, requireOptionalProperties) { - var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); + var properties = target.flags & 524288 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); for (var _i = 0, properties_5 = properties; _i < properties_5.length; _i++) { var targetProp = properties_5[_i]; if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */)) { @@ -35540,6 +40583,16 @@ var ts; } return undefined; } + function tupleTypesDefinitelyUnrelated(source, target) { + return target.target.minLength > source.target.minLength || + !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source)); + } + function typesDefinitelyUnrelated(source, target) { + // Two tuple types with incompatible arities are definitely unrelated. + // Two object types that each have a property that is unmatched in the other are definitely unrelated. + return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : @@ -35576,8 +40629,8 @@ var ts; } return; } - if (source.flags & 131072 /* Union */ && target.flags & 131072 /* Union */ && !(source.flags & 256 /* EnumLiteral */ && target.flags & 256 /* EnumLiteral */) || - source.flags & 262144 /* Intersection */ && target.flags & 262144 /* Intersection */) { + if (source.flags & 262144 /* Union */ && target.flags & 262144 /* Union */ && !(source.flags & 512 /* EnumLiteral */ && target.flags & 512 /* EnumLiteral */) || + source.flags & 524288 /* Intersection */ && target.flags & 524288 /* Intersection */) { // Source and target are both unions or both intersections. If source and target // are the same type, just relate each constituent type to itself. if (source === target) { @@ -35600,7 +40653,7 @@ var ts; (matchingTypes || (matchingTypes = [])).push(t); inferFromTypes(t, t); } - else if (t.flags & (64 /* NumberLiteral */ | 32 /* StringLiteral */)) { + else if (t.flags & (128 /* NumberLiteral */ | 64 /* StringLiteral */)) { var b = getBaseTypeOfLiteralType(t); if (typeIdenticalToSomeType(b, target.types)) { (matchingTypes || (matchingTypes = [])).push(t, b); @@ -35615,7 +40668,7 @@ var ts; target = removeTypesFromUnionOrIntersection(target, matchingTypes); } } - if (target.flags & 1081344 /* TypeVariable */) { + if (target.flags & 2162688 /* TypeVariable */) { // If target is a type parameter, make an inference, unless the source type contains // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). // Because the anyFunctionType is internal, it should not be exposed to the user by adding @@ -35623,7 +40676,7 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & 67108864 /* ContainsAnyFunctionType */ || source === silentNeverType) { + if (source.flags & 536870912 /* ContainsAnyFunctionType */ || source === silentNeverType) { return; } var inference = getInferenceInfoForType(target); @@ -35643,7 +40696,7 @@ var ts; inference.candidates = ts.append(inference.candidates, candidate); } } - if (!(priority & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 8 /* ReturnType */) && target.flags & 65536 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -35665,12 +40718,12 @@ var ts; } } } - else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { + else if (source.flags & 1048576 /* Index */ && target.flags & 1048576 /* Index */) { contravariant = !contravariant; inferFromTypes(source.type, target.type); contravariant = !contravariant; } - else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { + else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 1048576 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; var savePriority = priority; @@ -35679,17 +40732,17 @@ var ts; priority = savePriority; contravariant = !contravariant; } - else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { + else if (source.flags & 2097152 /* IndexedAccess */ && target.flags & 2097152 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); inferFromTypes(source.indexType, target.indexType); } - else if (source.flags & 2097152 /* Conditional */ && target.flags & 2097152 /* Conditional */) { + else if (source.flags & 4194304 /* Conditional */ && target.flags & 4194304 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } - else if (target.flags & 393216 /* UnionOrIntersection */) { + else if (target.flags & 786432 /* UnionOrIntersection */) { var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; @@ -35714,7 +40767,7 @@ var ts; priority = savePriority; } } - else if (source.flags & 131072 /* Union */) { + else if (source.flags & 262144 /* Union */) { // Source is a union or intersection type, infer from each constituent type var sourceTypes = source.types; for (var _e = 0, sourceTypes_3 = sourceTypes; _e < sourceTypes_3.length; _e++) { @@ -35723,10 +40776,10 @@ var ts; } } else { - if (!(priority & 32 /* NoConstraints */ && source.flags & (262144 /* Intersection */ | 7897088 /* Instantiable */))) { + if (!(priority & 32 /* NoConstraints */ && source.flags & (524288 /* Intersection */ | 15794176 /* Instantiable */))) { source = getApparentType(source); } - if (source.flags & (65536 /* Object */ | 262144 /* Intersection */)) { + if (source.flags & (131072 /* Object */ | 524288 /* Intersection */)) { var key = source.id + "," + target.id; if (visited && visited.get(key)) { return; @@ -35736,7 +40789,7 @@ var ts; // an instantiation of the same generic type), we do not explore this target as it would yield // no further inferences. We exclude the static side of classes from this check since it shares // its symbol with the instance side which would lead to false positives. - var isNonConstructorObject = target.flags & 65536 /* Object */ && + var isNonConstructorObject = target.flags & 131072 /* Object */ && !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */); var symbol = isNonConstructorObject ? target.symbol : undefined; if (symbol) { @@ -35764,7 +40817,7 @@ var ts; } } function getInferenceInfoForType(type) { - if (type.flags & 1081344 /* TypeVariable */) { + if (type.flags & 2162688 /* TypeVariable */) { for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) { var inference = inferences_1[_i]; if (type === inference.typeParameter) { @@ -35783,7 +40836,7 @@ var ts; } if (ts.getObjectFlags(target) & 32 /* Mapped */) { var constraintType = getConstraintTypeFromMappedType(target); - if (constraintType.flags & 524288 /* Index */) { + if (constraintType.flags & 1048576 /* Index */) { // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X }, // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference @@ -35800,7 +40853,7 @@ var ts; } return; } - if (constraintType.flags & 32768 /* TypeParameter */) { + if (constraintType.flags & 65536 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. var savePriority = priority; @@ -35811,9 +40864,8 @@ var ts; return; } } - // 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 (!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) || !getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false)) { + // Infer from the members of source and target only if the two types are possibly related + if (!typesDefinitelyUnrelated(source, target)) { inferFromProperties(source, target); inferFromSignatures(source, target, 0 /* Call */); inferFromSignatures(source, target, 1 /* Construct */); @@ -35821,12 +40873,33 @@ var ts; } } function inferFromProperties(source, target) { - var properties = getPropertiesOfObjectType(target); - for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { - var targetProp = properties_6[_i]; - var sourceProp = getPropertyOfType(source, targetProp.escapedName); - if (sourceProp) { - inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + if (isTupleType(source) && isTupleType(target)) { + var sourceLength = getLengthOfTupleType(source); + var targetLength = getLengthOfTupleType(target); + var sourceRestType = getRestTypeOfTupleType(source); + var targetRestType = getRestTypeOfTupleType(target); + var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength; + for (var i = 0; i < fixedLength; i++) { + inferFromTypes(i < sourceLength ? source.typeArguments[i] : sourceRestType, target.typeArguments[i]); + } + if (targetRestType) { + var types = fixedLength < sourceLength ? source.typeArguments.slice(fixedLength, sourceLength) : []; + if (sourceRestType) { + types.push(sourceRestType); + } + if (types.length) { + inferFromTypes(getUnionType(types), targetRestType); + } + } + } + else { + var properties = getPropertiesOfObjectType(target); + for (var _i = 0, properties_6 = properties; _i < properties_6.length; _i++) { + var targetProp = properties_6[_i]; + var sourceProp = getPropertyOfType(source, targetProp.escapedName); + if (sourceProp) { + inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); + } } } } @@ -35892,11 +40965,11 @@ var ts; reducedTypes.push(t); } } - return type.flags & 131072 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); + return type.flags & 262144 /* Union */ ? getUnionType(reducedTypes) : getIntersectionType(reducedTypes); } function hasPrimitiveConstraint(type) { var constraint = getConstraintOfTypeParameter(type); - return constraint && maybeTypeOfKind(constraint, 16382 /* Primitive */ | 524288 /* Index */); + return !!constraint && maybeTypeOfKind(constraint, 32764 /* Primitive */ | 1048576 /* Index */); } function isObjectLiteralType(type) { return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */); @@ -35921,10 +40994,12 @@ var ts; // all inferences were made to top-level occurrences of the type parameter, and // the type parameter has no constraint or its constraint includes no primitive or literal types, and // the type parameter was fixed during inference or does not occur at top-level in the return type. - var widenLiteralTypes = inference.topLevel && - !hasPrimitiveConstraint(inference.typeParameter) && + var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter); + var widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); - var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; + var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) : + widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : + candidates; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. @@ -35939,17 +41014,14 @@ var ts; if (!inferredType) { var signature = context.signature; if (signature) { + if (inference.contraCandidates) { + // If we have contravariant inferences we find the best common subtype and treat + // that as a single covariant candidate. + inference.candidates = ts.append(inference.candidates, getContravariantInference(inference)); + inference.contraCandidates = undefined; + } if (inference.candidates) { inferredType = getCovariantInference(inference, context, signature); - // If we have inferred 'never' but have contravariant candidates. To get a more specific type we - // infer from the contravariant candidates instead. - if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { - inferredType = getContravariantInference(inference); - } - } - else if (inference.contraCandidates) { - // We only have contravariant inferences, infer the best common subtype of those - inferredType = getContravariantInference(inference); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -35975,13 +41047,12 @@ var ts; else { inferredType = getTypeFromInference(inference); } - inferredType = getWidenedUniqueESSymbolType(inferredType); inference.inferredType = inferredType; var constraint = getConstraintOfTypeParameter(inference.typeParameter); if (constraint) { var instantiatedConstraint = instantiateType(constraint, context); if (!context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = getWidenedUniqueESSymbolType(instantiatedConstraint); + inference.inferredType = inferredType = instantiatedConstraint; } } } @@ -36011,7 +41082,7 @@ var ts; // TypeScript 1.0 spec (April 2014): 3.6.3 // A type query consists of the keyword typeof followed by an expression. // The expression is restricted to a single identifier or a sequence of identifiers separated by periods - return !!ts.findAncestor(node, function (n) { return n.kind === 164 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 145 /* QualifiedName */ ? false : "quit"; }); + return !!ts.findAncestor(node, function (n) { return n.kind === 165 /* TypeQuery */ ? true : n.kind === 71 /* Identifier */ || n.kind === 146 /* QualifiedName */ ? false : "quit"; }); } // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers // separated by dots). The key consists of the id of the symbol referenced by the @@ -36027,13 +41098,13 @@ var ts; if (node.kind === 99 /* ThisKeyword */) { return "0"; } - if (node.kind === 183 /* PropertyAccessExpression */) { + if (node.kind === 187 /* PropertyAccessExpression */) { var key = getFlowCacheKey(node.expression); return key && key + "." + ts.idText(node.name); } - if (node.kind === 180 /* BindingElement */) { + if (node.kind === 184 /* BindingElement */) { var container = node.parent.parent; - var key = container.kind === 180 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); + var key = container.kind === 184 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); var text = getBindingElementNameText(node); var result = key && text && (key + "." + text); return result; @@ -36041,12 +41112,13 @@ var ts; return undefined; } function getBindingElementNameText(element) { - if (element.parent.kind === 178 /* ObjectBindingPattern */) { + var parent = element.parent; + if (parent.kind === 182 /* ObjectBindingPattern */) { var name = element.propertyName || element.name; switch (name.kind) { case 71 /* Identifier */: return ts.idText(name); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: @@ -36057,41 +41129,41 @@ var ts; } } else { - return "" + element.parent.elements.indexOf(element); + return "" + parent.elements.indexOf(element); } } function isMatchingReference(source, target) { switch (source.kind) { case 71 /* Identifier */: return target.kind === 71 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || - (target.kind === 230 /* VariableDeclaration */ || target.kind === 180 /* BindingElement */) && + (target.kind === 235 /* VariableDeclaration */ || target.kind === 184 /* BindingElement */) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target); case 99 /* ThisKeyword */: return target.kind === 99 /* ThisKeyword */; case 97 /* SuperKeyword */: return target.kind === 97 /* SuperKeyword */; - case 183 /* PropertyAccessExpression */: - return target.kind === 183 /* PropertyAccessExpression */ && + case 187 /* PropertyAccessExpression */: + return target.kind === 187 /* PropertyAccessExpression */ && source.name.escapedText === target.name.escapedText && isMatchingReference(source.expression, target.expression); - case 180 /* BindingElement */: - if (target.kind !== 183 /* PropertyAccessExpression */) + case 184 /* BindingElement */: + if (target.kind !== 187 /* PropertyAccessExpression */) return false; var t = target; if (t.name.escapedText !== getBindingElementNameText(source)) return false; - if (source.parent.parent.kind === 180 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { + if (source.parent.parent.kind === 184 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { return true; } - if (source.parent.parent.kind === 230 /* VariableDeclaration */) { + if (source.parent.parent.kind === 235 /* VariableDeclaration */) { var maybeId = source.parent.parent.initializer; - return maybeId && isMatchingReference(maybeId, t.expression); + return !!maybeId && isMatchingReference(maybeId, t.expression); } } return false; } function containsMatchingReference(source, target) { - while (source.kind === 183 /* PropertyAccessExpression */) { + while (source.kind === 187 /* PropertyAccessExpression */) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -36104,7 +41176,7 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 183 /* PropertyAccessExpression */ && + return target.kind === 187 /* PropertyAccessExpression */ && containsMatchingReference(source, target.expression) && isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); } @@ -36112,18 +41184,18 @@ var ts; if (expr.kind === 71 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 183 /* PropertyAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */) { var type = getDeclaredTypeOfReference(expr.expression); return type && getTypeOfPropertyOfType(type, expr.name.escapedText); } return undefined; } function isDiscriminantProperty(type, name) { - if (type && type.flags & 131072 /* Union */) { + if (type && type.flags & 262144 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.checkFlags & 32 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -36156,7 +41228,7 @@ var ts; } } } - if (callExpression.expression.kind === 183 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -36170,7 +41242,7 @@ var ts; return flow.id; } function typeMaybeAssignableTo(source, target) { - if (!(source.flags & 131072 /* Union */)) { + if (!(source.flags & 262144 /* Union */)) { return isTypeAssignableTo(source, target); } for (var _i = 0, _a = source.types; _i < _a.length; _i++) { @@ -36186,11 +41258,11 @@ var ts; // we remove type string. function getAssignmentReducedType(declaredType, assignedType) { if (declaredType !== assignedType) { - if (assignedType.flags & 16384 /* Never */) { + if (assignedType.flags & 32768 /* Never */) { return assignedType; } var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); }); - if (!(reducedType.flags & 16384 /* Never */)) { + if (!(reducedType.flags & 32768 /* Never */)) { return reducedType; } } @@ -36213,53 +41285,53 @@ var ts; } function getTypeFacts(type) { var flags = type.flags; - if (flags & 2 /* String */) { + if (flags & 4 /* String */) { return strictNullChecks ? 4079361 /* StringStrictFacts */ : 4194049 /* StringFacts */; } - if (flags & 32 /* StringLiteral */) { + if (flags & 64 /* StringLiteral */) { var isEmpty = type.value === ""; return strictNullChecks ? isEmpty ? 3030785 /* EmptyStringStrictFacts */ : 1982209 /* NonEmptyStringStrictFacts */ : isEmpty ? 3145473 /* EmptyStringFacts */ : 4194049 /* NonEmptyStringFacts */; } - if (flags & (4 /* Number */ | 16 /* Enum */)) { + if (flags & (8 /* Number */ | 32 /* Enum */)) { return strictNullChecks ? 4079234 /* NumberStrictFacts */ : 4193922 /* NumberFacts */; } - if (flags & 64 /* NumberLiteral */) { + if (flags & 128 /* NumberLiteral */) { var isZero = type.value === 0; return strictNullChecks ? isZero ? 3030658 /* ZeroStrictFacts */ : 1982082 /* NonZeroStrictFacts */ : isZero ? 3145346 /* ZeroFacts */ : 4193922 /* NonZeroFacts */; } - if (flags & 8 /* Boolean */) { + if (flags & 16 /* Boolean */) { return strictNullChecks ? 4078980 /* BooleanStrictFacts */ : 4193668 /* BooleanFacts */; } - if (flags & 136 /* BooleanLike */) { + if (flags & 272 /* BooleanLike */) { return strictNullChecks ? type === falseType ? 3030404 /* FalseStrictFacts */ : 1981828 /* TrueStrictFacts */ : type === falseType ? 3145092 /* FalseFacts */ : 4193668 /* TrueFacts */; } - if (flags & 65536 /* Object */) { + if (flags & 131072 /* Object */) { return isFunctionObjectType(type) ? strictNullChecks ? 1970144 /* FunctionStrictFacts */ : 4181984 /* FunctionFacts */ : strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & (2048 /* Void */ | 4096 /* Undefined */)) { + if (flags & (4096 /* Void */ | 8192 /* Undefined */)) { return 2457472 /* UndefinedFacts */; } - if (flags & 8192 /* Null */) { + if (flags & 16384 /* Null */) { return 2340752 /* NullFacts */; } - if (flags & 1536 /* ESSymbolLike */) { + if (flags & 3072 /* ESSymbolLike */) { return strictNullChecks ? 1981320 /* SymbolStrictFacts */ : 4193160 /* SymbolFacts */; } - if (flags & 134217728 /* NonPrimitive */) { + if (flags & 16777216 /* NonPrimitive */) { return strictNullChecks ? 1972176 /* ObjectStrictFacts */ : 4184016 /* ObjectFacts */; } - if (flags & 7897088 /* Instantiable */) { + if (flags & 15794176 /* Instantiable */) { return getTypeFacts(getBaseConstraintOfType(type) || emptyObjectType); } - if (flags & 393216 /* UnionOrIntersection */) { + if (flags & 786432 /* UnionOrIntersection */) { return getTypeFactsOfTypes(type.types); } return 4194303 /* All */; @@ -36276,29 +41348,29 @@ var ts; } function getTypeOfDestructuredProperty(type, name) { var text = ts.getTextOfPropertyName(name); - return getTypeOfPropertyOfType(type, text) || + return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) || isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || - unknownType; + errorType; } function getTypeOfDestructuredArrayElement(type, index) { - return isTupleLikeType(type) && getTypeOfPropertyOfType(type, "" + index) || + return isTupleLikeType(type) && getTupleElementType(type, index) || checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || - unknownType; + errorType; } function getTypeOfDestructuredSpreadExpression(type) { - return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType); + return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType); } function getAssignedTypeOfBinaryExpression(node) { - var isDestructuringDefaultAssignment = node.parent.kind === 181 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || - node.parent.kind === 268 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + var isDestructuringDefaultAssignment = node.parent.kind === 185 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 273 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } function isDestructuringAssignmentTarget(parent) { - return parent.parent.kind === 198 /* BinaryExpression */ && parent.parent.left === parent || - parent.parent.kind === 220 /* ForOfStatement */ && parent.parent.initializer === parent; + return parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 225 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); @@ -36315,29 +41387,29 @@ var ts; function getAssignedType(node) { var parent = node.parent; switch (parent.kind) { - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return stringType; - case 220 /* ForOfStatement */: - return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || unknownType; - case 198 /* BinaryExpression */: + case 225 /* ForOfStatement */: + return checkRightHandSideOfForOf(parent.expression, parent.awaitModifier) || errorType; + case 202 /* BinaryExpression */: return getAssignedTypeOfBinaryExpression(parent); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return undefinedType; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return getAssignedTypeOfArrayLiteralElement(parent, node); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return getAssignedTypeOfSpreadExpression(parent); - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return getAssignedTypeOfPropertyAssignment(parent); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getAssignedTypeOfShorthandPropertyAssignment(parent); } - return unknownType; + return errorType; } function getInitialTypeOfBindingElement(node) { var pattern = node.parent; var parentType = getInitialType(pattern.parent); - var type = pattern.kind === 178 /* ObjectBindingPattern */ ? + var type = pattern.kind === 182 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : @@ -36355,35 +41427,35 @@ var ts; if (node.initializer) { return getTypeOfInitializer(node.initializer); } - if (node.parent.parent.kind === 219 /* ForInStatement */) { + if (node.parent.parent.kind === 224 /* ForInStatement */) { return stringType; } - if (node.parent.parent.kind === 220 /* ForOfStatement */) { - return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || unknownType; + if (node.parent.parent.kind === 225 /* ForOfStatement */) { + return checkRightHandSideOfForOf(node.parent.parent.expression, node.parent.parent.awaitModifier) || errorType; } - return unknownType; + return errorType; } function getInitialType(node) { - return node.kind === 230 /* VariableDeclaration */ ? + return node.kind === 235 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node); } function getInitialOrAssignedType(node) { - return node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */ ? + return node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */ ? getInitialType(node) : getAssignedType(node); } function isEmptyArrayAssignment(node) { - return node.kind === 230 /* VariableDeclaration */ && node.initializer && + return node.kind === 235 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral(node.initializer) || - node.kind !== 180 /* BindingElement */ && node.parent.kind === 198 /* BinaryExpression */ && + node.kind !== 184 /* BindingElement */ && node.parent.kind === 202 /* BinaryExpression */ && isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node) { switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return getReferenceCandidate(node.expression); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: switch (node.operatorToken.kind) { case 58 /* EqualsToken */: return getReferenceCandidate(node.left); @@ -36395,43 +41467,36 @@ var ts; } function getReferenceRoot(node) { var parent = node.parent; - return parent.kind === 189 /* ParenthesizedExpression */ || - parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || - parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? + return parent.kind === 193 /* ParenthesizedExpression */ || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */ && parent.left === node || + parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 26 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause) { - if (clause.kind === 264 /* CaseClause */) { - var caseType = getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); - return isUnitType(caseType) ? caseType : undefined; + if (clause.kind === 269 /* CaseClause */) { + return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression)); } return neverType; } function getSwitchClauseTypes(switchStatement) { var links = getNodeLinks(switchStatement); if (!links.switchTypes) { - // If all case clauses specify expressions that have unit types, we return an array - // of those unit types. Otherwise we return an empty array. links.switchTypes = []; for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) { var clause = _a[_i]; - var type = getTypeOfSwitchClause(clause); - if (type === undefined) { - return links.switchTypes = ts.emptyArray; - } - links.switchTypes.push(type); + links.switchTypes.push(getTypeOfSwitchClause(clause)); } } return links.switchTypes; } function eachTypeContainedIn(source, types) { - return source.flags & 131072 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); + return source.flags & 262144 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source); } function isTypeSubsetOf(source, target) { - return source === target || target.flags & 131072 /* Union */ && isTypeSubsetOfUnion(source, target); + return source === target || target.flags & 262144 /* Union */ && isTypeSubsetOfUnion(source, target); } function isTypeSubsetOfUnion(source, target) { - if (source.flags & 131072 /* Union */) { + if (source.flags & 262144 /* Union */) { for (var _i = 0, _a = source.types; _i < _a.length; _i++) { var t = _a[_i]; if (!containsType(target.types, t)) { @@ -36440,30 +41505,27 @@ var ts; } return true; } - if (source.flags & 256 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { + if (source.flags & 512 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) { return true; } return containsType(target.types, source); } function forEachType(type, f) { - return type.flags & 131072 /* Union */ ? ts.forEach(type.types, f) : f(type); + return type.flags & 262144 /* Union */ ? ts.forEach(type.types, f) : f(type); } function filterType(type, f) { - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var types = type.types; var filtered = ts.filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.flags & 67108864 /* UnionOfUnitTypes */); } return f(type) ? type : neverType; } - // Apply a mapping function to a type and return the resulting type. If the source type - // is a union type, the mapping function is applied to each constituent type and a union - // of the resulting types is returned. function mapType(type, mapper, noReductions) { - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { return type; } - if (!(type.flags & 131072 /* Union */)) { + if (!(type.flags & 262144 /* Union */)) { return mapper(type); } var types = type.types; @@ -36493,11 +41555,11 @@ var ts; // typeWithPrimitives have been replaced with occurrences of string literals and numeric // literals in typeWithLiterals, respectively. function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { - if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || - isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* NumberLiteral */)) { return mapType(typeWithPrimitives, function (t) { - return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : - t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 64 /* StringLiteral */) : + t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 128 /* NumberLiteral */) : t; }); } @@ -36532,9 +41594,9 @@ var ts; return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); } function createFinalArrayType(elementType) { - return elementType.flags & 16384 /* Never */ ? + return elementType.flags & 32768 /* Never */ ? autoArrayType : - createArrayType(elementType.flags & 131072 /* Union */ ? + createArrayType(elementType.flags & 262144 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType); } @@ -36552,7 +41614,7 @@ var ts; var hasEvolvingArrayType = false; for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { var t = types_14[_i]; - if (!(t.flags & 16384 /* Never */)) { + if (!(t.flags & 32768 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; } @@ -36574,15 +41636,15 @@ var ts; function isEvolvingArrayOperationTarget(node) { var root = getReferenceRoot(node); var parent = root.parent; - var isLengthPushOrUnshift = parent.kind === 183 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || - parent.parent.kind === 185 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); - var isElementAssignment = parent.kind === 184 /* ElementAccessExpression */ && + var isLengthPushOrUnshift = parent.kind === 187 /* PropertyAccessExpression */ && (parent.name.escapedText === "length" || + parent.parent.kind === 189 /* CallExpression */ && ts.isPushOrUnshiftIdentifier(parent.name)); + var isElementAssignment = parent.kind === 188 /* ElementAccessExpression */ && parent.expression === root && - parent.parent.kind === 198 /* BinaryExpression */ && + parent.parent.kind === 202 /* BinaryExpression */ && parent.parent.operatorToken.kind === 58 /* EqualsToken */ && parent.parent.left === parent && !ts.isAssignmentTarget(parent.parent) && - isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 84 /* NumberLike */); + isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 168 /* NumberLike */); return isLengthPushOrUnshift || isElementAssignment; } function maybeTypePredicateCall(node) { @@ -36597,7 +41659,7 @@ var ts; var funcType = checkNonNullExpression(node.expression); if (funcType !== silentNeverType) { var apparentType = getApparentType(funcType); - return apparentType !== unknownType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); + return apparentType !== errorType && ts.some(getSignaturesOfType(apparentType, 0 /* Call */), signatureHasTypePredicate); } } return false; @@ -36613,9 +41675,9 @@ var ts; var key; var flowDepth = 0; if (flowAnalysisDisabled) { - return unknownType; + return errorType; } - if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 142575359 /* Narrowable */)) { + if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 33492479 /* Narrowable */)) { return declaredType; } var sharedFlowStart = sharedFlowCount; @@ -36626,7 +41688,7 @@ var ts; // on empty arrays are possible without implicit any errors and new element types can be inferred without // type mismatch errors. var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); - if (reference.parent && reference.parent.kind === 207 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 16384 /* Never */) { + if (reference.parent && reference.parent.kind === 211 /* NonNullExpression */ && getTypeWithFacts(resultType, 524288 /* NEUndefinedOrNull */).flags & 32768 /* Never */) { return declaredType; } return resultType; @@ -36636,7 +41698,7 @@ var ts; // and disable further control flow analysis in the containing function or module body. flowAnalysisDisabled = true; reportFlowControlError(reference); - return unknownType; + return errorType; } flowDepth++; while (true) { @@ -36697,7 +41759,7 @@ var ts; else if (flags & 2 /* Start */) { // Check if we should continue with the control flow of the containing function. var container = flow.container; - if (container && container !== flowContainer && reference.kind !== 183 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { + if (container && container !== flowContainer && reference.kind !== 187 /* PropertyAccessExpression */ && reference.kind !== 99 /* ThisKeyword */) { flow = container.flowNode; continue; } @@ -36735,7 +41797,7 @@ var ts; var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; } - if (declaredType.flags & 131072 /* Union */) { + if (declaredType.flags & 262144 /* Union */) { return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); } return declaredType; @@ -36753,7 +41815,7 @@ var ts; function getTypeAtFlowArrayMutation(flow) { if (declaredType === autoType || declaredType === autoArrayType) { var node = flow.node; - var expr = node.kind === 185 /* CallExpression */ ? + var expr = node.kind === 189 /* CallExpression */ ? node.expression.expression : node.left.expression; if (isMatchingReference(reference, getReferenceCandidate(expr))) { @@ -36761,7 +41823,7 @@ var ts; var type = getTypeFromFlowType(flowType); if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) { var evolvedType_1 = type; - if (node.kind === 185 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) { var arg = _a[_i]; evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg); @@ -36769,7 +41831,7 @@ var ts; } else { var indexType = getTypeOfExpression(node.left.argumentExpression); - if (isTypeAssignableToKind(indexType, 84 /* NumberLike */)) { + if (isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right); } } @@ -36783,7 +41845,7 @@ var ts; function getTypeAtFlowCondition(flow) { var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { return flowType; } // If we have an antecedent type (meaning we're reachable in some way), we first @@ -36800,7 +41862,7 @@ var ts; return flowType; } var incomplete = isIncomplete(flowType); - var resultType = incomplete && narrowedType.flags & 16384 /* Never */ ? silentNeverType : narrowedType; + var resultType = incomplete && narrowedType.flags & 32768 /* Never */ ? silentNeverType : narrowedType; return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow) { @@ -36926,8 +41988,8 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - return expr.kind === 183 /* PropertyAccessExpression */ && - computedType.flags & 131072 /* Union */ && + return expr.kind === 187 /* PropertyAccessExpression */ && + computedType.flags & 262144 /* Union */ && isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, expr.name.escapedText); } @@ -36960,7 +42022,7 @@ var ts; return !assumeTrue; } function narrowByInKeyword(type, literal, assumeTrue) { - if ((type.flags & (131072 /* Union */ | 65536 /* Object */)) || (type.flags & 32768 /* TypeParameter */ && type.isThisType)) { + if ((type.flags & (262144 /* Union */ | 131072 /* Object */)) || (type.flags & 65536 /* TypeParameter */ && type.isThisType)) { var propName_1 = ts.escapeLeadingUnderscores(literal.text); return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); }); } @@ -36977,10 +42039,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 193 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { + if (left_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 193 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { + if (right_1.kind === 197 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -37020,24 +42082,24 @@ var ts; assumeTrue = !assumeTrue; } var valueType = getTypeOfExpression(value); - if (valueType.flags & 12288 /* Nullable */) { + if (valueType.flags & 24576 /* Nullable */) { if (!strictNullChecks) { return type; } var doubleEquals = operator === 32 /* EqualsEqualsToken */ || operator === 33 /* ExclamationEqualsToken */; var facts = doubleEquals ? assumeTrue ? 65536 /* EQUndefinedOrNull */ : 524288 /* NEUndefinedOrNull */ : - value.kind === 95 /* NullKeyword */ ? + valueType.flags & 16384 /* Null */ ? assumeTrue ? 32768 /* EQNull */ : 262144 /* NENull */ : assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 134283777 /* NotUnionOrUnit */) { + if (type.flags & 16909315 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 16384 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); + return narrowedType.flags & 32768 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -37059,16 +42121,19 @@ var ts; if (operator === 33 /* ExclamationEqualsToken */ || operator === 35 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } - if (assumeTrue && !(type.flags & 131072 /* Union */)) { + if (type.flags & 1 /* Any */ && literal.text === "function") { + return type; + } + if (assumeTrue && !(type.flags & 262144 /* Union */)) { // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. - var targetType = typeofTypesByName.get(literal.text); + var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); if (targetType) { if (isTypeSubtypeOf(targetType, type)) { return targetType; } - if (type.flags & 7897088 /* Instantiable */) { + if (type.flags & 15794176 /* Instantiable */) { var constraint = getBaseConstraintOfType(type) || anyType; if (isTypeSubtypeOf(targetType, constraint)) { return getIntersectionType([type, targetType]); @@ -37090,13 +42155,13 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 16384 /* Never */ ? neverType : + var caseType = discriminantType.flags & 32768 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); }); - return caseType.flags & 16384 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); + return caseType.flags & 32768 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); @@ -37150,9 +42215,9 @@ var ts; } // If the current type is a union type, remove all constituents that couldn't be instances of // the candidate type. If one or more constituents remain, return a union of those. - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var assignableType = filterType(type, function (t) { return isRelated(t, candidate); }); - if (!(assignableType.flags & 16384 /* Never */)) { + if (!(assignableType.flags & 32768 /* Never */)) { return assignableType; } } @@ -37192,7 +42257,7 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 184 /* ElementAccessExpression */ || invokedExpression.kind === 183 /* PropertyAccessExpression */) { + if (invokedExpression.kind === 188 /* ElementAccessExpression */ || invokedExpression.kind === 187 /* PropertyAccessExpression */) { var accessExpression = invokedExpression; var possibleReference = ts.skipParentheses(accessExpression.expression); if (isMatchingReference(reference, possibleReference)) { @@ -37212,15 +42277,15 @@ var ts; case 71 /* Identifier */: case 99 /* ThisKeyword */: case 97 /* SuperKeyword */: - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return narrowTypeByTruthiness(type, expr, assumeTrue); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return narrowTypeByTypePredicate(type, expr, assumeTrue); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return narrowType(type, expr.expression, assumeTrue); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return narrowTypeByBinaryExpression(type, expr, assumeTrue); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: if (expr.operator === 51 /* ExclamationToken */) { return narrowType(type, expr.operand, !assumeTrue); } @@ -37256,9 +42321,9 @@ var ts; function getControlFlowContainer(node) { return ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || - node.kind === 238 /* ModuleBlock */ || - node.kind === 272 /* SourceFile */ || - node.kind === 151 /* PropertyDeclaration */; + node.kind === 243 /* ModuleBlock */ || + node.kind === 277 /* SourceFile */ || + node.kind === 152 /* PropertyDeclaration */; }); } // Check if a parameter is assigned anywhere within its declaring function. @@ -37280,7 +42345,7 @@ var ts; if (node.kind === 71 /* Identifier */) { if (ts.isAssignmentTarget(node)) { var symbol = getResolvedSymbol(node); - if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 148 /* Parameter */) { + if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 149 /* Parameter */) { symbol.isAssigned = true; } } @@ -37295,28 +42360,28 @@ var ts; /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ function removeOptionalityFromDeclaredType(declaredType, declaration) { var annotationIncludesUndefined = strictNullChecks && - declaration.kind === 148 /* Parameter */ && + declaration.kind === 149 /* Parameter */ && declaration.initializer && - getFalsyFlags(declaredType) & 4096 /* Undefined */ && - !(getFalsyFlags(checkExpression(declaration.initializer)) & 4096 /* Undefined */); + getFalsyFlags(declaredType) & 8192 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 8192 /* Undefined */); return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 131072 /* NEUndefined */) : declaredType; } function isConstraintPosition(node) { var parent = node.parent; - return parent.kind === 183 /* PropertyAccessExpression */ || - parent.kind === 185 /* CallExpression */ && parent.expression === node || - parent.kind === 184 /* ElementAccessExpression */ && parent.expression === node || - parent.kind === 180 /* BindingElement */ && parent.name === node && !!parent.initializer; + return parent.kind === 187 /* PropertyAccessExpression */ || + parent.kind === 189 /* CallExpression */ && parent.expression === node || + parent.kind === 188 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 184 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { - return type.flags & 7372800 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); + return type.flags & 14745600 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 24576 /* Nullable */); } function getConstraintForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - if (isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { + if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getBaseConstraintOrType); } return type; @@ -37329,7 +42394,7 @@ var ts; function checkIdentifier(node) { var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { - return unknownType; + return errorType; } // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -37340,7 +42405,7 @@ var ts; if (symbol === argumentsSymbol) { var container = ts.getContainingFunction(node); if (languageVersion < 2 /* ES2015 */) { - if (container.kind === 191 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } else if (ts.hasModifier(container, 256 /* Async */)) { @@ -37361,7 +42426,7 @@ var ts; // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (declaration.kind === 233 /* ClassDeclaration */ + if (declaration.kind === 238 /* ClassDeclaration */ && ts.nodeIsDecorated(declaration)) { var container = ts.getContainingClass(node); while (container !== undefined) { @@ -37373,14 +42438,14 @@ var ts; container = ts.getContainingClass(container); } } - else if (declaration.kind === 203 /* ClassExpression */) { + else if (declaration.kind === 207 /* ClassExpression */) { // When we emit a class expression with static members that contain a reference // to the constructor in the initializer, we will need to substitute that // binding with an alias as the class name is not in scope. var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - while (container !== undefined) { + while (container.kind !== 277 /* SourceFile */) { if (container.parent === declaration) { - if (container.kind === 151 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { + if (container.kind === 152 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) { getNodeLinks(declaration).flags |= 8388608 /* ClassWithConstructorReference */; getNodeLinks(node).flags |= 16777216 /* ConstructorReferenceInClass */; } @@ -37390,20 +42455,18 @@ var ts; } } } - checkCollisionWithCapturedSuperVariable(node, node); - checkCollisionWithCapturedThisVariable(node, node); - checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { - if (!(localOrExportSymbol.flags & 3 /* Variable */)) { + if (!(localOrExportSymbol.flags & 3 /* Variable */) && + !(ts.isInJavaScriptFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); - return unknownType; + return errorType; } if (isReadonlySymbol(localOrExportSymbol)) { error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(symbol)); - return unknownType; + return errorType; } } var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */; @@ -37426,28 +42489,28 @@ var ts; // The declaration container is the innermost function that encloses the declaration of the variable // or parameter. The flow container is the innermost function starting with which we analyze the control // flow graph to determine the control flow based type. - var isParameter = ts.getRootDeclaration(declaration).kind === 148 /* Parameter */; + var isParameter = ts.getRootDeclaration(declaration).kind === 149 /* Parameter */; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; - var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); + var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. - while (flowContainer !== declarationContainer && (flowContainer.kind === 190 /* FunctionExpression */ || - flowContainer.kind === 191 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && + while (flowContainer !== declarationContainer && (flowContainer.kind === 194 /* FunctionExpression */ || + flowContainer.kind === 195 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || - type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || - isInTypeQuery(node) || node.parent.kind === 250 /* ExportSpecifier */) || - node.parent.kind === 207 /* NonNullExpression */ || - declaration.kind === 230 /* VariableDeclaration */ && declaration.exclamationToken || - declaration.flags & 2097152 /* Ambient */; + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 3 /* AnyOrUnknown */) !== 0 || + isInTypeQuery(node) || node.parent.kind === 255 /* ExportSpecifier */) || + node.parent.kind === 211 /* NonNullExpression */ || + declaration.kind === 235 /* VariableDeclaration */ && declaration.exclamationToken || + declaration.flags & 4194304 /* Ambient */; var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) : type === autoType || type === autoArrayType ? undefinedType : getOptionalType(type); @@ -37464,7 +42527,7 @@ var ts; return convertAutoToAny(flowType); } } - else if (!assumeInitialized && !(getFalsyFlags(type) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { + else if (!assumeInitialized && !(getFalsyFlags(type) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -37477,7 +42540,7 @@ var ts; function checkNestedBlockScopedBinding(node, symbol) { if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || - symbol.valueDeclaration.parent.kind === 267 /* CatchClause */) { + symbol.valueDeclaration.parent.kind === 272 /* CatchClause */) { return; } // 1. walk from the use site up to the declaration and check @@ -37502,8 +42565,8 @@ var ts; } // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement. // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back. - if (container.kind === 218 /* ForStatement */ && - ts.getAncestor(symbol.valueDeclaration, 231 /* VariableDeclarationList */).parent === container && + if (container.kind === 223 /* ForStatement */ && + ts.getAncestor(symbol.valueDeclaration, 236 /* VariableDeclarationList */).parent === container && isAssignedInBodyOfForStatement(node, container)) { getNodeLinks(symbol.valueDeclaration).flags |= 2097152 /* NeedsLoopOutParameter */; } @@ -37517,7 +42580,7 @@ var ts; function isAssignedInBodyOfForStatement(node, container) { // skip parenthesized nodes var current = node; - while (current.parent.kind === 189 /* ParenthesizedExpression */) { + while (current.parent.kind === 193 /* ParenthesizedExpression */) { current = current.parent; } // check if node is used as LHS in some assignment expression @@ -37525,7 +42588,7 @@ var ts; if (ts.isAssignmentTarget(current)) { isAssigned = true; } - else if ((current.parent.kind === 196 /* PrefixUnaryExpression */ || current.parent.kind === 197 /* PostfixUnaryExpression */)) { + else if ((current.parent.kind === 200 /* PrefixUnaryExpression */ || current.parent.kind === 201 /* PostfixUnaryExpression */)) { var expr = current.parent; isAssigned = expr.operator === 43 /* PlusPlusToken */ || expr.operator === 44 /* MinusMinusToken */; } @@ -37538,7 +42601,7 @@ var ts; } function captureLexicalThis(node, container) { getNodeLinks(node).flags |= 2 /* LexicalThis */; - if (container.kind === 151 /* PropertyDeclaration */ || container.kind === 154 /* Constructor */) { + if (container.kind === 152 /* PropertyDeclaration */ || container.kind === 155 /* Constructor */) { var classNode = container.parent; getNodeLinks(classNode).flags |= 4 /* CaptureThis */; } @@ -37583,7 +42646,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(containingClassDecl); + var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -37606,38 +42669,38 @@ var ts; // tell whether 'this' needs to be captured. var container = ts.getThisContainer(node, /* includeArrowFunctions */ true); var needToCaptureLexicalThis = false; - if (container.kind === 154 /* Constructor */) { + if (container.kind === 155 /* Constructor */) { checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class); } // Now skip arrow functions to get the "real" owner of 'this'. - if (container.kind === 191 /* ArrowFunction */) { + if (container.kind === 195 /* ArrowFunction */) { container = ts.getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code needToCaptureLexicalThis = (languageVersion < 2 /* ES2015 */); } switch (container.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks break; - case 154 /* Constructor */: + case 155 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: 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 } break; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); break; } @@ -37658,8 +42721,8 @@ var ts; // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } - if (container.kind === 190 /* FunctionExpression */ && - container.parent.kind === 198 /* BinaryExpression */ && + if (container.kind === 194 /* FunctionExpression */ && + container.parent.kind === 202 /* BinaryExpression */ && ts.getSpecialPropertyAssignmentKind(container.parent) === 3 /* PrototypeProperty */) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') var className = container.parent // x.prototype.y = f @@ -37683,14 +42746,14 @@ var ts; } if (ts.isInJavaScriptFile(node)) { var type = getTypeForThisExpressionFromJSDoc(container); - if (type && type !== unknownType) { + if (type && type !== errorType) { return getFlowTypeOfReference(node, type); } } } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); - if (jsdocType && jsdocType.kind === 280 /* JSDocFunctionType */) { + if (jsdocType && jsdocType.kind === 287 /* JSDocFunctionType */) { var jsDocFunctionType = jsdocType; if (jsDocFunctionType.parameters.length > 0 && jsDocFunctionType.parameters[0].name && @@ -37698,17 +42761,21 @@ var ts; return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type); } } + var thisTag = ts.getJSDocThisTag(node); + if (thisTag && thisTag.typeExpression) { + return getTypeFromTypeNode(thisTag.typeExpression); + } } function isInConstructorArgumentInitializer(node, constructorDecl) { - return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 148 /* Parameter */; }); + return !!ts.findAncestor(node, function (n) { return n === constructorDecl ? "quit" : n.kind === 149 /* Parameter */; }); } function checkSuperExpression(node) { - var isCallExpression = node.parent.kind === 185 /* CallExpression */ && node.parent.expression === node; + var isCallExpression = node.parent.kind === 189 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - while (container && container.kind === 191 /* ArrowFunction */) { + while (container && container.kind === 195 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } @@ -37721,22 +42788,22 @@ var ts; // class B { // [super.foo()]() {} // } - var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 146 /* ComputedPropertyName */; }); - if (current && current.kind === 146 /* ComputedPropertyName */) { + var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 147 /* ComputedPropertyName */; }); + if (current && current.kind === 147 /* ComputedPropertyName */) { error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); } else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } - else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 182 /* ObjectLiteralExpression */)) { + else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions); } else { error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class); } - return unknownType; + return errorType; } - if (!isCallExpression && container.kind === 154 /* Constructor */) { + if (!isCallExpression && container.kind === 155 /* 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.hasModifier(container, 32 /* Static */) || isCallExpression) { @@ -37802,7 +42869,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 === 153 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { + if (container.kind === 154 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) { if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) { getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */; } @@ -37816,10 +42883,10 @@ var ts; // in this case they should also use correct lexical this captureLexicalThis(node.parent, container); } - if (container.parent.kind === 182 /* ObjectLiteralExpression */) { + if (container.parent.kind === 186 /* ObjectLiteralExpression */) { if (languageVersion < 2 /* ES2015 */) { error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); - return unknownType; + return errorType; } else { // for object literal assume that type of 'super' is 'any' @@ -37828,19 +42895,19 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getClassExtendsHeritageClauseElement(classLikeDeclaration)) { + if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); - return unknownType; + return errorType; } var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration)); var baseClassType = classType && getBaseTypes(classType)[0]; if (!baseClassType) { - return unknownType; + return errorType; } - if (container.kind === 154 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { + if (container.kind === 155 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) { // issue custom error message for super property access in constructor arguments (to be aligned with old compiler) error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments); - return unknownType; + return errorType; } return nodeCheckFlag === 512 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) @@ -37852,7 +42919,7 @@ var ts; if (isCallExpression) { // TS 1.0 SPEC (April 2014): 4.8.1 // Super calls are only permitted in constructors of derived classes - return container.kind === 154 /* Constructor */; + return container.kind === 155 /* Constructor */; } else { // TS 1.0 SPEC (April 2014) @@ -37860,21 +42927,21 @@ var ts; // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance // - 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 === 182 /* ObjectLiteralExpression */) { + if (ts.isClassLike(container.parent) || container.parent.kind === 186 /* ObjectLiteralExpression */) { if (ts.hasModifier(container, 32 /* Static */)) { - return container.kind === 153 /* MethodDeclaration */ || - container.kind === 152 /* MethodSignature */ || - container.kind === 155 /* GetAccessor */ || - container.kind === 156 /* SetAccessor */; + return container.kind === 154 /* MethodDeclaration */ || + container.kind === 153 /* MethodSignature */ || + container.kind === 156 /* GetAccessor */ || + container.kind === 157 /* SetAccessor */; } else { - return container.kind === 153 /* MethodDeclaration */ || - container.kind === 152 /* MethodSignature */ || - container.kind === 155 /* GetAccessor */ || - container.kind === 156 /* SetAccessor */ || - container.kind === 151 /* PropertyDeclaration */ || - container.kind === 150 /* PropertySignature */ || - container.kind === 154 /* Constructor */; + return container.kind === 154 /* MethodDeclaration */ || + container.kind === 153 /* MethodSignature */ || + container.kind === 156 /* GetAccessor */ || + container.kind === 157 /* SetAccessor */ || + container.kind === 152 /* PropertyDeclaration */ || + container.kind === 151 /* PropertySignature */ || + container.kind === 155 /* Constructor */; } } } @@ -37882,10 +42949,10 @@ var ts; } } function getContainingObjectLiteral(func) { - return (func.kind === 153 /* MethodDeclaration */ || - func.kind === 155 /* GetAccessor */ || - func.kind === 156 /* SetAccessor */) && func.parent.kind === 182 /* ObjectLiteralExpression */ ? func.parent : - func.kind === 190 /* FunctionExpression */ && func.parent.kind === 268 /* PropertyAssignment */ ? func.parent.parent : + return (func.kind === 154 /* MethodDeclaration */ || + func.kind === 156 /* GetAccessor */ || + func.kind === 157 /* SetAccessor */) && func.parent.kind === 186 /* ObjectLiteralExpression */ ? func.parent : + func.kind === 194 /* FunctionExpression */ && func.parent.kind === 273 /* PropertyAssignment */ ? func.parent.parent : undefined; } function getThisTypeArgument(type) { @@ -37893,11 +42960,11 @@ var ts; } function getThisTypeFromContextualType(type) { return mapType(type, function (t) { - return t.flags & 262144 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); + return t.flags & 524288 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t); }); } function getContextualThisParameterType(func) { - if (func.kind === 191 /* ArrowFunction */) { + if (func.kind === 195 /* ArrowFunction */) { return undefined; } if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { @@ -37924,7 +42991,7 @@ var ts; if (thisType) { return instantiateType(thisType, getContextualMapper(containingLiteral)); } - if (literal.parent.kind !== 268 /* PropertyAssignment */) { + if (literal.parent.kind !== 273 /* PropertyAssignment */) { break; } literal = literal.parent.parent; @@ -37938,9 +43005,9 @@ var ts; // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the // contextual type for 'this' is 'obj'. var parent = func.parent; - if (parent.kind === 198 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { + if (parent.kind === 202 /* BinaryExpression */ && parent.operatorToken.kind === 58 /* EqualsToken */) { var target = parent.left; - if (target.kind === 183 /* PropertyAccessExpression */ || target.kind === 184 /* ElementAccessExpression */) { + if (target.kind === 187 /* PropertyAccessExpression */ || target.kind === 188 /* ElementAccessExpression */) { var expression = target.expression; // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }` if (inJs && ts.isIdentifier(expression)) { @@ -37958,47 +43025,42 @@ var ts; // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter) { var func = parameter.parent; - if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { - var iife = ts.getImmediatelyInvokedFunctionExpression(func); - if (iife && iife.arguments) { - var indexOfParameter = func.parameters.indexOf(parameter); - if (parameter.dotDotDotToken) { - var restTypes = []; - for (var i = indexOfParameter; i < iife.arguments.length; i++) { - restTypes.push(getWidenedLiteralType(checkExpression(iife.arguments[i]))); - } - return restTypes.length ? createArrayType(getUnionType(restTypes)) : undefined; - } - var links = getNodeLinks(iife); - var cached = links.resolvedSignature; - links.resolvedSignature = anySignature; - var type = indexOfParameter < iife.arguments.length ? - getWidenedLiteralType(checkExpression(iife.arguments[indexOfParameter])) : - parameter.initializer ? undefined : undefinedWideningType; - links.resolvedSignature = cached; - return type; + if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + return undefined; + } + var iife = ts.getImmediatelyInvokedFunctionExpression(func); + if (iife && iife.arguments) { + var args = getEffectiveCallArguments(iife); + var indexOfParameter = func.parameters.indexOf(parameter); + if (parameter.dotDotDotToken) { + return getSpreadArgumentType(iife, args, indexOfParameter, args.length, anyType, /*context*/ undefined); } - var contextualSignature = getContextualSignature(func); - if (contextualSignature) { - var funcHasRestParameters = ts.hasRestParameter(func); - var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = func.parameters.indexOf(parameter); - if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { - ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. - indexOfParameter -= 1; - } - if (indexOfParameter < len) { - return getTypeAtPosition(contextualSignature, indexOfParameter); - } - // If last parameter is contextually rest parameter get its type - if (funcHasRestParameters && - indexOfParameter === (func.parameters.length - 1) && - isRestParameterIndex(contextualSignature, func.parameters.length - 1)) { - return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); - } + var links = getNodeLinks(iife); + var cached = links.resolvedSignature; + links.resolvedSignature = anySignature; + var type = indexOfParameter < args.length ? + getWidenedLiteralType(checkExpression(args[indexOfParameter])) : + parameter.initializer ? undefined : undefinedWideningType; + links.resolvedSignature = cached; + return type; + } + var contextualSignature = getContextualSignature(func); + if (contextualSignature) { + var funcHasRestParameter = ts.hasRestParameter(func); + var len = func.parameters.length - (funcHasRestParameter ? 1 : 0); + var indexOfParameter = func.parameters.indexOf(parameter); + if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { + ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. + indexOfParameter -= 1; + } + if (indexOfParameter < len) { + return getTypeAtPosition(contextualSignature, indexOfParameter); + } + // If last parameter is contextually rest parameter get its type + if (funcHasRestParameter && indexOfParameter === len) { + return getRestTypeAtPosition(contextualSignature, indexOfParameter); } } - return undefined; } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. @@ -38015,7 +43077,7 @@ var ts; if (typeNode) { return getTypeFromTypeNode(typeNode); } - if (declaration.kind === 148 /* Parameter */) { + if (declaration.kind === 149 /* Parameter */) { var type = getContextuallyTypedParameterType(declaration); if (type) { return type; @@ -38027,7 +43089,7 @@ var ts; if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 180 /* BindingElement */) { + if (parentDeclaration.kind !== 184 /* BindingElement */) { var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); if (parentTypeNode && !ts.isBindingPattern(name)) { var text = ts.getTextOfPropertyName(name); @@ -38083,7 +43145,7 @@ var ts; function getContextualReturnType(functionDecl) { // If the containing function has a return type annotation, is a constructor, or is a get accessor whose // corresponding set accessor has a type annotation, return statements in the function are contextually typed - if (functionDecl.kind === 154 /* Constructor */ || + if (functionDecl.kind === 155 /* Constructor */ || ts.getEffectiveReturnTypeNode(functionDecl) || isGetAccessorWithAnnotatedSetAccessor(functionDecl)) { return getReturnTypeOfSignature(getSignatureFromDeclaration(functionDecl)); @@ -38098,7 +43160,7 @@ var ts; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { - var args = getEffectiveCallArguments(callTarget); + var args = getEffectiveCallArguments(callTarget); // TODO: GH#18217 var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); } @@ -38109,7 +43171,7 @@ var ts; return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { - if (template.parent.kind === 187 /* TaggedTemplateExpression */) { + if (template.parent.kind === 191 /* TaggedTemplateExpression */) { return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -38125,8 +43187,8 @@ var ts; // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` var type = getContextualType(binaryExpression); - return !type && node === right && !ts.getDeclaredJavascriptInitializer(binaryExpression.parent) && !ts.getAssignedJavascriptInitializer(binaryExpression) ? - getTypeOfExpression(left, /*cache*/ true) : type; + return !type && node === right && !ts.isDefaultedJavascriptInitializer(binaryExpression) ? + getTypeOfExpression(left) : type; case 53 /* AmpersandAmpersandToken */: case 26 /* CommaToken */: return node === right ? getContextualType(binaryExpression) : undefined; @@ -38152,13 +43214,24 @@ var ts; case 6 /* Prototype */: return false; default: - ts.Debug.assertNever(kind); + return ts.Debug.assertNever(kind); } } function getTypeOfPropertyOfContextualType(type, name) { return mapType(type, function (t) { - var prop = t.flags & 458752 /* StructuredType */ ? getPropertyOfType(t, name) : undefined; - return prop ? getTypeOfSymbol(prop) : undefined; + if (t.flags & 917504 /* StructuredType */) { + var prop = getPropertyOfType(t, name); + if (prop) { + return getTypeOfSymbol(prop); + } + if (isTupleType(t)) { + var restType = getRestTypeOfTupleType(t); + if (restType && isNumericLiteralName(name) && +name >= 0) { + return restType; + } + } + } + return undefined; }, /*noReductions*/ true); } function getIndexTypeOfContextualType(type, kind) { @@ -38166,14 +43239,14 @@ var ts; } // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 131072 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); + return !!(type.flags & 262144 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one // exists. Otherwise, it is the type of the string index signature in T, if one exists. function getContextualTypeForObjectLiteralMethod(node) { ts.Debug.assert(ts.isObjectLiteralMethod(node)); - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -38187,8 +43260,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - var symbolName_1 = getSymbolOfNode(element).escapedName; - var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_1); + var symbolName_3 = getSymbolOfNode(element).escapedName; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3); if (propertyType) { return propertyType; } @@ -38241,12 +43314,31 @@ var ts; return getContextualType(attribute.parent); } } + // Return true if the given expression is possibly a discriminant value. We limit the kinds of + // expressions we check to those that don't depend on their contextual type in order not to cause + // recursive (and possibly infinite) invocations of getContextualType. + function isPossiblyDiscriminantValue(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 8 /* NumericLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 101 /* TrueKeyword */: + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 71 /* Identifier */: + return true; + case 187 /* PropertyAccessExpression */: + case 193 /* ParenthesizedExpression */: + return isPossiblyDiscriminantValue(node.expression); + } + return false; + } // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getApparentTypeOfContextualType(node) { var contextualType = getContextualType(node); contextualType = contextualType && mapType(contextualType, getApparentType); - if (!(contextualType && contextualType.flags & 131072 /* Union */ && ts.isObjectLiteralExpression(node))) { + if (!(contextualType && contextualType.flags & 262144 /* Union */ && ts.isObjectLiteralExpression(node))) { return contextualType; } // Keep the below up-to-date with the work done within `isRelatedTo` by `findMatchingDiscriminantType` @@ -38255,14 +43347,14 @@ var ts; var prop = _a[_i]; if (!prop.symbol) continue; - if (prop.kind !== 268 /* PropertyAssignment */) + if (prop.kind !== 273 /* PropertyAssignment */) continue; - if (isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { - var discriminatingType = getTypeOfNode(prop.initializer); + if (isPossiblyDiscriminantValue(prop.initializer) && isDiscriminantProperty(contextualType, prop.symbol.escapedName)) { + var discriminatingType = checkExpression(prop.initializer); for (var _b = 0, _c = contextualType.types; _b < _c.length; _b++) { var type = _c[_b]; var targetType = getTypeOfPropertyOfType(type, prop.symbol.escapedName); - if (targetType && checkTypeAssignableTo(discriminatingType, targetType, /*errorNode*/ undefined)) { + if (targetType && isTypeAssignableTo(discriminatingType, targetType)) { if (match) { if (type === match) continue; // Finding multiple fields which discriminate to the same type is fine @@ -38294,7 +43386,7 @@ var ts; * @returns the contextual type of an expression. */ function getContextualType(node) { - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } @@ -38303,59 +43395,59 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 180 /* BindingElement */: + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 184 /* BindingElement */: return getContextualTypeForInitializerExpression(node); - case 191 /* ArrowFunction */: - case 223 /* ReturnStatement */: + case 195 /* ArrowFunction */: + case 228 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return getContextualTypeForYieldOperand(parent); - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: return getContextualTypeForArgument(parent, node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return getTypeFromTypeNode(parent.type); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return getContextualTypeForBinaryOperand(node); - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return getContextualTypeForObjectLiteralElement(parent); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return getApparentTypeOfContextualType(parent.parent); - case 181 /* ArrayLiteralExpression */: { + case 185 /* ArrayLiteralExpression */: { var arrayLiteral = parent; var type = getApparentTypeOfContextualType(arrayLiteral); return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node)); } - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); - case 209 /* TemplateSpan */: - ts.Debug.assert(parent.parent.kind === 200 /* TemplateExpression */); + case 214 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 204 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); - case 189 /* ParenthesizedExpression */: { + case 193 /* ParenthesizedExpression */: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. var tag = ts.isInJavaScriptFile(parent) ? ts.getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent); } - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return getContextualTypeForJsxExpression(parent); - case 260 /* JsxAttribute */: - case 262 /* JsxSpreadAttribute */: + case 265 /* JsxAttribute */: + case 267 /* JsxSpreadAttribute */: return getContextualTypeForJsxAttribute(parent); - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: return getContextualJsxElementAttributesType(parent); } return undefined; } function getContextualMapper(node) { - node = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); - return node ? node.contextualMapper : identityMapper; + var ancestor = ts.findAncestor(node, function (n) { return !!n.contextualMapper; }); + return ancestor ? ancestor.contextualMapper : identityMapper; } function getContextualJsxElementAttributesType(node) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -38371,16 +43463,16 @@ var ts; } function getJsxSignaturesParameterTypes(valueType, isJs, context) { // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (valueType.flags & 2 /* String */) { + if (valueType.flags & 4 /* String */) { return anyType; } - else if (valueType.flags & 32 /* StringLiteral */) { + else if (valueType.flags & 64 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, context); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { var stringLiteralTypeName = valueType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { @@ -38402,67 +43494,93 @@ var ts; ctor = false; if (signatures.length === 0) { // We found no signatures at all, which is an error - return unknownType; + return errorType; } } - return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromConstructSignature(t, isJs, context); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); + var links = getNodeLinks(context); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(valueType); + var cachedResolved = links.resolvedSignatures.get(cacheKey); + if (cachedResolved && cachedResolved !== resolvingSignaturesArray) { + signatures = cachedResolved; + } + else if (!cachedResolved) { + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + links.resolvedSignatures.set(cacheKey, signatures = instantiateJsxSignatures(context, signatures)); + } + return getUnionType(ts.map(signatures, ctor ? function (t) { return getJsxPropsTypeFromClassType(t, isJs, context, /*reportErrors*/ false); } : function (t) { return getJsxPropsTypeFromCallSignature(t, context); }), 0 /* None */); } function getJsxPropsTypeFromCallSignature(sig, context) { - var propsType = getTypeOfFirstParameterOfSignature(sig); + var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType); + propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType); var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); - if (intrinsicAttribs !== unknownType) { + if (intrinsicAttribs !== errorType) { propsType = intersectTypes(intrinsicAttribs, propsType); } return propsType; } - function getJsxPropsTypeFromClassType(hostClassType, isJs, context) { - if (isTypeAny(hostClassType)) { - return hostClassType; + function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + var instanceType = getReturnTypeOfSignature(sig); + return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); + } + function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { + var managedSym = getJsxLibraryManagedAttributes(ns); + if (managedSym) { + var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (ts.length(declaredManagedType.typeParameters) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.typeParameters, 2, ts.isInJavaScriptFile(context)); + return createTypeReference(declaredManagedType, args); + } + else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) { + var args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJavaScriptFile(context)); + return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args); + } } - var propsName = getJsxElementPropertiesName(getJsxNamespaceAt(context)); - if (propsName === undefined) { - // There is no type ElementAttributesProperty, return 'any' - return anyType; + return attributesType; + } + function getJsxPropsTypeFromClassType(sig, isJs, context, reportErrors) { + var ns = getJsxNamespaceAt(context); + var forcedLookupLocation = getJsxElementPropertiesName(ns); + var attributesType = forcedLookupLocation === undefined + // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type + ? getTypeOfFirstParameterOfSignatureWithFallback(sig, emptyObjectType) + : forcedLookupLocation === "" + // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead + ? getReturnTypeOfSignature(sig) + // Otherwise get the type of the property on the signature return type + : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation); + if (!attributesType) { + // There is no property named 'props' on this instance type + if (reportErrors && !!forcedLookupLocation && !!ts.length(context.attributes.properties)) { + error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation)); + } + return emptyObjectType; } - else if (propsName === "") { - // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead - return hostClassType; + attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType); + if (isTypeAny(attributesType)) { + // Props is of type 'any' or unknown + return attributesType; } else { - var attributesType = getTypeOfPropertyOfType(hostClassType, propsName); - if (!attributesType) { - // There is no property named 'props' on this instance type - return emptyObjectType; + // Normal case -- add in IntrinsicClassElements and IntrinsicElements + var apparentAttributesType = attributesType; + var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); + if (intrinsicClassAttribs !== errorType) { + var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); + var hostClassType = getReturnTypeOfSignature(sig); + apparentAttributesType = intersectTypes(typeParams + ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) + : intrinsicClassAttribs, apparentAttributesType); } - else if (isTypeAny(attributesType)) { - // Props is of type 'any' or unknown - return attributesType; - } - else { - // Normal case -- add in IntrinsicClassElements and IntrinsicElements - var apparentAttributesType = attributesType; - var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context); - if (intrinsicClassAttribs !== unknownType) { - var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol); - apparentAttributesType = intersectTypes(typeParams - ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isJs)) - : intrinsicClassAttribs, apparentAttributesType); - } - var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); - if (intrinsicAttribs !== unknownType) { - apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); - } - return apparentAttributesType; + var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); + if (intrinsicAttribs !== errorType) { + apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType); } + return apparentAttributesType; } } - function getJsxPropsTypeFromConstructSignature(sig, isJs, context) { - var hostClassType = getReturnTypeOfSignature(sig); - if (hostClassType) { - return getJsxPropsTypeFromClassType(hostClassType, isJs, context); - } - return getJsxPropsTypeFromCallSignature(sig, context); - } // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { @@ -38486,11 +43604,10 @@ var ts; if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) { targetParameterCount--; } - var sourceLength = signature.hasRestParameter ? Number.MAX_VALUE : signature.parameters.length; - return sourceLength < targetParameterCount; + return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount; } function isFunctionExpressionOrArrowFunction(node) { - return node.kind === 190 /* FunctionExpression */ || node.kind === 191 /* ArrowFunction */; + return node.kind === 194 /* FunctionExpression */ || node.kind === 195 /* ArrowFunction */; } function getContextualSignatureForFunctionLikeDeclaration(node) { // Only function expressions, arrow functions, and object literal methods are contextually typed. @@ -38509,12 +43626,21 @@ var ts; // all identical ignoring their return type, the result is same signature but with return type as // union type of return types from these signatures function getContextualSignature(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var type = getContextualTypeForFunctionLikeDeclaration(node); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var type; + if (ts.isInJavaScriptFile(node)) { + var jsdoc = ts.getJSDocType(node); + if (jsdoc) { + type = getTypeFromTypeNode(jsdoc); + } + } + if (!type) { + type = getContextualTypeForFunctionLikeDeclaration(node); + } if (!type) { return undefined; } - if (!(type.flags & 131072 /* Union */)) { + if (!(type.flags & 262144 /* Union */)) { return getContextualCallSignature(type, node); } var signatureList; @@ -38553,18 +43679,19 @@ var ts; return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false, /*allowAsyncIterables*/ false); } function hasDefaultValue(node) { - return (node.kind === 180 /* BindingElement */ && !!node.initializer) || - (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); + return (node.kind === 184 /* BindingElement */ && !!node.initializer) || + (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 58 /* EqualsToken */); } function checkArrayLiteral(node, checkMode) { var elements = node.elements; - var hasSpreadElement = false; + var elementCount = elements.length; + var hasNonEndingSpreadElement = false; var elementTypes = []; var inDestructuringPattern = ts.isAssignmentTarget(node); var contextualType = getApparentTypeOfContextualType(node); - for (var index = 0; index < elements.length; index++) { + for (var index = 0; index < elementCount; index++) { var e = elements[index]; - if (inDestructuringPattern && e.kind === 202 /* SpreadElement */) { + if (inDestructuringPattern && e.kind === 206 /* SpreadElement */) { // Given the following situation: // var c: {}; // [...c] = ["", 0]; @@ -38589,13 +43716,17 @@ var ts; var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType); elementTypes.push(type); } - hasSpreadElement = hasSpreadElement || e.kind === 202 /* SpreadElement */; + if (index < elementCount - 1 && e.kind === 206 /* SpreadElement */) { + hasNonEndingSpreadElement = true; + } } - if (!hasSpreadElement) { + if (!hasNonEndingSpreadElement) { + var hasRestElement = elementCount > 0 && elements[elementCount - 1].kind === 206 /* SpreadElement */; + var minLength = elementCount - (hasRestElement ? 1 : 0); // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". - if (inDestructuringPattern && elementTypes.length) { - var type = cloneTypeReference(createTupleType(elementTypes)); + if (inDestructuringPattern && minLength > 0) { + var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasRestElement)); type.pattern = node; return type; } @@ -38603,33 +43734,35 @@ var ts; var pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. - if (pattern && (pattern.kind === 179 /* ArrayBindingPattern */ || pattern.kind === 181 /* ArrayLiteralExpression */)) { + if (!hasRestElement && pattern && (pattern.kind === 183 /* ArrayBindingPattern */ || pattern.kind === 185 /* ArrayLiteralExpression */)) { var patternElements = pattern.elements; - for (var i = elementTypes.length; i < patternElements.length; i++) { - var patternElement = patternElements[i]; - if (hasDefaultValue(patternElement)) { + for (var i = elementCount; i < patternElements.length; i++) { + var e = patternElements[i]; + if (hasDefaultValue(e)) { elementTypes.push(contextualType.typeArguments[i]); } - else { - if (patternElement.kind !== 204 /* OmittedExpression */) { - error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); + else if (i < patternElements.length - 1 || !(e.kind === 184 /* BindingElement */ && e.dotDotDotToken || e.kind === 206 /* SpreadElement */)) { + if (e.kind !== 208 /* OmittedExpression */) { + error(e, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } - if (elementTypes.length) { - return createTupleType(elementTypes); - } + return createTupleType(elementTypes, minLength, hasRestElement); } } + return getArrayLiteralType(elementTypes, 2 /* Subtype */); + } + function getArrayLiteralType(elementTypes, unionReduction) { + if (unionReduction === void 0) { unionReduction = 1 /* Literal */; } return createArrayType(elementTypes.length ? - getUnionType(elementTypes, 2 /* Subtype */) : + getUnionType(elementTypes, unionReduction) : strictNullChecks ? implicitNeverType : undefinedWideningType); } function isNumericName(name) { switch (name.kind) { - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return isNumericComputedName(name); case 71 /* Identifier */: return isNumericLiteralName(name.escapedText); @@ -38643,7 +43776,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 isTypeAssignableToKind(checkComputedPropertyName(name), 84 /* NumberLike */); + return isTypeAssignableToKind(checkComputedPropertyName(name), 168 /* NumberLike */); } function isInfinityOrNaNString(name) { return name === "Infinity" || name === "-Infinity" || name === "NaN"; @@ -38678,9 +43811,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 (links.resolvedType.flags & 12288 /* Nullable */ || - !isTypeAssignableToKind(links.resolvedType, 524322 /* StringLike */ | 84 /* NumberLike */ | 1536 /* ESSymbolLike */) && - !isTypeAssignableTo(links.resolvedType, getUnionType([stringType, numberType, esSymbolType]))) { + if (links.resolvedType.flags & 24576 /* Nullable */ || + !isTypeAssignableToKind(links.resolvedType, 68 /* StringLike */ | 168 /* NumberLike */ | 3072 /* ESSymbolLike */) && + !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) { error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any); } else { @@ -38706,79 +43839,53 @@ var ts; var propertiesTable; var propertiesArray = []; var spread = emptyObjectType; - var propagatedFlags = 8388608 /* FreshLiteral */; + var propagatedFlags = 33554432 /* FreshLiteral */; var contextualType = getApparentTypeOfContextualType(node); var contextualTypeHasPattern = contextualType && contextualType.pattern && - (contextualType.pattern.kind === 178 /* ObjectBindingPattern */ || contextualType.pattern.kind === 182 /* ObjectLiteralExpression */); - var isInJSFile = ts.isInJavaScriptFile(node); + (contextualType.pattern.kind === 182 /* ObjectBindingPattern */ || contextualType.pattern.kind === 186 /* ObjectLiteralExpression */); + var isInJSFile = ts.isInJavaScriptFile(node) && !ts.isInJsonFile(node); var isJSObjectLiteral = !contextualType && isInJSFile; var typeFlags = 0; var patternWithComputedProperties = false; var hasComputedStringProperty = false; var hasComputedNumberProperty = false; - if (isInJSFile && node.properties.length === 0) { - // an empty JS object literal that nonetheless has members is a JS namespace - var symbol = getSymbolOfNode(node); - if (symbol.exports) { - propertiesTable = symbol.exports; - symbol.exports.forEach(function (symbol) { return propertiesArray.push(getMergedSymbol(symbol)); }); - return createObjectLiteralType(); - } - } propertiesTable = ts.createSymbolTable(); var offset = 0; for (var i = 0; i < node.properties.length; i++) { var memberDecl = node.properties[i]; var member = getSymbolOfNode(memberDecl); - var literalName = void 0; - if (memberDecl.kind === 268 /* PropertyAssignment */ || - memberDecl.kind === 269 /* ShorthandPropertyAssignment */ || + var computedNameType = memberDecl.name && memberDecl.name.kind === 147 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ? + checkComputedPropertyName(memberDecl.name) : undefined; + if (memberDecl.kind === 273 /* PropertyAssignment */ || + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { - var jsdocType = void 0; + var type = memberDecl.kind === 273 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : + memberDecl.kind === 274 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : + checkObjectLiteralMethod(memberDecl, checkMode); if (isInJSFile) { - jsdocType = getTypeForDeclarationFromJSDocComment(memberDecl); - } - var type = void 0; - if (memberDecl.kind === 268 /* PropertyAssignment */) { - if (memberDecl.name.kind === 146 /* ComputedPropertyName */) { - var t = checkComputedPropertyName(memberDecl.name); - if (t.flags & 224 /* Literal */) { - literalName = ts.escapeLeadingUnderscores("" + t.value); - } + var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); + if (jsDocType) { + checkTypeAssignableTo(type, jsDocType, memberDecl); + type = jsDocType; } - type = checkPropertyAssignment(memberDecl, checkMode); - } - else if (memberDecl.kind === 153 /* MethodDeclaration */) { - type = checkObjectLiteralMethod(memberDecl, checkMode); - } - else { - ts.Debug.assert(memberDecl.kind === 269 /* ShorthandPropertyAssignment */); - type = checkExpressionForMutableLocation(memberDecl.name, checkMode); - } - if (jsdocType) { - checkTypeAssignableTo(type, jsdocType, memberDecl); - type = jsdocType; } typeFlags |= type.flags; - var nameType = hasLateBindableName(memberDecl) ? checkComputedPropertyName(memberDecl.name) : undefined; - var hasLateBoundName = nameType && isTypeUsableAsLateBoundName(nameType); - var prop = hasLateBoundName - ? createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) - : createSymbol(4 /* Property */ | member.flags, literalName || member.escapedName); - if (hasLateBoundName) { + var nameType = computedNameType && computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */ ? + computedNameType : undefined; + var prop = nameType ? + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, member.escapedName); + if (nameType) { prop.nameType = nameType; } if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. - var isOptional = (memberDecl.kind === 268 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || - (memberDecl.kind === 269 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); + var isOptional = (memberDecl.kind === 273 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || + (memberDecl.kind === 274 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { prop.flags |= 16777216 /* Optional */; } - if (!literalName && ts.hasDynamicName(memberDecl)) { - patternWithComputedProperties = true; - } } else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the @@ -38800,7 +43907,7 @@ var ts; prop.target = member; member = prop; } - else if (memberDecl.kind === 270 /* SpreadAssignment */) { + else if (memberDecl.kind === 275 /* SpreadAssignment */) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } @@ -38815,7 +43922,7 @@ var ts; var type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return unknownType; + return errorType; } spread = getSpreadType(spread, type, node.symbol, propagatedFlags, /*objectFlags*/ 0); offset = i + 1; @@ -38827,15 +43934,20 @@ var ts; // an ordinary function declaration(section 6.1) with no parameters. // A set accessor declaration is processed in the same manner // as an ordinary function declaration with a single parameter and a Void return type. - ts.Debug.assert(memberDecl.kind === 155 /* GetAccessor */ || memberDecl.kind === 156 /* SetAccessor */); + ts.Debug.assert(memberDecl.kind === 156 /* GetAccessor */ || memberDecl.kind === 157 /* SetAccessor */); checkNodeDeferred(memberDecl); } - if (!literalName && hasNonBindableDynamicName(memberDecl)) { - if (isNumericName(memberDecl.name)) { - hasComputedNumberProperty = true; - } - else { - hasComputedStringProperty = true; + if (computedNameType && !(computedNameType.flags & 2240 /* StringOrNumberLiteralOrUnique */)) { + if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) { + if (isTypeAssignableTo(computedNameType, numberType)) { + hasComputedNumberProperty = true; + } + else { + hasComputedStringProperty = true; + } + if (inDestructuringPattern) { + patternWithComputedProperties = true; + } } } else { @@ -38868,8 +43980,8 @@ var ts; var stringIndexInfo = isJSObjectLiteral ? jsObjectLiteralIndexInfo : hasComputedStringProperty ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 0 /* String */) : undefined; var numberIndexInfo = hasComputedNumberProperty && !isJSObjectLiteral ? getObjectLiteralIndexInfo(node.properties, offset, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 8388608 /* FreshLiteral */; - result.flags |= 33554432 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 117440512 /* PropagatingFlags */); + var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 33554432 /* FreshLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 939524096 /* PropagatingFlags */); result.objectFlags |= 128 /* ObjectLiteral */; if (patternWithComputedProperties) { result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */; @@ -38877,25 +43989,28 @@ var ts; if (inDestructuringPattern) { result.pattern = node; } - if (!(result.flags & 12288 /* Nullable */)) { - propagatedFlags |= (result.flags & 117440512 /* PropagatingFlags */); + if (!(result.flags & 24576 /* Nullable */)) { + propagatedFlags |= (result.flags & 939524096 /* PropagatingFlags */); } return result; } } function isValidSpreadType(type) { - return !!(type.flags & (1 /* Any */ | 134217728 /* NonPrimitive */) || - getFalsyFlags(type) & 14560 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 65536 /* Object */ && !isGenericMappedType(type) || - type.flags & 393216 /* UnionOrIntersection */ && !ts.forEach(type.types, function (t) { return !isValidSpreadType(t); })); + return !!(type.flags & (3 /* AnyOrUnknown */ | 16777216 /* NonPrimitive */) || + getFalsyFlags(type) & 29120 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || + type.flags & 131072 /* Object */ && !isGenericMappedType(type) || + type.flags & 786432 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); } - function checkJsxSelfClosingElement(node, checkMode) { - checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode); + function checkJsxSelfClosingElementDeferred(node) { + checkJsxOpeningLikeElementOrOpeningFragment(node, 0 /* Normal */); + } + function checkJsxSelfClosingElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } - function checkJsxElement(node, checkMode) { + function checkJsxElementDeferred(node) { // Check attributes - checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, checkMode); + checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement, 0 /* Normal */); // Perform resolution on the closing tag so that rename/go to definition/etc work if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) { getIntrinsicTagSymbol(node.closingElement); @@ -38903,6 +44018,9 @@ var ts; else { checkExpression(node.closingElement.tagName); } + } + function checkJsxElement(node, _checkMode) { + checkNodeDeferred(node); return getJsxElementTypeAt(node) || anyType; } function checkJsxFragment(node, checkMode) { @@ -38925,16 +44043,7 @@ var ts; * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name */ function isJsxIntrinsicIdentifier(tagName) { - // TODO (yuisu): comment - switch (tagName.kind) { - case 183 /* PropertyAccessExpression */: - case 99 /* ThisKeyword */: - return false; - case 71 /* Identifier */: - return ts.isIntrinsicJsxName(tagName.escapedText); - default: - ts.Debug.fail(); - } + return tagName.kind === 71 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText); } function checkJsxAttribute(node, checkMode) { return node.initializer @@ -38977,7 +44086,7 @@ var ts; } } else { - ts.Debug.assert(attributeDecl.kind === 262 /* JsxSpreadAttribute */); + ts.Debug.assert(attributeDecl.kind === 267 /* JsxSpreadAttribute */); if (attributesTable.size > 0) { spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, 4096 /* JsxAttributes */); attributesTable = ts.createSymbolTable(); @@ -39000,7 +44109,7 @@ var ts; } } // Handle children attribute - var parent = openingLikeElement.parent.kind === 253 /* JsxElement */ ? openingLikeElement.parent : undefined; + var parent = openingLikeElement.parent.kind === 258 /* JsxElement */ ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { var childrenTypes = checkJsxChildren(parent, checkMode); @@ -39024,7 +44133,10 @@ var ts; if (hasSpreadAnyType) { return anyType; } - return typeToIntersect && spread !== emptyObjectType ? getIntersectionType([typeToIntersect, spread]) : (typeToIntersect || spread); + if (typeToIntersect && spread !== emptyObjectType) { + return getIntersectionType([typeToIntersect, spread]); + } + return typeToIntersect || (spread === emptyObjectType ? createJsxAttributesType() : spread); /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -39032,7 +44144,7 @@ var ts; */ function createJsxAttributesType() { var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= 33554432 /* ContainsObjectLiteral */; + result.flags |= 268435456 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */ | 4096 /* JsxAttributes */; return result; } @@ -39066,7 +44178,7 @@ var ts; var namespace = getJsxNamespaceAt(location); var exports = namespace && getExportsOfSymbol(namespace); var typeSymbol = exports && getSymbol(exports, name, 67901928 /* Type */); - return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : unknownType; + return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType; } /** * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic @@ -39078,7 +44190,7 @@ var ts; var links = getNodeLinks(node); if (!links.resolvedSymbol) { var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { // Property case if (!ts.isIdentifier(node.tagName)) return ts.Debug.fail(); @@ -39106,55 +44218,80 @@ var ts; } return links.resolvedSymbol; } - /** - * Given a JSX element that is a class element, finds the Element Instance Type. If the - * element is not a class element, or the class element type cannot be determined, returns 'undefined'. - * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). - */ - function getJsxElementInstanceType(node, valueType) { - ts.Debug.assert(!(valueType.flags & 131072 /* Union */)); - if (isTypeAny(valueType)) { - // Short-circuit if the class tag is using an element type 'any' - return anyType; - } - // Resolve the signatures, preferring constructor - var signatures = getSignaturesOfType(valueType, 1 /* Construct */); - if (signatures.length === 0) { - // No construct signatures, try call signatures - signatures = getSignaturesOfType(valueType, 0 /* Call */); - if (signatures.length === 0) { - // We found no signatures at all, which is an error - error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName)); - return unknownType; - } - } - // Instantiate in context of source type + function instantiateJsxSignatures(node, signatures) { var instantiatedSignatures = []; + var candidateForTypeArgumentError; + var hasTypeArgumentError = !!node.typeArguments; for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); - var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); - var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); - instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + var typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); + if (typeArgumentInstantiated) { + hasTypeArgumentError = false; + instantiatedSignatures.push(typeArgumentInstantiated); + } + else { + if (node.typeArguments && hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + candidateForTypeArgumentError = signature; + } + var inferenceContext = createInferenceContext(signature.typeParameters, signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0 /* None */); + var typeArguments = inferJsxTypeArguments(signature, node, inferenceContext); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments, isJavascript)); + } } else { instantiatedSignatures.push(signature); } } - return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), 2 /* Subtype */); + if (node.typeArguments && hasTypeArgumentError) { + if (candidateForTypeArgumentError) { + checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true); + } + // Length check to avoid issuing an arity error on length=0, the "Type argument list cannot be empty" grammar error alone is fine + else if (node.typeArguments.length !== 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, node.typeArguments)); + } + } + return instantiatedSignatures; + } + function getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, reportErrors) { + if (reportErrors === void 0) { reportErrors = false; } + if (!node.typeArguments) { + return; + } + if (!hasCorrectTypeArgumentArity(signature, node.typeArguments)) { + return; + } + var args = checkTypeArguments(signature, node.typeArguments, reportErrors); + if (!args) { + return; + } + return getSignatureInstantiation(signature, args, isJavascript); } function getJsxNamespaceAt(location) { - var namespaceName = getJsxNamespace(location); - var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); - if (resolvedNamespace) { - var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); - if (candidate) { - return candidate; + var links = location && getNodeLinks(location); + if (links && links.jsxNamespace) { + return links.jsxNamespace; + } + if (!links || links.jsxNamespace !== false) { + var namespaceName = getJsxNamespace(location); + var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); + if (resolvedNamespace) { + var candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */); + if (candidate) { + if (links) { + links.jsxNamespace = candidate; + } + return candidate; + } + if (links) { + links.jsxNamespace = false; + } } } // JSX global fallback - return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); + return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217 } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -39187,6 +44324,10 @@ var ts; } return undefined; } + function getJsxLibraryManagedAttributes(jsxNamespace) { + // JSX.LibraryManagedAttributes [symbol] + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 67901928 /* Type */); + } /// e.g. "props" for React.d.ts, /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all /// non-intrinsic elements' attributes type is 'any'), @@ -39202,7 +44343,7 @@ var ts; if (!propsType) { return undefined; } - if (propsType.flags & 262144 /* Intersection */) { + if (propsType.flags & 524288 /* Intersection */) { var propsApparentType = []; for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { var t = _a[_i]; @@ -39223,7 +44364,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); if (jsxStatelessElementType) { @@ -39236,7 +44377,7 @@ var ts; if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== unknownType) { + if (intrinsicAttributes !== errorType) { paramType = intersectTypes(intrinsicAttributes, paramType); } return paramType; @@ -39257,7 +44398,7 @@ var ts; * @param elementClassType a JSX-ElementClass type. This is a result of looking up ElementClass interface in the JSX global */ function tryGetAllJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { // Is this is a stateless function component? See if its single signature's return type is assignable to the JSX Element Type var jsxStatelessElementType = getJsxStatelessElementTypeAt(openingLikeElement); @@ -39270,6 +44411,7 @@ var ts; for (var _i = 0, candidatesOutArray_1 = candidatesOutArray; _i < candidatesOutArray_1.length; _i++) { var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); + // TODO: GH#18217: callReturnType should always be defined... var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { @@ -39278,7 +44420,7 @@ var ts; var attribute = _b[_a]; if (ts.isJsxAttribute(attribute) && isUnhyphenatedJsxName(attribute.name.escapedText) && - !getPropertyOfType(paramType, attribute.name.escapedText)) { + !getPropertyOfType(paramType, attribute.name.escapedText)) { // TODO: GH#18217 shouldBeCandidate = false; break; } @@ -39295,7 +44437,7 @@ var ts; } // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, openingLikeElement); - if (intrinsicAttributes !== unknownType) { + if (intrinsicAttributes !== errorType) { result = intersectTypes(intrinsicAttributes, result); } return result; @@ -39303,6 +44445,37 @@ var ts; } return undefined; } + function getInstantiatedJsxSignatures(openingLikeElement, elementType, reportErrors) { + var links = getNodeLinks(openingLikeElement); + if (!links.resolvedSignatures) { + links.resolvedSignatures = ts.createMap(); + } + var cacheKey = "" + getTypeId(elementType); + if (links.resolvedSignatures.get(cacheKey) && links.resolvedSignatures.get(cacheKey) === resolvingSignaturesArray) { + return; + } + else if (links.resolvedSignatures.get(cacheKey)) { + return links.resolvedSignatures.get(cacheKey); + } + links.resolvedSignatures.set(cacheKey, resolvingSignaturesArray); + // Resolve the signatures, preferring constructor + var signatures = getSignaturesOfType(elementType, 1 /* Construct */); + if (signatures.length === 0) { + // No construct signatures, try call signatures + signatures = getSignaturesOfType(elementType, 0 /* Call */); + if (signatures.length === 0) { + // We found no signatures at all, which is an error + if (reportErrors) { + error(openingLikeElement.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(openingLikeElement.tagName)); + } + return; + } + } + // Instantiate in context of source type + var results = instantiateJsxSignatures(openingLikeElement, signatures); + links.resolvedSignatures.set(cacheKey, results); + return results; + } /** * Resolve attributes type of the given opening-like element. The attributes type is a type of attributes associated with the given elementType. * For instance: @@ -39322,23 +44495,27 @@ var ts; * emptyObjectType if there is no "prop" in the element instance type */ function resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, elementType, elementClassType) { - if (elementType.flags & 131072 /* Union */) { + if (elementType.flags & 262144 /* Union */) { var types = elementType.types; return getUnionType(types.map(function (type) { return resolveCustomJsxElementAttributesType(openingLikeElement, shouldIncludeAllStatelessAttributesType, type, elementClassType); }), 2 /* Subtype */); } + // Shortcircuit any + if (isTypeAny(elementType)) { + return elementType; + } // If the elemType is a string type, we have to return anyType to prevent an error downstream as we will try to find construct or call signature of the type - if (elementType.flags & 2 /* String */) { + else if (elementType.flags & 4 /* String */) { return anyType; } - else if (elementType.flags & 32 /* StringLiteral */) { + else if (elementType.flags & 64 /* StringLiteral */) { // If the elemType is a stringLiteral type, we can then provide a check to make sure that the string literal type is one of the Jsx intrinsic element type // For example: // var CustomTag: "h1" = "h1"; // Hello World var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, openingLikeElement); - if (intrinsicElementsType !== unknownType) { + if (intrinsicElementsType !== errorType) { var stringLiteralTypeName = elementType.value; var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName)); if (intrinsicProp) { @@ -39354,7 +44531,11 @@ var ts; return anyType; } // Get the element instance type (the result of newing or invoking this tag) - var elemInstanceType = getJsxElementInstanceType(openingLikeElement, elementType); + var instantiatedSignatures = getInstantiatedJsxSignatures(openingLikeElement, elementType, /*reportErrors*/ true); + if (!ts.length(instantiatedSignatures)) { + return errorType; + } + var elemInstanceType = getUnionType(instantiatedSignatures.map(getReturnTypeOfSignature), 2 /* Subtype */); // If we should include all stateless attributes type, then get all attributes type from all stateless function signature. // Otherwise get only attributes type from the signature picked by choose-overload logic. var statelessAttributesType = shouldIncludeAllStatelessAttributesType ? @@ -39367,7 +44548,8 @@ var ts; if (elementClassType) { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, ts.Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - return getJsxPropsTypeFromClassType(elemInstanceType, ts.isInJavaScriptFile(openingLikeElement), openingLikeElement); + var isJs = ts.isInJavaScriptFile(openingLikeElement); + return getUnionType(instantiatedSignatures.map(function (sig) { return getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true); })); } /** * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name. @@ -39386,7 +44568,7 @@ var ts; return links.resolvedJsxElementAttributesType = getIndexInfoOfSymbol(symbol, 0 /* String */).type; } else { - return links.resolvedJsxElementAttributesType = unknownType; + return links.resolvedJsxElementAttributesType = errorType; } } return links.resolvedJsxElementAttributesType; @@ -39440,7 +44622,7 @@ var ts; } function getJsxElementClassTypeAt(location) { var type = getJsxType(JsxNames.ElementClass, location); - if (type === unknownType) + if (type === errorType) return undefined; return type; } @@ -39513,7 +44695,7 @@ var ts; * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType */ function isKnownProperty(targetType, name, isComparingJsxAttributes) { - if (targetType.flags & 65536 /* Object */) { + if (targetType.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(targetType); if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || @@ -39523,7 +44705,7 @@ var ts; return true; } } - else if (targetType.flags & 393216 /* UnionOrIntersection */) { + else if (targetType.flags & 786432 /* UnionOrIntersection */) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -39531,6 +44713,10 @@ var ts; } } } + else if (targetType.flags & 4194304 /* Conditional */) { + return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || + isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); + } return false; } /** @@ -39552,33 +44738,29 @@ var ts; // sourceAttributesType is a type of an attributes properties. // i.e
// attr1 and attr2 are treated as JSXAttributes attached in the JsxOpeningLikeElement as "attributes". - var sourceAttributesType = createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode); - // If the targetAttributesType is an emptyObjectType, indicating that there is no property named 'props' on this instance type. - // but there exists a sourceAttributesType, we need to explicitly give an error as normal assignability check allow excess properties and will pass. - if (targetAttributesType === emptyObjectType && (isTypeAny(sourceAttributesType) || getPropertiesOfType(sourceAttributesType).length > 0)) { - error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(getJsxElementPropertiesName(getJsxNamespaceAt(openingLikeElement)))); - } - else { - // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties - var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); - // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. - // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. - if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { - for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { - var attribute = _a[_i]; - if (!ts.isJsxAttribute(attribute)) { - continue; - } - var attrName = attribute.name; - var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); - if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { - error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); - // We break here so that errors won't be cascading - break; - } + var sourceAttributesType = checkExpressionCached(openingLikeElement.attributes, checkMode); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = isTypeAssignableTo(sourceAttributesType, targetAttributesType); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outer attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (!ts.isJsxAttribute(attribute)) { + continue; + } + var attrName = attribute.name; + var isNotIgnoredJsxProperty = (isUnhyphenatedJsxName(ts.idText(attrName)) || !!(getPropertyOfType(targetAttributesType, attrName.escapedText))); + if (isNotIgnoredJsxProperty && !isKnownProperty(targetAttributesType, attrName.escapedText, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(attrName), typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; } } } + else if (!isSourceAttributeTypeAssignableToTarget) { + checkTypeAssignableToAndOptionallyElaborate(sourceAttributesType, targetAttributesType, openingLikeElement.tagName, openingLikeElement.attributes); + } } function checkJsxExpression(node, checkMode) { if (node.expression) { @@ -39589,19 +44771,30 @@ var ts; return type; } else { - return unknownType; + return errorType; } } // If a symbol is a synthesized symbol with no value declaration, we assume it is a property. Example of this are the synthesized // '.prototype' property as well as synthesized tuple index properties. function getDeclarationKindFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.kind : 151 /* PropertyDeclaration */; + return s.valueDeclaration ? s.valueDeclaration.kind : 152 /* PropertyDeclaration */; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } - function isMethodLike(symbol) { - return !!(symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */); + /** + * Return whether this symbol is a member of a prototype somewhere + * Note that this is not tracked well within the compiler, so the answer may be incorrect. + */ + function isPrototypeProperty(symbol) { + if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) { + return true; + } + if (ts.isInJavaScriptFile(symbol.valueDeclaration)) { + var parent = symbol.valueDeclaration.parent; + return parent && ts.isBinaryExpression(parent) && + ts.getSpecialPropertyAssignmentKind(parent) === 3 /* PrototypeProperty */; + } } /** * Check whether the requested property access is valid. @@ -39613,9 +44806,11 @@ var ts; */ function checkPropertyAccessibility(node, left, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); - var errorNode = node.kind === 183 /* PropertyAccessExpression */ || node.kind === 230 /* VariableDeclaration */ ? + var errorNode = node.kind === 187 /* PropertyAccessExpression */ || node.kind === 235 /* VariableDeclaration */ ? node.name : - node.right; + node.kind === 181 /* ImportType */ ? + node : + node.right; if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); @@ -39648,7 +44843,7 @@ var ts; if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); + error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217 return false; } } @@ -39679,16 +44874,23 @@ var ts; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); - return false; + // allow PropertyAccessibility if context is in function with this parameter + // static member access is disallow + var thisParameter = void 0; + if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) { + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); + return false; + } + var thisType = getTypeFromTypeNode(thisParameter.type); + enclosingClass = ((thisType.flags & 65536 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType); } // No further restrictions for static properties if (flags & 32 /* Static */) { return true; } - if (type.flags & 32768 /* TypeParameter */) { + if (type.flags & 65536 /* TypeParameter */) { // get the original type -- represented as the type constraint of the 'this' type - type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); + type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined } if (!type || !hasBaseType(type, enclosingClass)) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); @@ -39696,24 +44898,32 @@ var ts; } return true; } + function getThisParameterFromNodeContext(node) { + var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false); + return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined; + } function symbolHasNonMethodDeclaration(symbol) { return forEachProperty(symbol, function (prop) { var propKind = getDeclarationKindFromSymbol(prop); - return propKind !== 153 /* MethodDeclaration */ && propKind !== 152 /* MethodSignature */; + return propKind !== 154 /* MethodDeclaration */ && propKind !== 153 /* MethodSignature */; }); } function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; + if (type.flags & 2 /* Unknown */) { + error(node, ts.Diagnostics.Object_is_of_type_unknown); + return errorType; + } + var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 24576 /* Nullable */; if (kind) { - error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + error(node, kind & 8192 /* Undefined */ ? kind & 16384 /* Null */ ? (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); - return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; + return t.flags & (24576 /* Nullable */ | 32768 /* Never */) ? errorType : t; } return type; } @@ -39743,9 +44953,9 @@ var ts; var indexInfo = getIndexInfoOfType(apparentType, 0 /* String */); if (!(indexInfo && indexInfo.type)) { if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, leftType.flags & 32768 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); + reportNonexistentProperty(right, leftType.flags & 65536 /* TypeParameter */ && leftType.isThisType ? apparentType : leftType); } - return unknownType; + return errorType; } if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) { error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType)); @@ -39760,7 +44970,7 @@ var ts; if (assignmentKind) { if (isReferenceToReadonlyEntity(node, prop) || isReferenceThroughNamespaceImport(node)) { error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, ts.idText(right)); - return unknownType; + return errorType; } } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); @@ -39768,9 +44978,9 @@ var ts; // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, // accessor, or optional method. - if (node.kind !== 183 /* PropertyAccessExpression */ || + if (node.kind !== 187 /* PropertyAccessExpression */ || assignmentKind === 1 /* Definite */ || - prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 131072 /* Union */)) { + prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 262144 /* Union */)) { return propType; } // If strict null checks and strict property initialization checks are enabled, if we have @@ -39782,14 +44992,14 @@ var ts; var declaration = prop && prop.valueDeclaration; if (declaration && isInstancePropertyWithoutInitializer(declaration)) { var flowContainer = getControlFlowContainer(node); - if (flowContainer.kind === 154 /* Constructor */ && flowContainer.parent === declaration.parent) { + if (flowContainer.kind === 155 /* Constructor */ && flowContainer.parent === declaration.parent) { assumeUninitialized = true; } } } var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType); - if (assumeUninitialized && !(getFalsyFlags(propType) & 4096 /* Undefined */) && getFalsyFlags(flowType) & 4096 /* Undefined */) { - error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); + if (assumeUninitialized && !(getFalsyFlags(propType) & 8192 /* Undefined */) && getFalsyFlags(flowType) & 8192 /* Undefined */) { + error(right, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217 // Return the declared type to reduce follow-on errors return propType; } @@ -39800,24 +45010,29 @@ var ts; if (!valueDeclaration) { return; } + var diagnosticMessage; + var declarationName = ts.idText(right); if (isInPropertyInitializer(node) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !isPropertyDeclaredInAncestorClass(prop)) { - error(right, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName); } - else if (valueDeclaration.kind === 233 /* ClassDeclaration */ && - node.parent.kind !== 161 /* TypeReference */ && - !(valueDeclaration.flags & 2097152 /* Ambient */) && + else if (valueDeclaration.kind === 238 /* ClassDeclaration */ && + node.parent.kind !== 162 /* TypeReference */ && + !(valueDeclaration.flags & 4194304 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) { - error(right, ts.Diagnostics.Class_0_used_before_its_declaration, ts.idText(right)); + diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName); + } + if (diagnosticMessage) { + addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName)); } } function isInPropertyInitializer(node) { return !!ts.findAncestor(node, function (node) { switch (node.kind) { - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return true; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // We might be in `a = { b: this.b }`, so keep looking. See `tests/cases/compiler/useBeforeDeclaration_propertyAssignment.ts`. return false; default: @@ -39835,11 +45050,11 @@ var ts; } var classType = getTypeOfSymbol(prop.parent); while (true) { - classType = getSuperClass(classType); + classType = classType.symbol && getSuperClass(classType); if (!classType) { return false; } - var superProperty = getPropertyOfObjectType(classType, prop.escapedName); + var superProperty = getPropertyOfType(classType, prop.escapedName); if (superProperty && superProperty.valueDeclaration) { return true; } @@ -39850,12 +45065,12 @@ var ts; if (x.length === 0) { return undefined; } - ts.Debug.assert(x.length === 1); - return x[0]; + return getIntersectionType(x); } function reportNonexistentProperty(propNode, containingType) { var errorInfo; - if (containingType.flags & 131072 /* Union */ && !(containingType.flags & 16382 /* Primitive */)) { + var relatedInfo; + if (containingType.flags & 262144 /* Union */ && !(containingType.flags & 32764 /* Primitive */)) { for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) { var subtype = _a[_i]; if (!getPropertyOfType(subtype, propNode.escapedText)) { @@ -39864,20 +45079,35 @@ var ts; } } } - var suggestion = getSuggestionForNonexistentProperty(propNode, containingType); - if (suggestion !== undefined) { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestion); + var promisedType = getPromisedTypeOfPromise(containingType); + if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_forget_to_use_await, ts.declarationNameToString(propNode), typeToString(containingType)); } else { - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType); + if (suggestion !== undefined) { + var suggestedName = ts.symbolName(suggestion); + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName); + relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName); + } + else { + errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType)); + } } - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo)); + var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo); + if (relatedInfo) { + addRelatedInfo(resultDiagnostic, relatedInfo); + } + diagnostics.add(resultDiagnostic); } - function getSuggestionForNonexistentProperty(node, containingType) { - var suggestion = getSpellingSuggestionForName(ts.idText(node), getPropertiesOfType(containingType), 67216319 /* Value */); + function getSuggestedSymbolForNonexistentProperty(name, containingType) { + return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 67216319 /* Value */); + } + function getSuggestionForNonexistentProperty(name, containingType) { + var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType); return suggestion && ts.symbolName(suggestion); } - function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); @@ -39887,10 +45117,17 @@ var ts; // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion. return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning); }); - return result && ts.symbolName(result); + return result; } - function getSuggestionForNonexistentModule(name, targetModule) { - var suggestion = targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + function getSuggestionForNonexistentSymbol(location, outerName, meaning) { + var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning); + return symbolResult && ts.symbolName(symbolResult); + } + function getSuggestedSymbolForNonexistentModule(name, targetModule) { + return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */); + } + function getSuggestionForNonexistentExport(name, targetModule) { + var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule); return suggestion && ts.symbolName(suggestion); } /** @@ -39909,86 +45146,14 @@ var ts; * and 1 insertion/deletion at 3 characters) */ function getSpellingSuggestionForName(name, symbols, meaning) { - var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34)); - var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother. - var bestCandidate; - var justCheckExactMatches = false; - var nameLowerCase = name.toLowerCase(); - for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { - var candidate = symbols_3[_i]; + return ts.getSpellingSuggestion(name, symbols, getCandidateName); + function getCandidateName(candidate) { var candidateName = ts.symbolName(candidate); - if (!(candidate.flags & meaning && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference)) { - continue; - } - var candidateNameLowerCase = candidateName.toLowerCase(); - if (candidateNameLowerCase === nameLowerCase) { - return candidate; - } - if (justCheckExactMatches) { - continue; - } - if (candidateName.length < 3) { - // Don't bother, user would have noticed a 2-character name having an extra character - continue; - } - // Only care about a result better than the best so far. - var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1); - if (distance === undefined) { - continue; - } - if (distance < 3) { - justCheckExactMatches = true; - bestCandidate = candidate; - } - else { - ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined - bestDistance = distance; - bestCandidate = candidate; - } + return !ts.startsWith(candidateName, "\"") && candidate.flags & meaning ? candidateName : undefined; } - return bestCandidate; - } - function levenshteinWithMax(s1, s2, max) { - var previous = new Array(s2.length + 1); - var current = new Array(s2.length + 1); - /** Represents any value > max. We don't care about the particular value. */ - var big = max + 1; - for (var i = 0; i <= s2.length; i++) { - previous[i] = i; - } - for (var i = 1; i <= s1.length; i++) { - var c1 = s1.charCodeAt(i - 1); - var minJ = i > max ? i - max : 1; - var maxJ = s2.length > max + i ? max + i : s2.length; - current[0] = i; - /** Smallest value of the matrix in the ith column. */ - var colMin = i; - for (var j = 1; j < minJ; j++) { - current[j] = big; - } - for (var j = minJ; j <= maxJ; j++) { - var dist = c1 === s2.charCodeAt(j - 1) - ? previous[j - 1] - : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2); - current[j] = dist; - colMin = Math.min(colMin, dist); - } - for (var j = maxJ + 1; j <= s2.length; j++) { - current[j] = big; - } - if (colMin > max) { - // Give up -- everything in this column is > max and it can't get better in future columns. - return undefined; - } - var temp = previous; - previous = current; - current = temp; - } - var res = previous[s2.length]; - return res > max ? undefined : res; } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (!prop || !noUnusedIdentifiers || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -40004,15 +45169,21 @@ var ts; (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */; } function isValidPropertyAccess(node, propertyName) { - var left = node.kind === 183 /* PropertyAccessExpression */ ? node.expression : node.left; - return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + switch (node.kind) { + case 187 /* PropertyAccessExpression */: + return isValidPropertyAccessWithType(node, node.expression, propertyName, getWidenedType(checkExpression(node.expression))); + case 146 /* QualifiedName */: + return isValidPropertyAccessWithType(node, node.left, propertyName, getWidenedType(checkExpression(node.left))); + case 181 /* ImportType */: + return isValidPropertyAccessWithType(node, node, propertyName, getTypeFromTypeNode(node)); + } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 181 /* ImportType */ ? node : node.expression, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { - var propType = getTypeOfFuncClassEnumModule(method); + var propType = getTypeOfPropertyOfType(actualThisType, method.escapedName); var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { @@ -40029,20 +45200,20 @@ var ts; return instantiateType(signatureThisType, createSignatureTypeMapper(sig, getInferredTypes(context))); } function isValidPropertyAccessWithType(node, left, propertyName, type) { - if (type === unknownType || isTypeAny(type)) { + if (type === errorType || isTypeAny(type)) { return true; } var prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, left, type, prop) // In js files properties of unions are allowed in completion - : ts.isInJavaScriptFile(node) && (type.flags & 131072 /* Union */) && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); + : ts.isInJavaScriptFile(node) && (type.flags & 262144 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, left, propertyName, elementType); }); } /** * Return the symbol of the for-in variable declared or referenced by the given for-in statement. */ function getForInVariableSymbol(node) { var initializer = node.initializer; - if (initializer.kind === 231 /* VariableDeclarationList */) { + if (initializer.kind === 236 /* VariableDeclarationList */) { var variable = initializer.declarations[0]; if (variable && !ts.isBindingPattern(variable.name)) { return getSymbolOfNode(variable); @@ -40071,7 +45242,7 @@ var ts; var child = expr; var node = expr.parent; while (node) { - if (node.kind === 219 /* ForInStatement */ && + if (node.kind === 224 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) { @@ -40089,7 +45260,7 @@ var ts; var indexExpression = node.argumentExpression; if (!indexExpression) { var sourceFile = ts.getSourceFileOfNode(node); - if (node.parent.kind === 186 /* NewExpression */ && node.parent.expression === node) { + if (node.parent.kind === 190 /* NewExpression */ && node.parent.expression === node) { var start = ts.skipTrivia(sourceFile.text, node.expression.end); var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); @@ -40099,20 +45270,20 @@ var ts; var end = node.end; grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Expression_expected); } - return unknownType; + return errorType; } var indexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : checkExpression(indexExpression); - if (objectType === unknownType || objectType === silentNeverType) { + if (objectType === errorType || objectType === silentNeverType) { return objectType; } if (isConstEnumObjectType(objectType) && indexExpression.kind !== 9 /* StringLiteral */) { error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); - return unknownType; + return errorType; } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { - if (expressionType === unknownType) { + if (expressionType === errorType) { // There is already an error, so no need to report one. return false; } @@ -40120,7 +45291,7 @@ var ts; return false; } // Make sure the property type is the primitive symbol type - if ((expressionType.flags & 1536 /* ESSymbolLike */) === 0) { + if ((expressionType.flags & 3072 /* ESSymbolLike */) === 0) { if (reportError) { error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression)); } @@ -40156,10 +45327,10 @@ var ts; // This gets us diagnostics for the type arguments and marks them as referenced. ts.forEach(node.typeArguments, checkSourceElement); } - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { checkExpression(node.template); } - else if (node.kind !== 149 /* Decorator */) { + else if (node.kind !== 150 /* Decorator */) { ts.forEach(node.arguments, function (argument) { checkExpression(argument); }); @@ -40192,7 +45363,7 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - index++; + index = index + 1; } else { lastParent = parent; @@ -40222,35 +45393,29 @@ var ts; result.splice(spliceIndex, 0, signature); } } + function isSpreadArgument(arg) { + return !!arg && (arg.kind === 206 /* SpreadElement */ || arg.kind === 213 /* SyntheticExpression */ && arg.isSpread); + } function getSpreadArgumentIndex(args) { - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - if (arg && arg.kind === 202 /* SpreadElement */) { - return i; - } - } - return -1; + return ts.findIndex(args, isSpreadArgument); } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } var argCount; // Apparent number of arguments we will have in this call - var typeArguments; // Type arguments (undefined if none) - var callIsIncomplete; // In incomplete call we want to be lenient when we have too few arguments + var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments var spreadArgIndex = -1; if (ts.isJsxOpeningLikeElement(node)) { // The arity check will be done in "checkApplicableSignatureForJsxOpeningLikeElement". return true; } - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length argCount = args.length; - typeArguments = undefined; - if (node.template.kind === 200 /* TemplateExpression */) { + if (node.template.kind === 204 /* TemplateExpression */) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - var lastSpan = ts.lastOrUndefined(node.template.templateSpans); - ts.Debug.assert(lastSpan !== undefined); // we should always have at least one span. + var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span. callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } else { @@ -40262,47 +45427,43 @@ var ts; callIsIncomplete = !!templateLiteral.isUnterminated; } } - else if (node.kind === 149 /* Decorator */) { - typeArguments = undefined; + else if (node.kind === 150 /* Decorator */) { argCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { if (!node.arguments) { // This only happens when we have something of the form: 'new C' - ts.Debug.assert(node.kind === 186 /* NewExpression */); - return signature.minArgumentCount === 0; + ts.Debug.assert(node.kind === 190 /* NewExpression */); + return getMinArgumentCount(signature) === 0; } argCount = signatureHelpTrailingComma ? args.length + 1 : args.length; // If we are missing the close parenthesis, the call is incomplete. callIsIncomplete = node.arguments.end === node.end; - typeArguments = node.typeArguments; spreadArgIndex = getSpreadArgumentIndex(args); } + // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. + if (spreadArgIndex >= 0) { + return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature)); + } + // Too many arguments implies incorrect arity. + if (!hasEffectiveRestParameter(signature) && argCount > getParameterCount(signature)) { + return false; + } + // If the call is incomplete, we should skip the lower bound check. + var hasEnoughArguments = argCount >= getMinArgumentCount(signature); + return callIsIncomplete || hasEnoughArguments; + } + function hasCorrectTypeArgumentArity(signature, typeArguments) { // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. var numTypeParameters = ts.length(signature.typeParameters); var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters); - var hasRightNumberOfTypeArgs = !typeArguments || + return !typeArguments || (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters); - if (!hasRightNumberOfTypeArgs) { - return false; - } - // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range. - if (spreadArgIndex >= 0) { - return isRestParameterIndex(signature, spreadArgIndex) || - signature.minArgumentCount <= spreadArgIndex && spreadArgIndex < signature.parameters.length; - } - // Too many arguments implies incorrect arity. - if (!signature.hasRestParameter && argCount > signature.parameters.length) { - return false; - } - // If the call is incomplete, we should skip the lower bound check. - var hasEnoughArguments = argCount >= signature.minArgumentCount; - return callIsIncomplete || hasEnoughArguments; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type) { - if (type.flags & 65536 /* Object */) { + if (type.flags & 131072 /* Object */) { var resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { @@ -40314,9 +45475,10 @@ var ts; // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper, compareTypes) { var context = createInferenceContext(signature.typeParameters, signature, 1 /* InferUnionTypes */, compareTypes); - forEachMatchingParameterType(contextualSignature, signature, function (source, target) { + var sourceSignature = contextualMapper ? instantiateSignature(contextualSignature, contextualMapper) : contextualSignature; + forEachMatchingParameterType(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type - inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); + inferTypes(context.inferences, source, target); }); if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); @@ -40350,7 +45512,7 @@ var ts; // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the // return type of 'wrap'. - if (node.kind !== 149 /* Decorator */) { + if (node.kind !== 150 /* Decorator */) { var contextualType = getContextualType(node); if (contextualType) { // We clone the contextual mapper to avoid disturbing a resolution in progress for an @@ -40366,7 +45528,7 @@ var ts; // Above, the type of the 'value' parameter is inferred to be 'A'. var contextualSignature = getSingleCallSignature(instantiatedType); var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? - getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : + getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. @@ -40381,11 +45543,13 @@ var ts; } // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - var argCount = getEffectiveArgumentCount(node, args, signature); + var effectiveArgCount = getEffectiveArgumentCount(node, args, signature); + var genericRestType = getGenericRestType(signature); + var argCount = genericRestType ? Math.min(getParameterCount(signature) - 1, effectiveArgCount) : effectiveArgCount; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 204 /* OmittedExpression */) { + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { var paramType = getTypeAtPosition(signature, i); var argType = getEffectiveArgumentType(node, i); // If the effective argument type is 'undefined', there is no synthetic type @@ -40399,6 +45563,10 @@ var ts; inferTypes(context.inferences, argType, paramType); } } + if (genericRestType) { + var spreadType = getSpreadArgumentType(node, args, argCount, effectiveArgCount, genericRestType, context); + inferTypes(context.inferences, spreadType, genericRestType); + } // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this // time treating function expressions normally (which may cause previously inferred type arguments to be fixed // as we construct types for contextually typed parameters) @@ -40416,6 +45584,35 @@ var ts; } return getInferredTypes(context); } + function getSpreadArgumentType(node, args, index, argCount, restType, context) { + if (index >= argCount - 1) { + var arg = getEffectiveArgument(node, args, argCount - 1); + if (isSpreadArgument(arg)) { + // We are inferring from a spread expression in the last argument position, i.e. both the parameter + // and the argument are ...x forms. + return arg.kind === 213 /* SyntheticExpression */ ? + createArrayType(arg.type) : + checkExpressionWithContextualType(arg.expression, restType, context); + } + } + var contextualType = getIndexTypeOfType(restType, 1 /* Number */) || anyType; + var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 32764 /* Primitive */ | 1048576 /* Index */); + var types = []; + var spreadIndex = -1; + for (var i = index; i < argCount; i++) { + var argType = getEffectiveArgumentType(node, i); + if (!argType) { + argType = checkExpressionWithContextualType(args[i], contextualType, context); + if (spreadIndex < 0 && isSpreadArgument(args[i])) { + spreadIndex = i - index; + } + } + types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); + } + return spreadIndex < 0 ? + createTupleType(types) : + createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true); + } function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) { var isJavascript = ts.isInJavaScriptFile(signature.declaration); var typeParameters = signature.typeParameters; @@ -40426,7 +45623,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); + var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined; var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -40475,7 +45672,7 @@ var ts; return checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation); } var thisType = getThisTypeOfSignature(signature); - if (thisType && thisType !== voidType && node.kind !== 186 /* NewExpression */) { + if (thisType && thisType !== voidType && node.kind !== 190 /* NewExpression */) { // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. @@ -40483,30 +45680,38 @@ var ts; var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; - if (!checkTypeRelatedTo(thisArgumentType, getThisTypeOfSignature(signature), relation, errorNode, headMessage_1)) { + if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1)) { return false; } } var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; var argCount = getEffectiveArgumentCount(node, args, signature); + var restIndex = signature.hasRestParameter ? signature.parameters.length - 1 : -1; + var restType = restIndex >= 0 ? getTypeOfSymbol(signature.parameters[restIndex]) : anyType; for (var i = 0; i < argCount; i++) { var arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. - if (arg === undefined || arg.kind !== 204 /* OmittedExpression */) { - // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - var paramType = getTypeAtPosition(signature, i); - // If the effective argument type is undefined, there is no synthetic type for the argument. - // In that case, we should check the argument. - var argType = getEffectiveArgumentType(node, i) || - checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); - // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), - // we obtain the regular type of any object literal arguments because we may not have inferred complete - // parameter types yet and therefore excess property checks may yield false positives (see #17041). - var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; - // Use argument expression as error location when reporting errors - var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { - return false; + if (arg === undefined || arg.kind !== 208 /* OmittedExpression */) { + if (i === restIndex && (restType.flags & 65536 /* TypeParameter */ || isSpreadArgument(arg) && !isArrayType(restType))) { + var spreadType = getSpreadArgumentType(node, args, i, argCount, restType, /*context*/ undefined); + return checkTypeRelatedTo(spreadType, restType, relation, arg, headMessage); + } + else { + // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) + var paramType = getTypeAtPosition(signature, i); + // If the effective argument type is undefined, there is no synthetic type for the argument. + // In that case, we should check the argument. + var argType = getEffectiveArgumentType(node, i) || + checkExpressionWithContextualType(arg, paramType, excludeArgument && excludeArgument[i] ? identityMapper : undefined); + // If one or more arguments are still excluded (as indicated by a non-null excludeArgument parameter), + // we obtain the regular type of any object literal arguments because we may not have inferred complete + // parameter types yet and therefore excess property checks may yield false positives (see #17041). + var checkArgType = excludeArgument ? getRegularTypeOfObjectLiteral(argType) : argType; + // Use argument expression as error location when reporting errors + var errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + if (!checkTypeRelatedTo(checkArgType, paramType, relation, errorNode, headMessage)) { + return false; + } } } } @@ -40516,12 +45721,9 @@ var ts; * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise. */ function getThisArgumentOfCall(node) { - if (node.kind === 185 /* CallExpression */) { - var callee = node.expression; - if (callee.kind === 183 /* PropertyAccessExpression */) { - return callee.expression; - } - else if (callee.kind === 184 /* ElementAccessExpression */) { + if (node.kind === 189 /* CallExpression */) { + var callee = ts.skipOuterExpressions(node.expression); + if (callee.kind === 187 /* PropertyAccessExpression */ || callee.kind === 188 /* ElementAccessExpression */) { return callee.expression; } } @@ -40536,17 +45738,17 @@ var ts; * will be supplied from calls to `getEffectiveArgumentCount` and `getEffectiveArgumentType`. */ function getEffectiveCallArguments(node) { - if (node.kind === 187 /* TaggedTemplateExpression */) { + if (node.kind === 191 /* TaggedTemplateExpression */) { var template = node.template; - var args_4 = [undefined]; - if (template.kind === 200 /* TemplateExpression */) { + var args_4 = [undefined]; // TODO: GH#18217 + if (template.kind === 204 /* TemplateExpression */) { ts.forEach(template.templateSpans, function (span) { args_4.push(span.expression); }); } return args_4; } - else if (node.kind === 149 /* Decorator */) { + else if (node.kind === 150 /* Decorator */) { // For a decorator, we return undefined as we will determine // the number and types of arguments for a decorator using // `getEffectiveArgumentCount` and `getEffectiveArgumentType` below. @@ -40556,7 +45758,28 @@ var ts; return node.attributes.properties.length > 0 ? [node.attributes] : ts.emptyArray; } else { - return node.arguments || ts.emptyArray; + var args = node.arguments || ts.emptyArray; + var length_4 = args.length; + if (length_4 && isSpreadArgument(args[length_4 - 1]) && getSpreadArgumentIndex(args) === length_4 - 1) { + // We have a spread argument in the last position and no other spread arguments. If the type + // of the argument is a tuple type, spread the tuple elements into the argument list. We can + // call checkExpressionCached because spread expressions never have a contextual type. + var spreadArgument_1 = args[length_4 - 1]; + var type = checkExpressionCached(spreadArgument_1.expression); + if (isTupleType(type)) { + var typeArguments = type.typeArguments || ts.emptyArray; + var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1; + var syntheticArgs = ts.map(typeArguments, function (t, i) { + var arg = ts.createNode(213 /* SyntheticExpression */, spreadArgument_1.pos, spreadArgument_1.end); + arg.parent = spreadArgument_1; + arg.type = t; + arg.isSpread = i === restIndex_2; + return arg; + }); + return ts.concatenate(args.slice(0, length_4 - 1), syntheticArgs); + } + } + return args; } } /** @@ -40573,19 +45796,19 @@ var ts; * Otherwise, the argument count is the length of the 'args' array. */ function getEffectiveArgumentCount(node, args, signature) { - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: // A class decorator will have one argument (see `ClassDecorator` in core.d.ts) return 1; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // A property declaration decorator will have two arguments (see // `PropertyDecorator` in core.d.ts) return 2; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // A method or accessor declaration decorator will have two or three arguments (see // `PropertyDecorator` and `MethodDecorator` in core.d.ts) // If we are emitting decorators for ES3, we will only pass two arguments. @@ -40595,10 +45818,12 @@ var ts; // If the method decorator signature only accepts a target and a key, we will only // type check those arguments. return signature.parameters.length >= 3 ? 3 : 2; - case 148 /* Parameter */: + case 149 /* Parameter */: // A parameter declaration decorator will have three arguments (see // `ParameterDecorator` in core.d.ts) return 3; + default: + return ts.Debug.fail(); } } else { @@ -40619,25 +45844,25 @@ var ts; */ function getEffectiveDecoratorFirstArgumentType(node) { // The first argument to a decorator is its `target`. - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { // For a parameter decorator, the `target` is the parent type of the // parameter's containing method. node = node.parent; - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { var classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // For a property or method decorator, the `target` is the // "static"-side type of the parent of the member if the member is // declared "static"; otherwise, it is the "instance"-side type of the @@ -40645,7 +45870,7 @@ var ts; return getParentTypeOfClassElement(node); } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective type for the second argument to a decorator. @@ -40664,37 +45889,38 @@ var ts; */ function getEffectiveDecoratorSecondArgumentType(node) { // The second argument to a decorator is its `propertyKey` - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a second synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { node = node.parent; - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } // For a non-constructor parameter decorator, the `propertyKey` will be either // a string or a symbol, based on the name of the parameter's containing method. } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // The `propertyKey` for a property or method decorator will be a // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. var element = node; - switch (element.name.kind) { + var name = element.name; + switch (name.kind) { case 71 /* Identifier */: - return getLiteralType(ts.idText(element.name)); + return getLiteralType(ts.idText(name)); case 8 /* NumericLiteral */: case 9 /* StringLiteral */: - return getLiteralType(element.name.text); - case 146 /* ComputedPropertyName */: - var nameType = checkComputedPropertyName(element.name); - if (isTypeAssignableToKind(nameType, 1536 /* ESSymbolLike */)) { + return getLiteralType(name.text); + case 147 /* ComputedPropertyName */: + var nameType = checkComputedPropertyName(name); + if (isTypeAssignableToKind(nameType, 3072 /* ESSymbolLike */)) { return nameType; } else { @@ -40702,11 +45928,11 @@ var ts; } default: ts.Debug.fail("Unsupported property name."); - return unknownType; + return errorType; } } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective argument type for the third argument to a decorator. @@ -40718,28 +45944,28 @@ var ts; function getEffectiveDecoratorThirdArgumentType(node) { // The third argument to a decorator is either its `descriptor` for a method decorator // or its `parameterIndex` for a parameter decorator - if (node.kind === 233 /* ClassDeclaration */) { + if (node.kind === 238 /* ClassDeclaration */) { ts.Debug.fail("Class decorators should not have a third synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { // The `parameterIndex` for a parameter decorator is always a number return numberType; } - if (node.kind === 151 /* PropertyDeclaration */) { + if (node.kind === 152 /* PropertyDeclaration */) { ts.Debug.fail("Property decorators should not have a third synthetic argument."); - return unknownType; + return errorType; } - if (node.kind === 153 /* MethodDeclaration */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 154 /* MethodDeclaration */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. var propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } ts.Debug.fail("Unsupported decorator target."); - return unknownType; + return errorType; } /** * Returns the effective argument type for the provided argument to a decorator. @@ -40755,7 +45981,7 @@ var ts; return getEffectiveDecoratorThirdArgumentType(node.parent); } ts.Debug.fail("Decorators should not have a fourth synthetic argument."); - return unknownType; + return errorType; } /** * Gets the effective argument type for an argument in a call expression. @@ -40764,10 +45990,10 @@ var ts; // Decorators provide special arguments, a tagged template expression provides // a special first argument, and string literals get string literal types // unless we're reporting errors - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { return getEffectiveDecoratorArgumentType(node, argIndex); } - else if (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { return getGlobalTemplateStringsArrayType(); } // This is not a synthetic argument, so we return 'undefined' @@ -40779,8 +46005,8 @@ var ts; */ function getEffectiveArgument(node, args, argIndex) { // For a decorator or the first argument of a tagged template expression we return undefined. - if (node.kind === 149 /* Decorator */ || - (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */)) { + if (node.kind === 150 /* Decorator */ || + (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */)) { return undefined; } return args[argIndex]; @@ -40789,11 +46015,11 @@ var ts; * Gets the error node to use when reporting errors for an effective argument. */ function getEffectiveArgumentErrorNode(node, argIndex, arg) { - if (node.kind === 149 /* Decorator */) { + if (node.kind === 150 /* Decorator */) { // For a decorator, we use the expression of the decorator for error reporting. return node.expression; } - else if (argIndex === 0 && node.kind === 187 /* TaggedTemplateExpression */) { + else if (argIndex === 0 && node.kind === 191 /* TaggedTemplateExpression */) { // For a the first argument of a tagged template expression, we use the template of the tag for error reporting. return node.template; } @@ -40801,15 +46027,62 @@ var ts; return arg; } } + function getArgumentArityError(node, signatures, args) { + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + var belowArgCount = Number.NEGATIVE_INFINITY; + var aboveArgCount = Number.POSITIVE_INFINITY; + var argCount = args.length; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; + var minCount = getMinArgumentCount(sig); + var maxCount = getParameterCount(sig); + if (minCount < argCount && minCount > belowArgCount) + belowArgCount = minCount; + if (argCount < maxCount && maxCount < aboveArgCount) + aboveArgCount = maxCount; + min = Math.min(min, minCount); + max = Math.max(max, maxCount); + } + var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter); + var paramRange = hasRestParameter ? min : + min < max ? min + "-" + max : + min; + var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; + if (argCount <= max && hasSpreadArgument) { + argCount--; + } + if (hasRestParameter || hasSpreadArgument) { + var error_1 = hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : + hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : + ts.Diagnostics.Expected_0_arguments_but_got_1_or_more; + return ts.createDiagnosticForNode(node, error_1, paramRange, argCount); + } + if (min < argCount && argCount < max) { + return ts.createDiagnosticForNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNode(node, ts.Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + } + function getTypeArgumentArityError(node, signatures, typeArguments) { + var min = Infinity; + var max = -Infinity; + for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { + var sig = signatures_6[_i]; + min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); + max = Math.max(max, ts.length(sig.typeParameters)); + } + var paramCount = min === max ? min : min + "-" + max; + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + } function resolveCall(node, signatures, candidatesOutArray, fallbackError) { - var isTaggedTemplate = node.kind === 187 /* TaggedTemplateExpression */; - var isDecorator = node.kind === 149 /* Decorator */; + var isTaggedTemplate = node.kind === 191 /* TaggedTemplateExpression */; + var isDecorator = node.kind === 150 /* Decorator */; var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node); var typeArguments; - if (!isTaggedTemplate && !isDecorator && !isJsxOpeningOrSelfClosingElement) { + if (!isDecorator) { typeArguments = node.typeArguments; // We already perform checking on the type arguments on the class declaration itself. - if (node.expression.kind !== 97 /* SuperKeyword */) { + if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 97 /* SuperKeyword */) { ts.forEach(typeArguments, checkSourceElement); } } @@ -40873,11 +46146,12 @@ var ts; // foo(0); // var candidateForArgumentError; + var candidateForArgumentArityError; var candidateForTypeArgumentError; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. - var signatureHelpTrailingComma = candidatesOutArray && node.kind === 185 /* CallExpression */ && node.arguments.hasTrailingComma; + var signatureHelpTrailingComma = candidatesOutArray && node.kind === 189 /* CallExpression */ && node.arguments.hasTrailingComma; // Section 4.12.1: // if the candidate list contains one or more signatures for which the type of each argument // expression is a subtype of each corresponding parameter type, the return type of the first @@ -40913,81 +46187,30 @@ var ts; // an error, we don't need to exclude any arguments, although it would cause no harm to do so. checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } + else if (candidateForArgumentArityError) { + diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args)); + } else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); - } - var paramCount = min < max ? min + "-" + max : min; - diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length)); + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); } else if (args) { - var min = Number.POSITIVE_INFINITY; - var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { - var sig = signatures_6[_a]; - min = Math.min(min, sig.minArgumentCount); - max = Math.max(max, sig.parameters.length); - } - var hasRestParameter_1 = ts.some(signatures, function (sig) { return sig.hasRestParameter; }); - var hasSpreadArgument = getSpreadArgumentIndex(args) > -1; - var paramCount = hasRestParameter_1 ? min : - min < max ? min + "-" + max : - min; - var argCount = args.length; - if (argCount <= max && hasSpreadArgument) { - argCount--; - } - var error_1 = hasRestParameter_1 && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : - hasRestParameter_1 ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 : - hasSpreadArgument ? ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : - ts.Diagnostics.Expected_0_arguments_but_got_1; - diagnostics.add(ts.createDiagnosticForNode(node, error_1, paramCount, argCount)); + diagnostics.add(getArgumentArityError(node, signatures, args)); } else if (fallbackError) { diagnostics.add(ts.createDiagnosticForNode(node, fallbackError)); } - // No signature was applicable. We have already reported the errors for the invalid signature. - // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. - // Pick the longest signature. This way we can get a contextual type for cases like: - // declare function f(a: { xa: number; xb: number; }, b: number); - // f({ | - // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: - // declare function f(k: keyof T); - // f(" - if (!produceDiagnostics) { - ts.Debug.assert(candidates.length > 0); // Else would have exited above. - var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); - var candidate = candidates[bestIndex]; - var typeParameters = candidate.typeParameters; - if (typeParameters && callLikeExpressionMayHaveTypeArguments(node) && node.typeArguments) { - var typeArguments_1 = node.typeArguments.map(getTypeOfNode); - while (typeArguments_1.length > typeParameters.length) { - typeArguments_1.pop(); - } - while (typeArguments_1.length < typeParameters.length) { - typeArguments_1.push(getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); - } - var instantiated = createSignatureInstantiation(candidate, typeArguments_1); - candidates[bestIndex] = instantiated; - return instantiated; - } - return candidate; - } - return resolveErrorCall(node); + return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } candidateForArgumentError = undefined; + candidateForArgumentArityError = undefined; candidateForTypeArgumentError = undefined; if (isSingleNonGenericCandidate) { var candidate = candidates[0]; - if (!hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + if (typeArguments || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { return undefined; } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { @@ -40998,7 +46221,7 @@ var ts; } for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) { var originalCandidate = candidates[candidateIndex]; - if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { + if (!hasCorrectTypeArgumentArity(originalCandidate, typeArguments) || !hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; @@ -41024,6 +46247,12 @@ var ts; } var isJavascript = ts.isInJavaScriptFile(candidate.declaration); candidate = getSignatureInstantiation(candidate, typeArgumentTypes, isJavascript); + // If the original signature has a generic rest type, instantiation may produce a + // signature with different arity and we need to perform another arity check. + if (getGenericRestType(originalCandidate) && !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) { + candidateForArgumentArityError = candidate; + break; + } } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = candidate; @@ -41045,16 +46274,98 @@ var ts; return undefined; } } + // No signature was applicable. We have already reported the errors for the invalid signature. + // If this is a type resolution session, e.g. Language Service, try to get better information than anySignature. + function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) { + ts.Debug.assert(candidates.length > 0); // Else should not have called this. + // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine. + // Don't do this if there is a `candidatesOutArray`, + // because then we want the chosen best candidate to be one of the overloads, not a combination. + return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; }) + ? pickLongestCandidateSignature(node, candidates, args) + : createUnionOfSignaturesForOverloadFailure(candidates); + } + function createUnionOfSignaturesForOverloadFailure(candidates) { + var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; }); + var thisParameter; + if (thisParameters.length) { + thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter)); + } + var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; + var parameters = []; + var _loop_8 = function (i) { + var symbols = ts.mapDefined(candidates, function (_a) { + var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; + return hasRestParameter ? + i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : + i < parameters.length ? parameters[i] : undefined; + }); + ts.Debug.assert(symbols.length !== 0); + parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); + }; + for (var i = 0; i < maxNonRestParam; i++) { + _loop_8(i); + } + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); + var hasRestParameter = restParameterSymbols.length !== 0; + if (hasRestParameter) { + var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); + parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + } + return createSignature(candidates[0].declaration, + /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. + thisParameter, parameters, + /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), + /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, + /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + } + function getNumNonRestParameters(signature) { + var numParams = signature.parameters.length; + return signature.hasRestParameter ? numParams - 1 : numParams; + } + function createCombinedSymbolFromTypes(sources, types) { + return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); + } + function createCombinedSymbolForOverloadFailure(sources, type) { + // This function is currently only used for erroneous overloads, so it's good enough to just use the first source. + return createSymbolWithType(ts.first(sources), type); + } + function pickLongestCandidateSignature(node, candidates, args) { + // Pick the longest signature. This way we can get a contextual type for cases like: + // declare function f(a: { xa: number; xb: number; }, b: number); + // f({ | + // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like: + // declare function f(k: keyof T); + // f(" + var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount); + var candidate = candidates[bestIndex]; + var typeParameters = candidate.typeParameters; + if (!typeParameters) { + return candidate; + } + var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments || ts.emptyArray : ts.emptyArray; + var typeArguments = typeArgumentNodes.map(function (n) { return getTypeOfNode(n) || anyType; }); + while (typeArguments.length > typeParameters.length) { + typeArguments.pop(); + } + while (typeArguments.length < typeParameters.length) { + typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(ts.isInJavaScriptFile(node))); + } + var instantiated = createSignatureInstantiation(candidate, typeArguments); + candidates[bestIndex] = instantiated; + return instantiated; + } function getLongestCandidateIndex(candidates, argsCount) { var maxParamsIndex = -1; var maxParams = -1; for (var i = 0; i < candidates.length; i++) { var candidate = candidates[i]; - if (candidate.hasRestParameter || candidate.parameters.length >= argsCount) { + var paramCount = getParameterCount(candidate); + if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) { return i; } - if (candidate.parameters.length > maxParams) { - maxParams = candidate.parameters.length; + if (paramCount > maxParams) { + maxParams = paramCount; maxParamsIndex = i; } } @@ -41063,10 +46374,14 @@ var ts; function resolveCallExpression(node, candidatesOutArray) { if (node.expression.kind === 97 /* SuperKeyword */) { var superType = checkSuperExpression(node.expression); - if (superType !== unknownType) { + if (isTypeAny(superType)) { + ts.forEach(node.arguments, checkExpresionNoReturn); // Still visit arguments so they get marked for visibility, etc + return anySignature; + } + if (superType !== errorType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(ts.getContainingClass(node)); + var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node)); if (baseTypeNode) { var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode); return resolveCall(node, baseConstructors, candidatesOutArray); @@ -41079,7 +46394,7 @@ var ts; return silentNeverSignature; } var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { + if (apparentType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41095,7 +46410,7 @@ var ts; if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, constructSignatures.length)) { // The unknownType indicates that an error already occurred (and was reported). No // need to report another error in this case. - if (funcType !== unknownType && node.typeArguments) { + if (funcType !== errorType && node.typeArguments) { error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments); } return resolveUntypedCall(node); @@ -41121,8 +46436,8 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 32768 /* TypeParameter */ || - !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (131072 /* Union */ | 16384 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 65536 /* TypeParameter */ || + !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (262144 /* Union */ | 32768 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray) { if (node.arguments && languageVersion < 1 /* ES5 */) { @@ -41141,7 +46456,7 @@ var ts; // signatures for overload resolution. The result type of the function call becomes // the result type of the operation. expressionType = getApparentType(expressionType); - if (expressionType === unknownType) { + if (expressionType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41192,6 +46507,38 @@ var ts; invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } + function typeHasProtectedAccessibleBase(target, type) { + var baseTypes = getBaseTypes(type); + if (!ts.length(baseTypes)) { + return false; + } + var firstBase = baseTypes[0]; + if (firstBase.flags & 524288 /* Intersection */) { + var types = firstBase.types; + var mixinCount = ts.countWhere(types, isMixinConstructorType); + var i = 0; + for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) { + var intersectionMember = _a[_i]; + i++; + // We want to ignore mixin ctors + if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(intersectionMember)) { + if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) { + if (intersectionMember.symbol === target) { + return true; + } + if (typeHasProtectedAccessibleBase(target, intersectionMember)) { + return true; + } + } + } + } + return false; + } + if (firstBase.symbol === target) { + return true; + } + return typeHasProtectedAccessibleBase(target, firstBase); + } function isConstructorAccessible(node, signature) { if (!signature || !signature.declaration) { return true; @@ -41207,16 +46554,10 @@ var ts; // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected) if (!isNodeWithinClass(node, declaringClassDeclaration)) { var containingClass = ts.getContainingClass(node); - if (containingClass) { + if (containingClass && modifiers & 16 /* Protected */) { var containingType = getTypeOfNode(containingClass); - var baseTypes = getBaseTypes(containingType); - while (baseTypes.length) { - var baseType = baseTypes[0]; - if (modifiers & 16 /* Protected */ && - baseType.symbol === declaration.parent.symbol) { - return true; - } - baseTypes = getBaseTypes(baseType); + if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) { + return true; } } if (modifiers & 8 /* Private */) { @@ -41230,12 +46571,11 @@ var ts; return true; } function invocationError(node, apparentType, kind) { - error(node, kind === 0 /* Call */ + invocationErrorRecovery(apparentType, kind, error(node, kind === 0 /* Call */ ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); - invocationErrorRecovery(apparentType, kind); + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType))); } - function invocationErrorRecovery(apparentType, kind) { + function invocationErrorRecovery(apparentType, kind, diagnostic) { if (!apparentType.symbol) { return; } @@ -41246,13 +46586,13 @@ var ts; var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); if (!sigs || !sigs.length) return; - error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + addRelatedInfo(diagnostic, ts.createDiagnosticForNode(importNode, ts.Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); - if (apparentType === unknownType) { + if (apparentType === errorType) { // Another error has already been reported return resolveErrorCall(node); } @@ -41272,17 +46612,19 @@ var ts; */ function getDiagnosticHeadMessageForDecoratorResolution(node) { switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression; - case 148 /* Parameter */: + case 149 /* Parameter */: return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression; + default: + return ts.Debug.fail(); } } /** @@ -41291,7 +46633,7 @@ var ts; function resolveDecorator(node, candidatesOutArray) { var funcType = checkExpression(node.expression); var apparentType = getApparentType(funcType); - if (apparentType === unknownType) { + if (apparentType === errorType) { return resolveErrorCall(node); } var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */); @@ -41306,11 +46648,11 @@ var ts; } var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { - var errorInfo = void 0; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); - diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); - invocationErrorRecovery(apparentType, 0 /* Call */); + var diag = ts.createDiagnosticForNodeFromMessageChain(node, errorInfo); + diagnostics.add(diag); + invocationErrorRecovery(apparentType, 0 /* Call */, diag); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -41338,29 +46680,7 @@ var ts; * the function will fill it up with appropriate candidate signatures */ function getResolvedJsxStatelessFunctionSignature(openingLikeElement, elementType, candidatesOutArray) { - ts.Debug.assert(!(elementType.flags & 131072 /* Union */)); - return resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray); - } - /** - * Try treating a given opening-like element as stateless function component and resolve a tagName to a function signature. - * @param openingLikeElement an JSX opening-like element we want to try resolve its stateless function if possible - * @param elementType a type of the opening-like JSX element, a result of resolving tagName in opening-like element. - * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service; - * the function will fill it up with appropriate candidate signatures - * @return a resolved signature if we can find function matching function signature through resolve call or a first signature in the list of functions. - * otherwise return undefined if tag-name of the opening-like element doesn't have call signatures - */ - function resolveStatelessJsxOpeningLikeElement(openingLikeElement, elementType, candidatesOutArray) { - // If this function is called from language service, elementType can be a union type. This is not possible if the function is called from compiler (see: resolveCustomJsxElementAttributesType) - if (elementType.flags & 131072 /* Union */) { - var types = elementType.types; - var result = void 0; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var type = types_16[_i]; - result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); - } - return result; - } + ts.Debug.assert(!(elementType.flags & 262144 /* Union */)); var callSignatures = elementType && getSignaturesOfType(elementType, 0 /* Call */); if (callSignatures && callSignatures.length > 0) { return resolveCall(openingLikeElement, callSignatures, candidatesOutArray); @@ -41369,20 +46689,31 @@ var ts; } function resolveSignature(node, candidatesOutArray) { switch (node.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: return resolveCallExpression(node, candidatesOutArray); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return resolveNewExpression(node, candidatesOutArray); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return resolveTaggedTemplateExpression(node, candidatesOutArray); - case 149 /* Decorator */: + case 150 /* Decorator */: return resolveDecorator(node, candidatesOutArray); - case 255 /* JsxOpeningElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: // This code-path is called by language service - return resolveStatelessJsxOpeningLikeElement(node, checkExpression(node.tagName), candidatesOutArray) || unknownSignature; + var exprTypes = checkExpression(node.tagName); + return forEachType(exprTypes, function (exprType) { + var sfcResult = getResolvedJsxStatelessFunctionSignature(node, exprType, candidatesOutArray); + if (sfcResult && sfcResult !== unknownSignature) { + return sfcResult; + } + var sigs = getInstantiatedJsxSignatures(node, exprType); + if (candidatesOutArray && ts.length(sigs)) { + candidatesOutArray.push.apply(candidatesOutArray, sigs); + } + return ts.length(sigs) ? sigs[0] : unknownSignature; + }) || unknownSignature; } - ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); + throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable."); } /** * Resolve a signature of a given call-like expression. @@ -41422,15 +46753,11 @@ var ts; var symbol = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? getSymbolOfNode(node) : ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? getSymbolOfNode(node.initializer) : undefined; - return symbol && symbol.members !== undefined; + return !!symbol && symbol.members !== undefined; } return false; } function getJavaScriptClassType(symbol) { - var initializer = ts.getDeclaredJavascriptInitializer(symbol.valueDeclaration); - if (initializer) { - symbol = getSymbolOfNode(initializer); - } var inferred; if (isJavaScriptConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); @@ -41447,7 +46774,8 @@ var ts; function getAssignedClassType(symbol) { var decl = symbol.valueDeclaration; var assignmentSymbol = decl && decl.parent && - (ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || + (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) || + ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); if (assignmentSymbol) { var prototype = ts.forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); @@ -41461,15 +46789,13 @@ var ts; return false; } var parent = node.parent; - while (parent && parent.kind === 183 /* PropertyAccessExpression */) { + while (parent && parent.kind === 187 /* PropertyAccessExpression */) { parent = parent.parent; } - return parent && ts.isBinaryExpression(parent) && - ts.isPropertyAccessExpression(parent.left) && - parent.left.name.escapedText === "prototype" && - parent.operatorToken.kind === 58 /* EqualsToken */ && - ts.isObjectLiteralExpression(parent.right) && - parent.right; + if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 58 /* EqualsToken */) { + var right = ts.getInitializerOfBinaryExpression(parent); + return ts.isObjectLiteralExpression(right) && right; + } } function getInferredClassType(symbol) { var links = getSymbolLinks(symbol); @@ -41495,12 +46821,12 @@ var ts; if (node.expression.kind === 97 /* SuperKeyword */) { return voidType; } - if (node.kind === 186 /* NewExpression */) { + if (node.kind === 190 /* NewExpression */) { var declaration = signature.declaration; if (declaration && - declaration.kind !== 154 /* Constructor */ && - declaration.kind !== 158 /* ConstructSignature */ && - declaration.kind !== 163 /* ConstructorType */ && + declaration.kind !== 155 /* Constructor */ && + declaration.kind !== 159 /* ConstructSignature */ && + declaration.kind !== 164 /* ConstructorType */ && !ts.isJSDocConstructSignature(declaration)) { // When resolved signature is a call signature (and not a construct signature) the result type is any, unless // the declaring function had members created through 'x.prototype.y = expr' or 'this.y = expr' psuedodeclarations @@ -41513,7 +46839,7 @@ var ts; } var type = funcSymbol && getJavaScriptClassType(funcSymbol); if (type) { - return type; + return signature.target ? instantiateType(type, signature.mapper) : type; } if (noImplicitAny) { error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type); @@ -41528,10 +46854,20 @@ var ts; var returnType = getReturnTypeOfSignature(signature); // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property // as a fresh unique symbol literal type. - if (returnType.flags & 1536 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { + if (returnType.flags & 3072 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) { return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent)); } - return returnType; + var jsAssignmentType; + if (ts.isInJavaScriptFile(node)) { + var decl = ts.getDeclarationOfJSInitializer(node); + if (decl) { + var jsSymbol = getSymbolOfNode(decl); + if (jsSymbol && ts.hasEntries(jsSymbol.exports)) { + jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, jsObjectLiteralIndexInfo, undefined); + } + } + } + return jsAssignmentType ? getIntersectionType([returnType, jsAssignmentType]) : returnType; } function isSymbolOrSymbolForCall(node) { if (!ts.isCallExpression(node)) @@ -41559,11 +46895,11 @@ var ts; } var specifier = node.arguments[0]; var specifierType = checkExpressionCached(specifier); - // Even though multiple arugments is grammatically incorrect, type-check extra arguments for completion + // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion for (var i = 1; i < node.arguments.length; ++i) { checkExpressionCached(node.arguments[i]); } - if (specifierType.flags & 4096 /* Undefined */ || specifierType.flags & 8192 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { + if (specifierType.flags & 8192 /* Undefined */ || specifierType.flags & 16384 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) { error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType)); } // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal @@ -41577,7 +46913,7 @@ var ts; return createPromiseReturnType(node, anyType); } function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { - if (allowSyntheticDefaultImports && type && type !== unknownType) { + if (allowSyntheticDefaultImports && type && type !== errorType) { var synthType = type; if (!synthType.syntheticType) { var file = ts.find(originalSymbol.declarations, ts.isSourceFile); @@ -41601,34 +46937,34 @@ var ts; return type; } function isCommonJsRequire(node) { - if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { + if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { return false; } // Make sure require is not a local function if (!ts.isIdentifier(node.expression)) return ts.Debug.fail(); - var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (!resolvedRequire) { - // project does not contain symbol named 'require' - assume commonjs require + var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 67216319 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217 + if (resolvedRequire === requireSymbol) { return true; } - // project includes symbol named 'require' - make sure that it it ambient and local non-alias + // project includes symbol named 'require' - make sure that it is ambient and local non-alias if (resolvedRequire.flags & 2097152 /* Alias */) { return false; } var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ - ? 232 /* FunctionDeclaration */ + ? 237 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ - ? 230 /* VariableDeclaration */ + ? 235 /* VariableDeclaration */ : 0 /* Unknown */; if (targetDeclarationKind !== 0 /* Unknown */) { var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind); // function/variable declaration should be ambient - return !!decl && !!(decl.flags & 2097152 /* Ambient */); + return !!decl && !!(decl.flags & 4194304 /* Ambient */); } return false; } function checkTaggedTemplateExpression(node) { + checkGrammarTypeArguments(node, node.typeArguments); if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 65536 /* MakeTemplateObject */); } @@ -41641,7 +46977,7 @@ var ts; var exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression, checkMode))); checkSourceElement(type); var targetType = getTypeFromTypeNode(type); - if (produceDiagnostics && targetType !== unknownType) { + if (produceDiagnostics && targetType !== errorType) { var widenedType = getWidenedType(exprType); if (!isTypeComparableTo(targetType, widenedType)) { checkTypeComparableTo(exprType, targetType, errNode, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1); @@ -41654,12 +46990,21 @@ var ts; } function checkMetaProperty(node) { checkGrammarMetaProperty(node); + if (node.keywordToken === 94 /* NewKeyword */) { + return checkNewTargetMetaProperty(node); + } + if (node.keywordToken === 91 /* ImportKeyword */) { + return checkImportMetaProperty(node); + } + return ts.Debug.assertNever(node.keywordToken); + } + function checkNewTargetMetaProperty(node) { var container = ts.getNewTargetContainer(node); if (!container) { error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target"); - return unknownType; + return errorType; } - else if (container.kind === 154 /* Constructor */) { + else if (container.kind === 155 /* Constructor */) { var symbol = getSymbolOfNode(container.parent); return getTypeOfSymbol(symbol); } @@ -41668,6 +47013,15 @@ var ts; return getTypeOfSymbol(symbol); } } + function checkImportMetaProperty(node) { + if (languageVersion < 6 /* ESNext */ || moduleKind < ts.ModuleKind.ESNext) { + error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_using_ESNext_for_the_target_and_module_compiler_options); + } + var file = ts.getSourceFileOfNode(node); + ts.Debug.assert(!!(file.flags & 1048576 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag."); + ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module."); + return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType; + } function getTypeOfParameter(symbol) { var type = getTypeOfSymbol(symbol); if (strictNullChecks) { @@ -41678,13 +47032,116 @@ var ts; } return type; } + function getParameterNameAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return signature.parameters[pos].escapedName; + } + var restParameter = signature.parameters[paramCount] || unknownSymbol; + var restType = getTypeOfSymbol(restParameter); + if (isTupleType(restType)) { + var associatedNames = restType.target.associatedNames; + var index = pos - paramCount; + return associatedNames ? associatedNames[index] : restParameter.escapedName + "_" + index; + } + return restParameter.escapedName; + } function getTypeAtPosition(signature, pos) { - return signature.hasRestParameter ? - pos < signature.parameters.length - 1 ? getTypeOfParameter(signature.parameters[pos]) : getRestTypeOfSignature(signature) : - pos < signature.parameters.length ? getTypeOfParameter(signature.parameters[pos]) : anyType; + return tryGetTypeAtPosition(signature, pos) || anyType; + } + function tryGetTypeAtPosition(signature, pos) { + var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + if (pos < paramCount) { + return getTypeOfParameter(signature.parameters[pos]); + } + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[paramCount]); + if (isTupleType(restType)) { + if (pos - paramCount < getLengthOfTupleType(restType)) { + return restType.typeArguments[pos - paramCount]; + } + var tupleRestType = getRestTypeOfTupleType(restType); + if (tupleRestType) { + return tupleRestType; + } + } + return getIndexTypeOfType(restType, 1 /* Number */); + } + return undefined; + } + function getRestTypeAtPosition(source, pos) { + var paramCount = getParameterCount(source); + var hasRest = hasEffectiveRestParameter(source); + if (hasRest && pos === paramCount - 1) { + var genericRestType = getGenericRestType(source); + if (genericRestType) { + return genericRestType; + } + } + var start = hasRest ? Math.min(pos, paramCount - 1) : pos; + var types = []; + var names = []; + for (var i = start; i < paramCount; i++) { + types.push(getTypeAtPosition(source, i)); + names.push(getParameterNameAtPosition(source, i)); + } + var minArgumentCount = getMinArgumentCount(source); + var minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + return createTupleType(types, minLength, hasRest, names); + } + function getTypeOfRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + return getRestTypeOfTupleType(restType); + } + return restType; + } + return undefined; + } + function getParameterCount(signature) { + var length = signature.parameters.length; + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[length - 1]); + if (isTupleType(restType)) { + return length + (restType.typeArguments || ts.emptyArray).length - 1; + } + } + return length; + } + function getMinArgumentCount(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (isTupleType(restType)) { + var minLength = restType.target.minLength; + if (minLength > 0) { + return signature.parameters.length - 1 + minLength; + } + } + } + return signature.minArgumentCount; + } + function getGenericRestType(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + if (restType.flags & 15794176 /* Instantiable */) { + return restType; + } + } + return undefined; + } + function hasEffectiveRestParameter(signature) { + if (signature.hasRestParameter) { + var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + return !isTupleType(restType) || restType.target.hasRestElement; + } + return false; } function getTypeOfFirstParameterOfSignature(signature) { - return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : neverType; + return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType); + } + function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) { + return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, mapper) { var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); @@ -41717,11 +47174,11 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { + if (signature.hasRestParameter) { // parameter might be a transient symbol generated by use of `arguments` in the function body. - var parameter = ts.lastOrUndefined(signature.parameters); + var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { - var contextualParameterType = getTypeOfSymbol(ts.lastOrUndefined(context.parameters)); + var contextualParameterType = getRestTypeAtPosition(context, len); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } @@ -41771,7 +47228,7 @@ var ts; error(func, ts.isImportCall(func) ? ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : ts.Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option); - return unknownType; + return errorType; } else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) { error(func, ts.isImportCall(func) ? @@ -41782,11 +47239,11 @@ var ts; } function getReturnTypeFromBody(func, checkMode) { if (!func.body) { - return unknownType; + return errorType; } var functionFlags = ts.getFunctionFlags(func); var type; - if (func.body.kind !== 211 /* Block */) { + if (func.body.kind !== 216 /* Block */) { type = checkExpressionCached(func.body, checkMode); if (functionFlags & 2 /* Async */) { // From within an async function you can return either a non-promise value or a promise. Any @@ -41875,7 +47332,7 @@ var ts; } function getYieldedTypeOfYieldExpression(node, isAsync, checkMode) { var errorNode = node.expression || node; - var expressionType = node.expression ? checkExpressionCached(node.expression, checkMode) : undefinedWideningType; + var expressionType = node.expression ? checkExpression(node.expression, checkMode) : undefinedWideningType; // A `yield*` expression effectively yields everything that its operand yields var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(expressionType, errorNode, /*allowStringInput*/ false, isAsync) : expressionType; return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken @@ -41891,7 +47348,7 @@ var ts; return false; } var switchTypes = getSwitchClauseTypes(node); - if (!switchTypes.length) { + if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) { return false; } return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes); @@ -41900,12 +47357,12 @@ var ts; if (!(func.flags & 128 /* HasImplicitReturn */)) { return false; } - if (ts.some(func.body.statements, function (statement) { return statement.kind === 225 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { + if (ts.some(func.body.statements, function (statement) { return statement.kind === 230 /* SwitchStatement */ && isExhaustiveSwitchStatement(statement); })) { return false; } return true; } - /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means return `void`, `undefined` means return `never`. */ + /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */ function checkAndAggregateReturnExpressionTypes(func, checkMode) { var functionFlags = ts.getFunctionFlags(func); var aggregatedTypes = []; @@ -41922,7 +47379,7 @@ var ts; // the native Promise type by the caller. type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } - if (type.flags & 16384 /* Never */) { + if (type.flags & 32768 /* Never */) { hasReturnOfTypeNever = true; } ts.pushIfUnique(aggregatedTypes, type); @@ -41934,18 +47391,20 @@ var ts; if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) { return undefined; } - if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression) { + if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && + !(isJavaScriptConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) { + // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined ts.pushIfUnique(aggregatedTypes, undefinedType); } return aggregatedTypes; } function mayReturnNever(func) { switch (func.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return true; - case 153 /* MethodDeclaration */: - return func.parent.kind === 182 /* ObjectLiteralExpression */; + case 154 /* MethodDeclaration */: + return func.parent.kind === 186 /* ObjectLiteralExpression */; default: return false; } @@ -41964,16 +47423,16 @@ var ts; return; } // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions. - if (returnType && maybeTypeOfKind(returnType, 1 /* Any */ | 2048 /* Void */)) { + if (returnType && maybeTypeOfKind(returnType, 3 /* AnyOrUnknown */ | 4096 /* Void */)) { return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw - if (func.kind === 152 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 211 /* Block */ || !functionHasImplicitReturn(func)) { + if (func.kind === 153 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 216 /* Block */ || !functionHasImplicitReturn(func)) { return; } var hasExplicitReturn = func.flags & 256 /* HasExplicitReturn */; - if (returnType && returnType.flags & 16384 /* Never */) { + if (returnType && returnType.flags & 32768 /* Never */) { error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point); } else if (returnType && !hasExplicitReturn) { @@ -42002,19 +47461,21 @@ var ts; } } function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(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 === 190 /* FunctionExpression */) { + if (!hasGrammarError && node.kind === 194 /* FunctionExpression */) { checkGrammarForGenerator(node); } var links = getNodeLinks(node); - var type = getTypeOfSymbol(node.symbol); + var type = getTypeOfSymbol(getMergedSymbol(node.symbol)); + if (isTypeAny(type)) { + return type; + } // Check if function expression is contextually typed and assign parameter types if so. if (!(links.flags & 1024 /* ContextChecked */)) { var contextualSignature = getContextualSignature(node); @@ -42045,27 +47506,26 @@ var ts; checkNodeDeferred(node); } } - if (produceDiagnostics && node.kind !== 153 /* MethodDeclaration */) { - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); - } return type; } - function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { - ts.Debug.assert(node.kind !== 153 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); - var functionFlags = ts.getFunctionFlags(node); + function getReturnOrPromisedType(node, functionFlags) { var returnTypeNode = ts.getEffectiveReturnTypeNode(node); - var returnOrPromisedType = returnTypeNode && + return returnTypeNode && ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? - checkAsyncFunctionReturnType(node) : // Async function - getTypeFromTypeNode(returnTypeNode)); // AsyncGenerator function, Generator function, or normal function + checkAsyncFunctionReturnType(node, returnTypeNode) : // Async function + getTypeFromTypeNode(returnTypeNode)) || // AsyncGenerator function, Generator function, or normal function + getReturnTypeOfTypeTag(node); // type from JSDoc @type tag + } + function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) { + ts.Debug.assert(node.kind !== 154 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); + var functionFlags = ts.getFunctionFlags(node); + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function // return is not necessary in the body of generators checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } if (node.body) { - if (!returnTypeNode) { + if (!ts.getEffectiveReturnTypeNode(node)) { // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors // we need. An example is the noImplicitAny errors resulting from widening the return expression // of a function. Because checking of function expression bodies is deferred, there was never an @@ -42073,7 +47533,7 @@ var ts; // checkFunctionExpressionBodies). So it must be done now. getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } - if (node.body.kind === 211 /* Block */) { + if (node.body.kind === 216 /* Block */) { checkSourceElement(node.body); } else { @@ -42086,18 +47546,17 @@ var ts; if (returnOrPromisedType) { if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); - checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body); } else { // Normal function - checkTypeAssignableTo(exprType, returnOrPromisedType, node.body); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body); } } } - registerForUnusedIdentifiersCheck(node); } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!isTypeAssignableToKind(type, 84 /* NumberLike */)) { + if (!isTypeAssignableToKind(type, 168 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -42120,11 +47579,11 @@ var ts; if (isReadonlySymbol(symbol)) { // Allow assignments to readonly properties within constructors of the same class declaration. if (symbol.flags & 4 /* Property */ && - (expr.kind === 183 /* PropertyAccessExpression */ || expr.kind === 184 /* ElementAccessExpression */) && + (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) && expr.expression.kind === 99 /* ThisKeyword */) { // Look for if this is the constructor for the class that `symbol` is a property of. var func = ts.getContainingFunction(expr); - if (!(func && func.kind === 154 /* Constructor */)) { + if (!(func && func.kind === 155 /* Constructor */)) { return true; } // If func.parent is a class and symbol is a (readonly) property of that class, or @@ -42137,13 +47596,13 @@ var ts; return false; } function isReferenceThroughNamespaceImport(expr) { - if (expr.kind === 183 /* PropertyAccessExpression */ || expr.kind === 184 /* ElementAccessExpression */) { + if (expr.kind === 187 /* PropertyAccessExpression */ || expr.kind === 188 /* ElementAccessExpression */) { var node = ts.skipParentheses(expr.expression); if (node.kind === 71 /* Identifier */) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol.flags & 2097152 /* Alias */) { var declaration = getDeclarationOfAliasSymbol(symbol); - return declaration && declaration.kind === 244 /* NamespaceImport */; + return !!declaration && declaration.kind === 249 /* NamespaceImport */; } } } @@ -42152,7 +47611,7 @@ var ts; function checkReferenceExpression(expr, invalidReferenceMessage) { // References are combinations of identifiers, parentheses, and property accesses. var node = ts.skipOuterExpressions(expr, 2 /* Assertions */ | 1 /* Parentheses */); - if (node.kind !== 71 /* Identifier */ && node.kind !== 183 /* PropertyAccessExpression */ && node.kind !== 184 /* ElementAccessExpression */) { + if (node.kind !== 71 /* Identifier */ && node.kind !== 187 /* PropertyAccessExpression */ && node.kind !== 188 /* ElementAccessExpression */) { error(expr, invalidReferenceMessage); return false; } @@ -42161,7 +47620,7 @@ var ts; function checkDeleteExpression(node) { checkExpression(node.expression); var expr = ts.skipParentheses(node.expression); - if (expr.kind !== 183 /* PropertyAccessExpression */ && expr.kind !== 184 /* ElementAccessExpression */) { + if (expr.kind !== 187 /* PropertyAccessExpression */ && expr.kind !== 188 /* ElementAccessExpression */) { error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference); return booleanType; } @@ -42211,7 +47670,7 @@ var ts; case 38 /* MinusToken */: case 52 /* TildeToken */: checkNonNullType(operandType, node.operand); - if (maybeTypeOfKind(operandType, 1536 /* ESSymbolLike */)) { + if (maybeTypeOfKind(operandType, 3072 /* ESSymbolLike */)) { error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator)); } return numberType; @@ -42229,7 +47688,7 @@ var ts; } return numberType; } - return unknownType; + return errorType; } function checkPostfixUnaryExpression(node) { var operandType = checkExpression(node.operand); @@ -42246,13 +47705,13 @@ var ts; // Return true if type might be of the given kind. A union or intersection type might be of a given // kind if at least one constituent type is of the given kind. function maybeTypeOfKind(type, kind) { - if (type.flags & kind || kind & 536870912 /* GenericMappedType */ && isGenericMappedType(type)) { + if (type.flags & kind & ~134217728 /* GenericMappedType */ || kind & 134217728 /* GenericMappedType */ && isGenericMappedType(type)) { return true; } - if (type.flags & 393216 /* UnionOrIntersection */) { + if (type.flags & 786432 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var t = types_16[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -42264,26 +47723,26 @@ var ts; if (source.flags & kind) { return true; } - if (strict && source.flags & (1 /* Any */ | 2048 /* Void */ | 4096 /* Undefined */ | 8192 /* Null */)) { + if (strict && source.flags & (3 /* AnyOrUnknown */ | 4096 /* Void */ | 8192 /* Undefined */ | 16384 /* Null */)) { return false; } - return (kind & 84 /* NumberLike */ && isTypeAssignableTo(source, numberType)) || - (kind & 524322 /* StringLike */ && isTypeAssignableTo(source, stringType)) || - (kind & 136 /* BooleanLike */ && isTypeAssignableTo(source, booleanType)) || - (kind & 2048 /* Void */ && isTypeAssignableTo(source, voidType)) || - (kind & 16384 /* Never */ && isTypeAssignableTo(source, neverType)) || - (kind & 8192 /* Null */ && isTypeAssignableTo(source, nullType)) || - (kind & 4096 /* Undefined */ && isTypeAssignableTo(source, undefinedType)) || - (kind & 512 /* ESSymbol */ && isTypeAssignableTo(source, esSymbolType)) || - (kind & 134217728 /* NonPrimitive */ && isTypeAssignableTo(source, nonPrimitiveType)); + return !!(kind & 168 /* NumberLike */) && isTypeAssignableTo(source, numberType) || + !!(kind & 68 /* StringLike */) && isTypeAssignableTo(source, stringType) || + !!(kind & 272 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || + !!(kind & 4096 /* Void */) && isTypeAssignableTo(source, voidType) || + !!(kind & 32768 /* Never */) && isTypeAssignableTo(source, neverType) || + !!(kind & 16384 /* Null */) && isTypeAssignableTo(source, nullType) || + !!(kind & 8192 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || + !!(kind & 1024 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || + !!(kind & 16777216 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType); } function allTypesAssignableToKind(source, kind, strict) { - return source.flags & 131072 /* Union */ ? + return source.flags & 262144 /* Union */ ? ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) : isTypeAssignableToKind(source, kind, strict); } function isConstEnumObjectType(type) { - return ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && isConstEnumSymbol(type.symbol); + return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol); } function isConstEnumSymbol(symbol) { return (symbol.flags & 128 /* ConstEnum */) !== 0; @@ -42298,7 +47757,7 @@ var ts; // 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 (!isTypeAny(leftType) && - allTypesAssignableToKind(leftType, 16382 /* Primitive */)) { + allTypesAssignableToKind(leftType, 32764 /* 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 @@ -42317,10 +47776,10 @@ 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) || isTypeAssignableToKind(leftType, 84 /* NumberLike */ | 1536 /* ESSymbolLike */))) { + if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 168 /* NumberLike */ | 3072 /* ESSymbolLike */))) { error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol); } - if (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { + if (!isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { 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; @@ -42338,9 +47797,9 @@ var ts; } /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */ function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, allProperties) { - if (property.kind === 268 /* PropertyAssignment */ || property.kind === 269 /* ShorthandPropertyAssignment */) { + if (property.kind === 273 /* PropertyAssignment */ || property.kind === 274 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(name); } if (isComputedNonLiteralName(name)) { @@ -42353,7 +47812,7 @@ var ts; isNumericLiteralName(text) && getIndexTypeOfType(objectLiteralType, 1 /* Number */) || getIndexTypeOfType(objectLiteralType, 0 /* String */); if (type) { - if (property.kind === 269 /* ShorthandPropertyAssignment */) { + if (property.kind === 274 /* ShorthandPropertyAssignment */) { return checkDestructuringAssignment(property, type); } else { @@ -42365,7 +47824,7 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); } } - else if (property.kind === 270 /* SpreadAssignment */) { + else if (property.kind === 275 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(property, 4 /* Rest */); } @@ -42376,6 +47835,7 @@ var ts; } } var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol); + checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); return checkDestructuringAssignment(property.expression, type); } else { @@ -42383,14 +47843,14 @@ var ts; } } function checkArrayLiteralAssignment(node, sourceType, checkMode) { + var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - var elements = node.elements; + var elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; for (var i = 0; i < elements.length; i++) { checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode); } @@ -42399,27 +47859,23 @@ var ts; function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) { var elements = node.elements; var element = elements[elementIndex]; - if (element.kind !== 204 /* OmittedExpression */) { - if (element.kind !== 202 /* SpreadElement */) { + if (element.kind !== 208 /* OmittedExpression */) { + if (element.kind !== 206 /* SpreadElement */) { var propName = "" + elementIndex; - var type = isTypeAny(sourceType) - ? sourceType - : isTupleLikeType(sourceType) - ? getTypeOfPropertyOfType(sourceType, propName) - : elementType; + var type = isTypeAny(sourceType) ? sourceType : + isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); } + // We still need to check element expression here because we may need to set appropriate flag on the expression + // such as NodeCheckFlags.LexicalThis on "this"expression. + checkExpression(element); + if (isTupleType(sourceType)) { + error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); + } else { - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); } } else { @@ -42428,11 +47884,15 @@ var ts; } else { var restExpression = element.expression; - if (restExpression.kind === 198 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { + if (restExpression.kind === 202 /* BinaryExpression */ && restExpression.operatorToken.kind === 58 /* EqualsToken */) { error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - return checkDestructuringAssignment(restExpression, createArrayType(elementType), checkMode); + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = isTupleType(sourceType) ? + getArrayLiteralType((sourceType.typeArguments || ts.emptyArray).slice(elementIndex, getTypeReferenceArity(sourceType))) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -42441,13 +47901,13 @@ var ts; } function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode) { var target; - if (exprOrAssignment.kind === 269 /* ShorthandPropertyAssignment */) { + if (exprOrAssignment.kind === 274 /* ShorthandPropertyAssignment */) { var prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. if (strictNullChecks && - !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 4096 /* Undefined */)) { + !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 8192 /* Undefined */)) { sourceType = getTypeWithFacts(sourceType, 131072 /* NEUndefined */); } checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode); @@ -42457,25 +47917,25 @@ var ts; else { target = exprOrAssignment; } - if (target.kind === 198 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { + if (target.kind === 202 /* BinaryExpression */ && target.operatorToken.kind === 58 /* EqualsToken */) { checkBinaryExpression(target, checkMode); target = target.left; } - if (target.kind === 182 /* ObjectLiteralExpression */) { + if (target.kind === 186 /* ObjectLiteralExpression */) { return checkObjectLiteralAssignment(target, sourceType); } - if (target.kind === 181 /* ArrayLiteralExpression */) { + if (target.kind === 185 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } function checkReferenceAssignment(target, sourceType, checkMode) { var targetType = checkExpression(target, checkMode); - var error = target.parent.kind === 270 /* SpreadAssignment */ ? + var error = target.parent.kind === 275 /* SpreadAssignment */ ? ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access; if (checkReferenceExpression(target, error)) { - checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target); } return sourceType; } @@ -42493,35 +47953,35 @@ var ts; case 71 /* Identifier */: case 9 /* StringLiteral */: case 12 /* RegularExpressionLiteral */: - case 187 /* TaggedTemplateExpression */: - case 200 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + case 204 /* TemplateExpression */: case 13 /* NoSubstitutionTemplateLiteral */: case 8 /* NumericLiteral */: case 101 /* TrueKeyword */: case 86 /* FalseKeyword */: case 95 /* NullKeyword */: case 140 /* UndefinedKeyword */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: - case 191 /* ArrowFunction */: - case 181 /* ArrayLiteralExpression */: - case 182 /* ObjectLiteralExpression */: - case 193 /* TypeOfExpression */: - case 207 /* NonNullExpression */: - case 254 /* JsxSelfClosingElement */: - case 253 /* JsxElement */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 185 /* ArrayLiteralExpression */: + case 186 /* ObjectLiteralExpression */: + case 197 /* TypeOfExpression */: + case 211 /* NonNullExpression */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: return true; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.isAssignmentOperator(node.operatorToken.kind)) { return false; } return isSideEffectFree(node.left) && isSideEffectFree(node.right); - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: // Unary operators ~, !, +, and - have no side effects. // The rest do. switch (node.operator) { @@ -42533,15 +47993,15 @@ var ts; } return false; // Some forms listed here for clarity - case 194 /* VoidExpression */: // Explicit opt-out - case 188 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings - case 206 /* AsExpression */: // Not SEF, but can produce useful type warnings + case 198 /* VoidExpression */: // Explicit opt-out + case 192 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings + case 210 /* AsExpression */: // Not SEF, but can produce useful type warnings default: return false; } } function isTypeEqualityComparableTo(source, target) { - return (target.flags & 12288 /* Nullable */) !== 0 || isTypeComparableTo(source, target); + return (target.flags & 24576 /* Nullable */) !== 0 || isTypeComparableTo(source, target); } function checkBinaryExpression(node, checkMode) { if (ts.isInJavaScriptFile(node) && ts.getAssignedJavascriptInitializer(node)) { @@ -42551,7 +48011,7 @@ var ts; } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { var operator = operatorToken.kind; - if (operator === 58 /* EqualsToken */ && (left.kind === 182 /* ObjectLiteralExpression */ || left.kind === 181 /* ArrayLiteralExpression */)) { + if (operator === 58 /* EqualsToken */ && (left.kind === 186 /* ObjectLiteralExpression */ || left.kind === 185 /* ArrayLiteralExpression */)) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode); } var leftType = checkExpression(left, checkMode); @@ -42587,8 +48047,8 @@ var ts; var suggestedOperator = void 0; // if a user tries to apply a bitwise operator to 2 boolean operands // try and return them a helpful suggestion - if ((leftType.flags & 136 /* BooleanLike */) && - (rightType.flags & 136 /* BooleanLike */) && + if ((leftType.flags & 272 /* BooleanLike */) && + (rightType.flags & 272 /* BooleanLike */) && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) { error(errorNode || operatorToken, ts.Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, ts.tokenToString(operatorToken.kind), ts.tokenToString(suggestedOperator)); } @@ -42606,24 +48066,24 @@ var ts; if (leftType === silentNeverType || rightType === silentNeverType) { return silentNeverType; } - if (!isTypeAssignableToKind(leftType, 524322 /* StringLike */) && !isTypeAssignableToKind(rightType, 524322 /* StringLike */)) { + if (!isTypeAssignableToKind(leftType, 68 /* StringLike */) && !isTypeAssignableToKind(rightType, 68 /* StringLike */)) { leftType = checkNonNullType(leftType, left); rightType = checkNonNullType(rightType, right); } var resultType = void 0; - if (isTypeAssignableToKind(leftType, 84 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 84 /* NumberLike */, /*strict*/ true)) { + if (isTypeAssignableToKind(leftType, 168 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 168 /* 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 (isTypeAssignableToKind(leftType, 524322 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 524322 /* StringLike */, /*strict*/ true)) { + else if (isTypeAssignableToKind(leftType, 68 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 68 /* 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; + resultType = leftType === errorType || rightType === errorType ? errorType : anyType; } // Symbols are not allowed at all in arithmetic expressions if (resultType && !checkForDisallowedESSymbolOperand(operator)) { @@ -42676,21 +48136,47 @@ var ts; getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) : leftType; case 58 /* EqualsToken */: - checkAssignmentOperator(rightType); - return getRegularTypeOfObjectLiteral(rightType); + var special = ts.isBinaryExpression(left.parent) ? ts.getSpecialPropertyAssignmentKind(left.parent) : 0 /* None */; + checkSpecialAssignment(special, right); + if (isJSSpecialPropertyAssignment(special)) { + return leftType; + } + else { + checkAssignmentOperator(rightType); + return getRegularTypeOfObjectLiteral(rightType); + } case 26 /* CommaToken */: if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) { error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; + default: + return ts.Debug.fail(); + } + function checkSpecialAssignment(special, right) { + if (special === 2 /* ModuleExports */) { + var rightType_1 = checkExpression(right, checkMode); + for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _i < _a.length; _i++) { + var prop = _a[_i]; + var propType = getTypeOfSymbol(prop); + if (propType.symbol && propType.symbol.flags & 32 /* Class */) { + var name = prop.escapedName; + var symbol = resolveName(prop.valueDeclaration, name, 67901928 /* Type */, undefined, name, /*isUse*/ false); + if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) { + grammarErrorOnNode(symbol.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + return grammarErrorOnNode(prop.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name)); + } + } + } + } } function isEvalNode(node) { return node.kind === 71 /* Identifier */ && node.escapedText === "eval"; } // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator) { - var offendingSymbolOperand = maybeTypeOfKind(leftType, 1536 /* ESSymbolLike */) ? left : - maybeTypeOfKind(rightType, 1536 /* ESSymbolLike */) ? right : + var offendingSymbolOperand = maybeTypeOfKind(leftType, 3072 /* ESSymbolLike */) ? left : + maybeTypeOfKind(rightType, 3072 /* ESSymbolLike */) ? right : undefined; if (offendingSymbolOperand) { error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator)); @@ -42720,15 +48206,48 @@ var ts; // VarExpr = ValueExpr // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) - // and the type of the non - compound operation to be assignable to the type of VarExpr. - if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access)) { + // and the type of the non-compound operation to be assignable to the type of VarExpr. + if (checkReferenceExpression(left, ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access) + && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported - checkTypeAssignableTo(valueType, leftType, left, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right); } } } + function isJSSpecialPropertyAssignment(special) { + switch (special) { + case 1 /* ExportsProperty */: + case 2 /* ModuleExports */: + case 5 /* Property */: + case 6 /* Prototype */: + case 3 /* PrototypeProperty */: + case 4 /* ThisProperty */: + var symbol = getSymbolOfNode(left); + var init = ts.getAssignedJavascriptInitializer(right); + return init && ts.isObjectLiteralExpression(init) && + symbol && ts.hasEntries(symbol.exports); + default: + return false; + } + } function reportOperatorError() { - error(errorNode || operatorToken, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), typeToString(leftType), typeToString(rightType)); + var leftStr = typeToString(leftType); + var rightStr = typeToString(rightType); + var errNode = errorNode || operatorToken; + if (!tryGiveBetterPrimaryError(errNode, leftStr, rightStr)) { + error(errNode, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr); + } + } + function tryGiveBetterPrimaryError(errNode, leftStr, rightStr) { + switch (operatorToken.kind) { + case 34 /* EqualsEqualsEqualsToken */: + case 32 /* EqualsEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "false", leftStr, rightStr); + case 35 /* ExclamationEqualsEqualsToken */: + case 33 /* ExclamationEqualsToken */: + return error(errNode, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, "true", leftStr, rightStr); + } + return undefined; } } function isYieldExpressionInClass(node) { @@ -42757,7 +48276,9 @@ var ts; } } var func = ts.getContainingFunction(node); - var functionFlags = func ? ts.getFunctionFlags(func) : 0 /* Normal */; + if (!func) + return anyType; + var functionFlags = ts.getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context. return anyType; @@ -42776,14 +48297,14 @@ var ts; } } var isAsync = (functionFlags & 2 /* Async */) !== 0; - var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); + var yieldedType = getYieldedTypeOfYieldExpression(node, isAsync); // TODO: GH#18217 // There is no point in doing an assignability check if the function // has no explicit return type because the return type is directly computed // from the yield expressions. var returnType = ts.getEffectiveReturnTypeNode(func); if (returnType) { var signatureElementType = getIteratedTypeOfGenerator(getTypeFromTypeNode(returnType), isAsync) || anyType; - checkTypeAssignableTo(yieldedType, signatureElementType, node.expression || node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureElementType, node.expression || node, node.expression); } // Both yield and yield* expressions have type 'any' return anyType; @@ -42801,12 +48322,14 @@ var ts; // A place where we actually *are* concerned with the expressions' types are // in tagged templates. ts.forEach(node.templateSpans, function (templateSpan) { - checkExpression(templateSpan.expression); + if (maybeTypeOfKind(checkExpression(templateSpan.expression), 3072 /* ESSymbolLike */)) { + error(templateSpan.expression, ts.Diagnostics.Type_0_cannot_be_converted_to_type_1, typeToString(esSymbolType), typeToString(stringType)); + } }); return stringType; } function getContextNode(node) { - if (node.kind === 261 /* JsxAttributes */) { + if (node.kind === 266 /* JsxAttributes */) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; @@ -42842,38 +48365,52 @@ var ts; } function isTypeAssertion(node) { node = ts.skipParentheses(node); - return node.kind === 188 /* TypeAssertionExpression */ || node.kind === 206 /* AsExpression */; + return node.kind === 192 /* TypeAssertionExpression */ || node.kind === 210 /* AsExpression */; } function checkDeclarationInitializer(declaration) { - var initializer = ts.isInJavaScriptFile(declaration) && ts.getDeclaredJavascriptInitializer(declaration) || declaration.initializer; + var initializer = ts.getEffectiveInitializer(declaration); var type = getTypeOfExpression(initializer, /*cache*/ true); - return ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || + var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || (ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration)) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + if (ts.isInJavaScriptFile(declaration)) { + if (widened.flags & 24576 /* Nullable */) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyType); + } + return anyType; + } + else if (isEmptyArrayLiteralType(widened)) { + if (noImplicitAny) { + reportImplicitAnyError(declaration, anyArrayType); + } + return anyArrayType; + } + } + return widened; } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { - if (contextualType.flags & 393216 /* UnionOrIntersection */) { + if (contextualType.flags & 786432 /* UnionOrIntersection */) { var types = contextualType.types; return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); }); } - if (contextualType.flags & 7372800 /* InstantiableNonPrimitive */) { + if (contextualType.flags & 14745600 /* InstantiableNonPrimitive */) { // If the contextual type is a type variable constrained to a primitive type, consider // this a literal context for literals of that primitive type. For example, given a // type parameter 'T extends string', infer string literal types for T. var constraint = getBaseConstraintOfType(contextualType) || emptyObjectType; - return constraint.flags & 2 /* String */ && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - constraint.flags & 4 /* Number */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - constraint.flags & 8 /* Boolean */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - constraint.flags & 512 /* ESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */) || + return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || + maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || + maybeTypeOfKind(constraint, 1024 /* ESSymbol */) && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint); } // If the contextual type is a literal of a particular primitive type, we consider this a // literal context for all literals of that primitive type. - return contextualType.flags & (32 /* StringLiteral */ | 524288 /* Index */) && maybeTypeOfKind(candidateType, 32 /* StringLiteral */) || - contextualType.flags & 64 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 64 /* NumberLiteral */) || - contextualType.flags & 128 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 128 /* BooleanLiteral */) || - contextualType.flags & 1024 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 1024 /* UniqueESSymbol */); + return !!(contextualType.flags & (64 /* StringLiteral */ | 1048576 /* Index */) && maybeTypeOfKind(candidateType, 64 /* StringLiteral */) || + contextualType.flags & 128 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 128 /* NumberLiteral */) || + contextualType.flags & 256 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 256 /* BooleanLiteral */) || + contextualType.flags & 2048 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 2048 /* UniqueESSymbol */)); } return false; } @@ -42889,7 +48426,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } return checkExpressionForMutableLocation(node.initializer, checkMode); @@ -42900,7 +48437,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); @@ -42930,7 +48467,7 @@ var ts; function getTypeOfExpression(node, cache) { // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. - if (node.kind === 185 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true) && !isSymbolOrSymbolForCall(node)) { + if (node.kind === 189 /* CallExpression */ && node.expression.kind !== 97 /* SuperKeyword */ && !ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(node)) { var funcType = checkNonNullExpression(node.expression); var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { @@ -42956,6 +48493,9 @@ var ts; node.contextualType = saveContextualType; return type; } + function checkExpresionNoReturn(node) { + checkExpression(node); + } // Checks an expression and returns its type. The contextualMapper parameter serves two purposes: When // contextualMapper is not undefined and not equal to the identityMapper function object it indicates that the // expression is being inferentially typed (section 4.15.2 in spec) and provides the type mapper to use in @@ -42965,7 +48505,7 @@ var ts; // contextually typed function and arrow expressions in the initial phase. function checkExpression(node, checkMode) { var type; - if (node.kind === 145 /* QualifiedName */) { + if (node.kind === 146 /* QualifiedName */) { type = checkQualifiedName(node); } else { @@ -42977,10 +48517,10 @@ var ts; // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - var ok = (node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.expression === node) || - (node.parent.kind === 184 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 145 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || - (node.parent.kind === 164 /* TypeQuery */ && node.parent.exprName === node)); + var ok = (node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.expression === node) || + (node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.expression === node) || + ((node.kind === 71 /* Identifier */ || node.kind === 146 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 165 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } @@ -43014,77 +48554,79 @@ var ts; return trueType; case 86 /* FalseKeyword */: return falseType; - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return checkTemplateExpression(node); case 12 /* RegularExpressionLiteral */: return globalRegExpType; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return checkArrayLiteral(node, checkMode); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return checkObjectLiteral(node, checkMode); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return checkPropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return checkIndexedAccess(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: if (node.expression.kind === 91 /* ImportKeyword */) { return checkImportCallExpression(node); } /* falls through */ - case 186 /* NewExpression */: + case 190 /* NewExpression */: return checkCallExpression(node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return checkTaggedTemplateExpression(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return checkParenthesizedExpression(node, checkMode); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return checkClassExpression(node); - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return checkTypeOfExpression(node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: return checkAssertion(node); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return checkNonNullAssertion(node); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return checkMetaProperty(node); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return checkDeleteExpression(node); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return checkVoidExpression(node); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return checkAwaitExpression(node); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return checkPrefixUnaryExpression(node); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return checkPostfixUnaryExpression(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return checkBinaryExpression(node, checkMode); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return checkConditionalExpression(node, checkMode); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return checkSpreadExpression(node, checkMode); - case 204 /* OmittedExpression */: + case 208 /* OmittedExpression */: return undefinedWideningType; - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return checkYieldExpression(node); - case 263 /* JsxExpression */: + case 213 /* SyntheticExpression */: + return node.type; + case 268 /* JsxExpression */: return checkJsxExpression(node, checkMode); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return checkJsxElement(node, checkMode); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return checkJsxSelfClosingElement(node, checkMode); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return checkJsxFragment(node, checkMode); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return checkJsxAttributes(node, checkMode); - case 255 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } - return unknownType; + return errorType; } // DECLARATION AND STATEMENT TYPE CHECKING function checkTypeParameter(node) { @@ -43110,6 +48652,9 @@ var ts; checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } } + function isRestParameterType(type) { + return isArrayType(type) || isTupleType(type) || type.flags & 15794176 /* Instantiable */ && isTypeAssignableTo(type, anyArrayType); + } function checkParameter(node) { // Grammar checking // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the @@ -43119,7 +48664,7 @@ var ts; checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - if (!(func.kind === 154 /* Constructor */ && ts.nodeIsPresent(func.body))) { + if (!(func.kind === 155 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -43130,13 +48675,13 @@ var ts; if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } - if (func.kind === 154 /* Constructor */ || func.kind === 158 /* ConstructSignature */ || func.kind === 163 /* ConstructorType */) { + if (func.kind === 155 /* Constructor */ || func.kind === 159 /* ConstructSignature */ || func.kind === 164 /* ConstructorType */) { error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter); } } // Only check rest parameter type if it's not a binding pattern. Since binding patterns are // not allowed in a rest parameter, we already have an error from checkGrammarParameterList. - if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isArrayType(getTypeOfSymbol(node.symbol))) { + if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isRestParameterType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); } } @@ -43196,13 +48741,13 @@ var ts; } function getTypePredicateParent(node) { switch (node.parent.kind) { - case 191 /* ArrowFunction */: - case 157 /* CallSignature */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 162 /* FunctionType */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 195 /* ArrowFunction */: + case 158 /* CallSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 163 /* FunctionType */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: var parent = node.parent; if (node === parent.type) { return parent; @@ -43220,7 +48765,7 @@ var ts; error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name.kind === 179 /* ArrayBindingPattern */ || name.kind === 178 /* ObjectBindingPattern */) { + else if (name.kind === 183 /* ArrayBindingPattern */ || name.kind === 182 /* ObjectBindingPattern */) { if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) { return true; } @@ -43229,13 +48774,13 @@ var ts; } function checkSignatureDeclaration(node) { // Grammar checking - if (node.kind === 159 /* IndexSignature */) { + if (node.kind === 160 /* IndexSignature */) { checkGrammarIndexSignature(node); } // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled - else if (node.kind === 162 /* FunctionType */ || node.kind === 232 /* FunctionDeclaration */ || node.kind === 163 /* ConstructorType */ || - node.kind === 157 /* CallSignature */ || node.kind === 154 /* Constructor */ || - node.kind === 158 /* ConstructSignature */) { + else if (node.kind === 163 /* FunctionType */ || node.kind === 237 /* FunctionDeclaration */ || node.kind === 164 /* ConstructorType */ || + node.kind === 158 /* CallSignature */ || node.kind === 155 /* Constructor */ || + node.kind === 159 /* ConstructSignature */) { checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); @@ -43265,10 +48810,10 @@ var ts; var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if (noImplicitAny && !returnTypeNode) { switch (node.kind) { - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; - case 157 /* CallSignature */: + case 158 /* CallSignature */: error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type); break; } @@ -43295,11 +48840,11 @@ var ts; } } else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { - checkAsyncFunctionReturnType(node); + checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (noUnusedIdentifiers && !node.body) { - checkUnusedTypeParameters(node); + if (node.kind !== 160 /* IndexSignature */ && node.kind !== 287 /* JSDocFunctionType */) { + registerForUnusedIdentifiersCheck(node); } } } @@ -43315,7 +48860,7 @@ var ts; var staticNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 154 /* Constructor */) { + if (member.kind === 155 /* Constructor */) { for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var param = _c[_b]; if (ts.isParameterPropertyDeclaration(param) && !ts.isBindingPattern(param.name)) { @@ -43326,20 +48871,21 @@ var ts; else { var isStatic = ts.hasModifier(member, 32 /* Static */); var names = isStatic ? staticNames : instanceNames; - var memberName = member.name && ts.getPropertyNameForPropertyNameNode(member.name); - if (memberName) { + var name = member.name; + var memberName = name && ts.getPropertyNameForPropertyNameNode(name); + if (name && memberName) { switch (member.kind) { - case 155 /* GetAccessor */: - addName(names, member.name, memberName, 1 /* Getter */); + case 156 /* GetAccessor */: + addName(names, name, memberName, 1 /* Getter */); break; - case 156 /* SetAccessor */: - addName(names, member.name, memberName, 2 /* Setter */); + case 157 /* SetAccessor */: + addName(names, name, memberName, 2 /* Setter */); break; - case 151 /* PropertyDeclaration */: - addName(names, member.name, memberName, 3 /* Property */); + case 152 /* PropertyDeclaration */: + addName(names, name, memberName, 3 /* Property */); break; - case 153 /* MethodDeclaration */: - addName(names, member.name, memberName, 4 /* Method */); + case 154 /* MethodDeclaration */: + addName(names, name, memberName, 4 /* Method */); break; } } @@ -43401,15 +48947,16 @@ var ts; var names = ts.createMap(); for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - if (member.kind === 150 /* PropertySignature */) { + if (member.kind === 151 /* PropertySignature */) { var memberName = void 0; - switch (member.name.kind) { + var name = member.name; + switch (name.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - memberName = member.name.text; + memberName = name.text; break; case 71 /* Identifier */: - memberName = ts.idText(member.name); + memberName = ts.idText(name); break; default: continue; @@ -43425,7 +48972,7 @@ var ts; } } function checkTypeForDuplicateIndexSignatures(node) { - if (node.kind === 234 /* InterfaceDeclaration */) { + if (node.kind === 239 /* InterfaceDeclaration */) { var nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind @@ -43480,7 +49027,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.hasModifier(node, 128 /* Abstract */) && node.kind === 153 /* MethodDeclaration */ && node.body) { + if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 154 /* MethodDeclaration */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -43491,7 +49038,6 @@ var ts; if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); var symbol = getSymbolOfNode(node); var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind); // Only type check the symbol once @@ -43506,7 +49052,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 151 /* PropertyDeclaration */ && + return n.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && !!n.initializer; } @@ -43514,7 +49060,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -43536,7 +49082,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -43561,8 +49107,8 @@ var ts; checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); - if (node.kind === 155 /* GetAccessor */) { - if (!(node.flags & 2097152 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { + if (node.kind === 156 /* GetAccessor */) { + if (!(node.flags & 4194304 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 128 /* HasImplicitReturn */)) { if (!(node.flags & 256 /* HasExplicitReturn */)) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); } @@ -43571,13 +49117,13 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); } if (!hasNonBindableDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - var otherKind = node.kind === 155 /* GetAccessor */ ? 156 /* SetAccessor */ : 155 /* GetAccessor */; + var otherKind = node.kind === 156 /* GetAccessor */ ? 157 /* SetAccessor */ : 156 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind); if (otherAccessor) { var nodeFlags = ts.getModifierFlags(node); @@ -43595,12 +49141,11 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 155 /* GetAccessor */) { + if (node.kind === 156 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } checkSourceElement(node.body); - registerForUnusedIdentifiersCheck(node); } function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) { var firstType = getAnnotatedType(first); @@ -43633,7 +49178,7 @@ var ts; } function getTypeParametersForTypeReference(node) { var type = getTypeFromTypeReference(node); - if (type !== unknownType) { + if (type !== errorType) { var symbol = getNodeLinks(node).resolvedSymbol; if (symbol) { return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || @@ -43644,11 +49189,11 @@ var ts; } function checkTypeReferenceNode(node) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === 161 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { + if (node.kind === 162 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJavaScriptFile(node) && !ts.isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } var type = getTypeFromTypeReference(node); - if (type !== unknownType) { + if (type !== errorType) { if (node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved ts.forEach(node.typeArguments, checkSourceElement); @@ -43659,7 +49204,7 @@ var ts; } } } - if (type.flags & 16 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { + if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) { error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type)); } } @@ -43668,7 +49213,7 @@ var ts; var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType); if (!typeReferenceNode) return undefined; - var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); + var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217 var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -43688,25 +49233,42 @@ var ts; checkSourceElement(node.elementType); } function checkTupleType(node) { - // Grammar checking - var hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); - if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { - grammarErrorOnNode(node, ts.Diagnostics.A_tuple_type_element_list_cannot_be_empty); + var elementTypes = node.elementTypes; + var seenOptionalElement = false; + for (var i = 0; i < elementTypes.length; i++) { + var e = elementTypes[i]; + if (e.kind === 170 /* RestType */) { + if (i !== elementTypes.length - 1) { + grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type); + break; + } + if (!isArrayType(getTypeFromTypeNode(e))) { + error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type); + } + } + else if (e.kind === 169 /* OptionalType */) { + seenOptionalElement = true; + } + else if (seenOptionalElement) { + grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element); + break; + } } + checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { ts.forEach(node.types, checkSourceElement); } function checkIndexedAccessIndexType(type, accessNode) { - if (!(type.flags & 1048576 /* IndexedAccess */)) { + if (!(type.flags & 2097152 /* IndexedAccess */)) { return type; } // Check if the index type is assignable to 'keyof T' for the object type. var objectType = type.objectType; var indexType = type.indexType; - if (isTypeAssignableTo(indexType, getIndexType(objectType))) { - if (accessNode.kind === 184 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && + if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) { + if (accessNode.kind === 188 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) && ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) { error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType)); } @@ -43714,7 +49276,7 @@ var ts; } // 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 */)) { + if (getIndexInfoOfType(getApparentType(objectType), 1 /* Number */) && isTypeAssignableToKind(indexType, 168 /* NumberLike */)) { return type; } error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType)); @@ -43733,7 +49295,7 @@ var ts; } var type = getTypeFromMappedTypeNode(node); var constraintType = getConstraintTypeFromMappedType(type); - checkTypeAssignableTo(constraintType, stringType, node.typeParameter.constraint); + checkTypeAssignableTo(constraintType, keyofConstraintType, node.typeParameter.constraint); } function checkTypeOperator(node) { checkGrammarTypeOperatorNode(node); @@ -43743,23 +49305,27 @@ var ts; ts.forEachChild(node, checkSourceElement); } function checkInferType(node) { - if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 170 /* ConditionalType */ && n.parent.extendsType === n; })) { + if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 173 /* ConditionalType */ && n.parent.extendsType === n; })) { grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type); } checkSourceElement(node.typeParameter); } + function checkImportType(node) { + checkSourceElement(node.argument); + getTypeFromTypeNode(node); + } function isPrivateWithinAmbient(node) { - return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 2097152 /* Ambient */); + return ts.hasModifier(node, 8 /* Private */) && !!(node.flags & 4194304 /* Ambient */); } function getEffectiveDeclarationFlags(n, flagsToCheck) { var flags = ts.getCombinedModifierFlags(n); // children of classes (even ambient classes) should not be marked as ambient or export // because those flags have no useful semantics there. - if (n.parent.kind !== 234 /* InterfaceDeclaration */ && - n.parent.kind !== 233 /* ClassDeclaration */ && - n.parent.kind !== 203 /* ClassExpression */ && - n.flags & 2097152 /* Ambient */) { - if (!(flags & 2 /* Ambient */)) { + if (n.parent.kind !== 239 /* InterfaceDeclaration */ && + n.parent.kind !== 238 /* ClassDeclaration */ && + n.parent.kind !== 207 /* ClassExpression */ && + n.flags & 4194304 /* Ambient */) { + if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) { // It is nested in an ambient context, which means it is automatically exported flags |= 1 /* Export */; } @@ -43848,7 +49414,7 @@ var ts; if (node.name && subsequentName && (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 === 153 /* MethodDeclaration */ || node.kind === 152 /* MethodSignature */) && + var reportError = (node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */) && ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */); // we can get here in two cases // 1. mixed static and instance class members @@ -43886,8 +49452,8 @@ var ts; for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { var current = declarations_4[_i]; var node = current; - var inAmbientContext = node.flags & 2097152 /* Ambient */; - var inAmbientContextOrInterface = node.parent.kind === 234 /* InterfaceDeclaration */ || node.parent.kind === 165 /* TypeLiteral */ || inAmbientContext; + var inAmbientContext = node.flags & 4194304 /* Ambient */; + var inAmbientContextOrInterface = node.parent.kind === 239 /* InterfaceDeclaration */ || node.parent.kind === 166 /* TypeLiteral */ || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -43898,7 +49464,7 @@ var ts; // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one previousDeclaration = undefined; } - if (node.kind === 232 /* FunctionDeclaration */ || node.kind === 153 /* MethodDeclaration */ || node.kind === 152 /* MethodSignature */ || node.kind === 154 /* Constructor */) { + if (node.kind === 237 /* FunctionDeclaration */ || node.kind === 154 /* MethodDeclaration */ || node.kind === 153 /* MethodSignature */ || node.kind === 155 /* Constructor */) { var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; @@ -44024,37 +49590,46 @@ var ts; DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType"; DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace"; })(DeclarationSpaces || (DeclarationSpaces = {})); - function getDeclarationSpaces(d) { + function getDeclarationSpaces(decl) { + var d = decl; switch (d.kind) { - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - // A jsdoc typedef is, by definition, a type alias - case 291 /* JSDocTypedefTag */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return 2 /* ExportType */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */; - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: return 2 /* ExportType */ | 1 /* ExportValue */; - case 272 /* SourceFile */: + case 277 /* SourceFile */: return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */; + case 252 /* ExportAssignment */: + // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values + if (!ts.isEntityNameExpression(d.expression)) { + return 1 /* ExportValue */; + } + d = d.expression; + /* falls through */ // The below options all declare an Alias, which is allowed to merge with other values within the importing module - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 243 /* ImportClause */: - var result_2 = 0 /* None */; + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 248 /* ImportClause */: + var result_3 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_2 |= getDeclarationSpaces(d); }); - return result_2; - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 232 /* FunctionDeclaration */: - case 246 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 + ts.forEach(target.declarations, function (d) { result_3 |= getDeclarationSpaces(d); }); + return result_3; + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 237 /* FunctionDeclaration */: + case 251 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591 return 1 /* ExportValue */; default: - ts.Debug.fail(ts.Debug.showSyntaxKind(d)); + return ts.Debug.fail(ts.Debug.showSyntaxKind(d)); } } } @@ -44087,7 +49662,7 @@ var ts; if (isReferenceToType(promise, getGlobalPromiseType(/*reportErrors*/ false))) { return typeAsPromise.promisedTypeOfPromise = promise.typeArguments[0]; } - var thenFunction = getTypeOfPropertyOfType(promise, "then"); + var thenFunction = getTypeOfPropertyOfType(promise, "then"); // TODO: GH#18217 if (isTypeAny(thenFunction)) { return undefined; } @@ -44119,7 +49694,7 @@ var ts; * The runtime behavior of the `await` keyword. */ function checkAwaitedType(type, errorNode, diagnosticMessage) { - return getAwaitedType(type, errorNode, diagnosticMessage) || unknownType; + return getAwaitedType(type, errorNode, diagnosticMessage) || errorType; } function getAwaitedType(type, errorNode, diagnosticMessage) { var typeAsAwaitable = type; @@ -44129,7 +49704,7 @@ var ts; if (isTypeAny(type)) { return typeAsAwaitable.awaitedTypeOfType = type; } - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { var types = void 0; for (var _i = 0, _a = type.types; _i < _a.length; _i++) { var constituentType = _a[_i]; @@ -44208,7 +49783,8 @@ var ts; var thenFunction = getTypeOfPropertyOfType(type, "then"); if (thenFunction && getSignaturesOfType(thenFunction, 0 /* Call */).length > 0) { if (errorNode) { - ts.Debug.assert(!!diagnosticMessage); + if (!diagnosticMessage) + return ts.Debug.fail(); error(errorNode, diagnosticMessage); } return undefined; @@ -44228,7 +49804,7 @@ var ts; * * @param node The signature to check */ - function checkAsyncFunctionReturnType(node) { + function checkAsyncFunctionReturnType(node, returnTypeNode) { // As part of our emit for an async function, we will need to emit the entity name of // the return type annotation as an expression. To meet the necessary runtime semantics // for __awaiter, we must also check that the type of the declaration (e.g. the static @@ -44253,58 +49829,57 @@ var ts; // then(...): Promise; // } // - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); var returnType = getTypeFromTypeNode(returnTypeNode); if (languageVersion >= 2 /* ES2015 */) { - if (returnType === unknownType) { - return unknownType; + if (returnType === errorType) { + return errorType; } var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true); if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) { // The promise type was not a valid type reference to the global promise type, so we // report an error and return the unknown type. error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); - return unknownType; + return errorType; } } else { // Always mark the type node as referenced if it points to a value markTypeNodeAsReferenced(returnTypeNode); - if (returnType === unknownType) { - return unknownType; + if (returnType === errorType) { + return errorType; } var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode); if (promiseConstructorName === undefined) { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, typeToString(returnType)); - return unknownType; + return errorType; } var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 67216319 /* Value */, /*ignoreErrors*/ true); - var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : unknownType; - if (promiseConstructorType === unknownType) { + var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType; + if (promiseConstructorType === errorType) { if (promiseConstructorName.kind === 71 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) { error(returnTypeNode, ts.Diagnostics.An_async_function_or_method_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option); } else { error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); } - return unknownType; + return errorType; } var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. error(returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, ts.entityNameToString(promiseConstructorName)); - return unknownType; + return errorType; } if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { - return unknownType; + return errorType; } // Verify there is no local declaration that could collide with the promise constructor. var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 67216319 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); - return unknownType; + return errorType; } } // Get and return the awaited type of the return type. @@ -44321,26 +49896,30 @@ var ts; var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); var errorInfo; switch (node.parent.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 148 /* Parameter */: + case 149 /* Parameter */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); + errorInfo = ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; + default: + return ts.Debug.fail(); } checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } @@ -44380,12 +49959,12 @@ var ts; function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { - case 169 /* IntersectionType */: - case 168 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: var commonEntityName = void 0; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 172 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -44417,9 +49996,9 @@ var ts; } } return commonEntityName; - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return getEntityNameForDecoratorMetadata(node.type); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return node.typeName; } } @@ -44443,14 +50022,14 @@ var ts; } var firstDecorator = node.decorators[0]; checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */); - if (node.kind === 148 /* Parameter */) { + if (node.kind === 149 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } if (compilerOptions.emitDecoratorMetadata) { checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var constructor = ts.getFirstConstructorWithBody(node); if (constructor) { for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) { @@ -44459,19 +50038,19 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); } markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node)); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node)); break; - case 148 /* Parameter */: + case 149 /* Parameter */: markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); var containingSignature = node.parent; for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) { @@ -44487,18 +50066,22 @@ var ts; if (produceDiagnostics) { checkFunctionOrMethodDeclaration(node); checkGrammarForGenerator(node); - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } - function checkJSDocTypedefTag(node) { + function checkJSDocTypeAliasTag(node) { if (!node.typeExpression) { // If the node had `@property` tags, `typeExpression` would have been set to the first property tag. error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags); } + if (node.name) { + checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0); + } + checkSourceElement(node.typeExpression); + } + function checkJSDocTypeTag(node) { + checkSourceElement(node.typeExpression); } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); @@ -44508,13 +50091,17 @@ var ts; // and give a better error message when the host function mentions `arguments` // but the tag doesn't have an array type if (decl) { + var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); + if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { + return; + } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 145 /* QualifiedName */ ? node.name.right : node.name)); + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 146 /* QualifiedName */ ? node.name.right : node.name)); } } } @@ -44525,13 +50112,13 @@ var ts; error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName)); return; } - var augmentsTags = ts.getAllJSDocTagsOfKind(classLike, 285 /* JSDocAugmentsTag */); + var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag); ts.Debug.assert(augmentsTags.length > 0); if (augmentsTags.length > 1) { error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag); } var name = getIdentifierFromEntityNameExpression(node.class.expression); - var extend = ts.getClassExtendsHeritageClauseElement(classLike); + var extend = ts.getClassExtendsHeritageElement(classLike); if (extend) { var className = getIdentifierFromEntityNameExpression(extend.expression); if (className && name.escapedText !== className.escapedText) { @@ -44543,7 +50130,7 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return node.name; default: return undefined; @@ -44556,7 +50143,7 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name && node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name && node.name.kind === 147 /* ComputedPropertyName */) { // This check will account for methods in class/interface declarations, // as well as accessors in classes/object literals checkComputedPropertyName(node.name); @@ -44585,16 +50172,13 @@ var ts; } } } - var body = node.kind === 152 /* MethodSignature */ ? undefined : node.body; + var body = node.kind === 153 /* MethodSignature */ ? undefined : node.body; checkSourceElement(body); - var returnTypeNode = ts.getEffectiveReturnTypeNode(node); if ((functionFlags & 1 /* Generator */) === 0) { // Async function or normal function - var returnOrPromisedType = returnTypeNode && (functionFlags & 2 /* Async */ - ? checkAsyncFunctionReturnType(node) // Async function - : getTypeFromTypeNode(returnTypeNode)); // normal function + var returnOrPromisedType = getReturnOrPromisedType(node, functionFlags); checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnOrPromisedType); } - if (produceDiagnostics && !returnTypeNode) { + if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context if (noImplicitAny && ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) { @@ -44607,140 +50191,110 @@ var ts; getReturnTypeOfSignature(getSignatureFromDeclaration(node)); } } - registerForUnusedIdentifiersCheck(node); + // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature + if (ts.isInJavaScriptFile(node)) { + var typeTag = ts.getJSDocTypeTag(node); + if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { + error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); + } + } } function registerForUnusedIdentifiersCheck(node) { - if (deferredUnusedIdentifierNodes) { - deferredUnusedIdentifierNodes.push(node); + // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`. + if (produceDiagnostics) { + var sourceFile = ts.getSourceFileOfNode(node); + var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path); + if (!potentiallyUnusedIdentifiers) { + potentiallyUnusedIdentifiers = []; + allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers); + } + // TODO: GH#22580 + // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice"); + potentiallyUnusedIdentifiers.push(node); } } - function checkUnusedIdentifiers() { - if (deferredUnusedIdentifierNodes) { - for (var _i = 0, deferredUnusedIdentifierNodes_1 = deferredUnusedIdentifierNodes; _i < deferredUnusedIdentifierNodes_1.length; _i++) { - var node = deferredUnusedIdentifierNodes_1[_i]; - switch (node.kind) { - case 272 /* SourceFile */: - case 237 /* ModuleDeclaration */: - checkUnusedModuleMembers(node); - break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - checkUnusedClassMembers(node); - checkUnusedTypeParameters(node); - break; - case 234 /* InterfaceDeclaration */: - checkUnusedTypeParameters(node); - break; - case 211 /* Block */: - case 239 /* CaseBlock */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - checkUnusedLocalsAndParameters(node); - break; - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - if (node.body) { - checkUnusedLocalsAndParameters(node); - } - checkUnusedTypeParameters(node); - break; - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 235 /* TypeAliasDeclaration */: - checkUnusedTypeParameters(node); - break; - default: - ts.Debug.fail("Node should not have been registered for unused identifiers check"); - } + function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) { + for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) { + var node = potentiallyUnusedIdentifiers_1[_i]; + switch (node.kind) { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + checkUnusedClassMembers(node, addDiagnostic); + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 239 /* InterfaceDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 277 /* SourceFile */: + case 242 /* ModuleDeclaration */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + checkUnusedLocalsAndParameters(node, addDiagnostic); + break; + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + if (node.body) { + checkUnusedLocalsAndParameters(node, addDiagnostic); + } + checkUnusedTypeParameters(node, addDiagnostic); + break; + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 240 /* TypeAliasDeclaration */: + checkUnusedTypeParameters(node, addDiagnostic); + break; + default: + ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check"); } } } - function checkUnusedLocalsAndParameters(node) { - if (noUnusedIdentifiers && !(node.flags & 2097152 /* Ambient */)) { - node.locals.forEach(function (local) { - // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. - // If it's a type parameter merged with a parameter, check if the parameter-side is used. - if (local.flags & 262144 /* TypeParameter */ ? (local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : !local.isReferenced) { - if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 148 /* Parameter */) { - var parameter = ts.getRootDeclaration(local.valueDeclaration); - var name = ts.getNameOfDeclaration(local.valueDeclaration); - if (compilerOptions.noUnusedParameters && - !ts.isParameterPropertyDeclaration(parameter) && - !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(name)) { - error(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)); - } - } - else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d, ts.symbolName(local)); }); - } - } - }); - } - } - function isRemovedPropertyFromObjectSpread(node) { - if (ts.isBindingElement(node) && ts.isObjectBindingPattern(node.parent)) { - var lastElement = ts.lastOrUndefined(node.parent.elements); - return lastElement !== node && !!lastElement.dotDotDotToken; - } - return false; - } - function errorUnusedLocal(declaration, name) { + function errorUnusedLocal(declaration, name, addDiagnostic) { var node = ts.getNameOfDeclaration(declaration) || declaration; - if (isIdentifierThatStartsWithUnderScore(node)) { - var declaration_2 = ts.getRootDeclaration(node.parent); - if ((declaration_2.kind === 230 /* VariableDeclaration */ && ts.isForInOrOfStatement(declaration_2.parent.parent)) || - declaration_2.kind === 147 /* TypeParameter */) { - return; - } - } - if (!isRemovedPropertyFromObjectSpread(node.kind === 71 /* Identifier */ ? node.parent : node)) { - diagnostics.add(ts.createDiagnosticForNodeSpan(ts.getSourceFileOfNode(declaration), declaration, node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name)); - } + var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read; + addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name)); } - function parameterNameStartsWithUnderscore(parameterName) { - return parameterName && isIdentifierThatStartsWithUnderScore(parameterName); - } - function isIdentifierThatStartsWithUnderScore(node) { + function isIdentifierThatStartsWithUnderscore(node) { return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */; } - function checkUnusedClassMembers(node) { - if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { + function checkUnusedClassMembers(node, addDiagnostic) { + if (!(node.flags & 4194304 /* Ambient */)) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 153 /* MethodDeclaration */: - case 151 /* PropertyDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - if (member.kind === 156 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + case 154 /* MethodDeclaration */: + case 152 /* PropertyDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + if (member.kind === 157 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { // Already would have reported an error on the getter. break; } var symbol = getSymbolOfNode(member); if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 154 /* Constructor */: + case 155 /* Constructor */: for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { var parameter = _c[_b]; if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); + addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol))); } } break; - case 159 /* IndexSignature */: - case 210 /* SemicolonClassElement */: + case 160 /* IndexSignature */: + case 215 /* SemicolonClassElement */: // Can't be private break; default: @@ -44749,84 +50303,152 @@ var ts; } } } - function checkUnusedTypeParameters(node) { - if (compilerOptions.noUnusedParameters && !(node.flags & 2097152 /* Ambient */)) { - if (node.typeParameters) { - // Only report errors on the last declaration for the type parameter container; - // this ensures that all uses have been accounted for. - var symbol = getSymbolOfNode(node); - var lastDeclaration = symbol && symbol.declarations && ts.lastOrUndefined(symbol.declarations); - if (lastDeclaration !== node) { - return; - } - for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) { - var typeParameter = _a[_i]; - if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderScore(typeParameter.name)) { - error(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol)); - } + function checkUnusedTypeParameters(node, addDiagnostic) { + // Only report errors on the last declaration for the type parameter container; + // this ensures that all uses have been accounted for. + var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); + if (!(node.flags & 4194304 /* Ambient */) && ts.last(getSymbolOfNode(node).declarations) === node) { + for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) { + var typeParameter = typeParameters_2[_i]; + if (!(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name)) { + addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(typeParameter.symbol))); } } } } - function checkUnusedModuleMembers(node) { - if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. - var unusedImports_1 = ts.createMap(); - node.locals.forEach(function (local) { - if (local.isReferenced || local.exportSymbol) - return; - for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isAmbientModule(declaration)) - continue; - if (isImportedDeclaration(declaration)) { - var importClause = importClauseFromImported(declaration); - var key = String(getNodeId(importClause)); - var group_1 = unusedImports_1.get(key); - if (group_1) { - group_1[1].push(declaration); - } - else { - unusedImports_1.set(key, [importClause, [declaration]]); + function addToGroup(map, key, value, getKey) { + var keyString = String(getKey(key)); + var group = map.get(keyString); + if (group) { + group[1].push(value); + } + else { + map.set(keyString, [key, [value]]); + } + } + function tryGetRootParameterDeclaration(node) { + return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter); + } + function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) { + if (nodeWithLocals.flags & 4194304 /* Ambient */) + return; + // Ideally we could use the ImportClause directly as a key, but must wait until we have full ES6 maps. So must store key along with value. + var unusedImports = ts.createMap(); + var unusedDestructures = ts.createMap(); + var unusedVariables = ts.createMap(); + nodeWithLocals.locals.forEach(function (local) { + // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`. + // If it's a type parameter merged with a parameter, check if the parameter-side is used. + if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) { + return; + } + for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { + var declaration = _a[_i]; + if (ts.isAmbientModule(declaration) || + (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name)) { + continue; + } + if (isImportedDeclaration(declaration)) { + addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId); + } + else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) { + // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though. + var lastElement = ts.last(declaration.parent.elements); + if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) { + addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId); + } + } + else if (ts.isVariableDeclaration(declaration)) { + addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); + } + else { + var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); + var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration); + if (parameter && name) { + if (!ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) { + addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local))); } } else { - errorUnusedLocal(declaration, ts.symbolName(local)); + errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic); } } - }); - unusedImports_1.forEach(function (_a) { - var importClause = _a[0], unuseds = _a[1]; - var importDecl = importClause.parent; - if (forEachImportedDeclaration(importClause, function (d) { return !ts.contains(unuseds, d); })) { - for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { - var unused = unuseds_1[_i]; - errorUnusedLocal(unused, ts.idText(unused.name)); - } + } + }); + unusedImports.forEach(function (_a) { + var importClause = _a[0], unuseds = _a[1]; + var importDecl = importClause.parent; + var nDeclarations = (importClause.name ? 1 : 0) + + (importClause.namedBindings ? + (importClause.namedBindings.kind === 249 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length) + : 0); + if (nDeclarations === unuseds.length) { + addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1 + ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)) + : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused)); + } + else { + for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) { + var unused = unuseds_1[_i]; + errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic); } - else if (unuseds.length === 1) { - error(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name)); + } + }); + unusedDestructures.forEach(function (_a) { + var bindingPattern = _a[0], bindingElements = _a[1]; + var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */; + if (bindingPattern.elements.length === bindingElements.length) { + if (bindingElements.length === 1 && bindingPattern.parent.kind === 235 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 236 /* VariableDeclarationList */) { + addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId); } else { - error(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused, ts.showModuleSpecifier(importDecl)); + addDiagnostic(bindingPattern, kind, bindingElements.length === 1 + ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(ts.first(bindingElements).name, ts.isIdentifier))) + : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused)); } - }); + } + else { + for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) { + var e = bindingElements_1[_i]; + addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(e.name, ts.isIdentifier)))); + } + } + }); + unusedVariables.forEach(function (_a) { + var declarationList = _a[0], declarations = _a[1]; + if (declarationList.declarations.length === declarations.length) { + addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1 + ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name)) + : ts.createDiagnosticForNode(declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused)); + } + else { + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var decl = declarations_5[_i]; + addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.cast(decl.name, ts.isIdentifier)))); + } + } + }); + } + function bindingNameText(name) { + switch (name.kind) { + case 71 /* Identifier */: + return ts.idText(name); + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name); + default: + return ts.Debug.assertNever(name); } } function isImportedDeclaration(node) { - return node.kind === 243 /* ImportClause */ || node.kind === 246 /* ImportSpecifier */ || node.kind === 244 /* NamespaceImport */; + return node.kind === 248 /* ImportClause */ || node.kind === 251 /* ImportSpecifier */ || node.kind === 249 /* NamespaceImport */; } function importClauseFromImported(decl) { - return decl.kind === 243 /* ImportClause */ ? decl : decl.kind === 244 /* NamespaceImport */ ? decl.parent : decl.parent.parent; - } - function forEachImportedDeclaration(importClause, cb) { - var defaultName = importClause.name, namedBindings = importClause.namedBindings; - return (defaultName && cb(importClause)) || - namedBindings && (namedBindings.kind === 244 /* NamespaceImport */ ? cb(namedBindings) : ts.forEach(namedBindings.elements, cb)); + return decl.kind === 248 /* ImportClause */ ? decl : decl.kind === 249 /* NamespaceImport */ ? decl.parent : decl.parent.parent; } function checkBlock(node) { // Grammar checking for SyntaxKind.Block - if (node.kind === 211 /* Block */) { + if (node.kind === 216 /* Block */) { checkGrammarStatementInAmbientContext(node); } if (ts.isFunctionOrModuleBlock(node)) { @@ -44843,7 +50465,7 @@ var ts; } function checkCollisionWithArgumentsInGeneratedCode(node) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!ts.hasRestParameter(node) || node.flags & 2097152 /* Ambient */ || ts.nodeIsMissing(node.body)) { + if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 4194304 /* Ambient */ || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -44856,36 +50478,26 @@ var ts; if (!(identifier && identifier.escapedText === name)) { return false; } - if (node.kind === 151 /* PropertyDeclaration */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 153 /* MethodDeclaration */ || - node.kind === 152 /* MethodSignature */ || - node.kind === 155 /* GetAccessor */ || - node.kind === 156 /* SetAccessor */) { + if (node.kind === 152 /* PropertyDeclaration */ || + node.kind === 151 /* PropertySignature */ || + node.kind === 154 /* MethodDeclaration */ || + node.kind === 153 /* MethodSignature */ || + node.kind === 156 /* GetAccessor */ || + node.kind === 157 /* SetAccessor */) { // it is ok to have member named '_super' or '_this' - member access is always qualified return false; } - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { // ambient context - no codegen impact return false; } var root = ts.getRootDeclaration(node); - if (root.kind === 148 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { + if (root.kind === 149 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { // just an overload - no codegen impact return false; } return true; } - function checkCollisionWithCapturedThisVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_this")) { - potentialThisCollisions.push(node); - } - } - function checkCollisionWithCapturedNewTargetVariable(node, name) { - if (needCollisionCheckForIdentifier(node, name, "_newTarget")) { - potentialNewTargetCollisions.push(node); - } - } // this function will run after checking the source file so 'CaptureThis' is correct for all nodes function checkIfThisIsCapturedInEnclosingScope(node) { ts.findAncestor(node, function (current) { @@ -44899,6 +50511,7 @@ var ts; } return true; } + return false; }); } function checkIfNewTargetIsCapturedInEnclosingScope(node) { @@ -44913,31 +50526,12 @@ var ts; } return true; } + return false; }); } - function checkCollisionWithCapturedSuperVariable(node, name) { - if (!needCollisionCheckForIdentifier(node, name, "_super")) { - return; - } - // bubble up and find containing type - var enclosingClass = ts.getContainingClass(node); - // if containing type was not found or it is ambient - exit (no codegen) - if (!enclosingClass || enclosingClass.flags & 2097152 /* Ambient */) { - return; - } - if (ts.getClassExtendsHeritageClauseElement(enclosingClass)) { - var isDeclaration_3 = node.kind !== 71 /* Identifier */; - if (isDeclaration_3) { - error(node, ts.Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); - } - else { - error(node, ts.Diagnostics.Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference); - } - } - } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ts.ModuleKind.ES2015) { + if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) { return; } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -44949,13 +50543,13 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name)); } } function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) { - if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) { + if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) { return; } // Uninstantiated modules shouldnt do this check @@ -44964,7 +50558,7 @@ var ts; } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent var parent = getDeclarationContainer(node); - if (parent.kind === 272 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { + if (parent.kind === 277 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 1024 /* HasAsyncFunctions */) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name)); } @@ -44999,7 +50593,7 @@ var ts; // skip variable declarations that don't have initializers // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern // so we'll always treat binding elements as initialized - if (node.kind === 230 /* VariableDeclaration */ && !node.initializer) { + if (node.kind === 235 /* VariableDeclaration */ && !node.initializer) { return; } var symbol = getSymbolOfNode(node); @@ -45011,17 +50605,17 @@ var ts; localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) { - var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 231 /* VariableDeclarationList */); - var container = varDeclList.parent.kind === 212 /* VariableStatement */ && varDeclList.parent.parent + var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 236 /* VariableDeclarationList */); + var container = varDeclList.parent.kind === 217 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) var namesShareScope = container && - (container.kind === 211 /* Block */ && ts.isFunctionLike(container.parent) || - container.kind === 238 /* ModuleBlock */ || - container.kind === 237 /* ModuleDeclaration */ || - container.kind === 272 /* SourceFile */); + (container.kind === 216 /* Block */ && ts.isFunctionLike(container.parent) || + container.kind === 243 /* ModuleBlock */ || + container.kind === 242 /* ModuleDeclaration */ || + container.kind === 277 /* SourceFile */); // here we know that function scoped variable is shadowed by block scoped one // if they are defined in the same scope - binder has already reported redeclaration error // otherwise if variable has an initializer - show error that initialization will fail @@ -45036,7 +50630,7 @@ var ts; } // Check that a parameter initializer contains no references to parameters declared to the right of itself function checkParameterInitializer(node) { - if (ts.getRootDeclaration(node).kind !== 148 /* Parameter */) { + if (ts.getRootDeclaration(node).kind !== 149 /* Parameter */) { return; } var func = ts.getContainingFunction(node); @@ -45047,7 +50641,7 @@ var ts; // skip declaration names (i.e. in object literal expressions) return; } - if (n.kind === 183 /* PropertyAccessExpression */) { + if (n.kind === 187 /* PropertyAccessExpression */) { // skip property names in property access expression return visit(n.expression); } @@ -45066,8 +50660,8 @@ var ts; // so we need to do a bit of extra work to check if reference is legal var enclosingContainer = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (enclosingContainer === func) { - if (symbol.valueDeclaration.kind === 148 /* Parameter */ || - symbol.valueDeclaration.kind === 180 /* BindingElement */) { + if (symbol.valueDeclaration.kind === 149 /* Parameter */ || + symbol.valueDeclaration.kind === 184 /* BindingElement */) { // it is ok to reference parameter in initializer if either // - parameter is located strictly on the left of current parameter declaration if (symbol.valueDeclaration.pos < node.pos) { @@ -45081,7 +50675,7 @@ var ts; return ts.isFunctionLike(current.parent) || // computed property names/initializers in instance property declaration of class like entities // are executed in constructor and thus deferred - (current.parent.kind === 151 /* PropertyDeclaration */ && + (current.parent.kind === 152 /* PropertyDeclaration */ && !(ts.hasModifier(current.parent, 32 /* Static */)) && ts.isClassLike(current.parent.parent)); })) { @@ -45114,18 +50708,18 @@ var ts; // Do not use hasDynamicName here, because that returns false for well known symbols. // We want to perform checkComputedPropertyName for all computed properties, including // well known symbols. - if (node.name.kind === 146 /* ComputedPropertyName */) { + if (node.name.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } } - if (node.kind === 180 /* BindingElement */) { - if (node.parent.kind === 178 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { + if (node.kind === 184 /* BindingElement */) { + if (node.parent.kind === 182 /* ObjectBindingPattern */ && languageVersion < 6 /* ESNext */) { checkExternalEmitHelpers(node, 4 /* Rest */); } // check computed properties inside property names of binding elements - if (node.propertyName && node.propertyName.kind === 146 /* ComputedPropertyName */) { + if (node.propertyName && node.propertyName.kind === 147 /* ComputedPropertyName */) { checkComputedPropertyName(node.propertyName); } // check private/protected variable access @@ -45133,7 +50727,7 @@ var ts; var parentType = getTypeForBindingElementParent(parent); var name = node.propertyName || node.name; if (!ts.isBindingPattern(name)) { - var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); + var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); // TODO: GH#18217 markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference. if (parent.initializer && property) { checkPropertyAccessibility(parent, parent.initializer, parentType, property); @@ -45142,26 +50736,26 @@ var ts; } // For a binding pattern, check contained binding elements if (ts.isBindingPattern(node.name)) { - if (node.name.kind === 179 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 183 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } ts.forEach(node.name.elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && ts.getRootDeclaration(node).kind === 148 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { + if (node.initializer && ts.getRootDeclaration(node).kind === 149 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } // For a binding pattern, validate the initializer and exit if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 219 /* ForInStatement */) { + if (node.initializer && node.parent.parent.kind !== 224 /* ForInStatement */) { var initializerType = checkExpressionCached(node.initializer); if (strictNullChecks && node.name.elements.length === 0) { checkNonNullType(initializerType, node); } else { - checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer); } checkParameterInitializer(node); } @@ -45172,52 +50766,55 @@ var ts; if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error - if (node.initializer && node.parent.parent.kind !== 219 /* ForInStatement */) { - var initializer = ts.isInJavaScriptFile(node) && ts.getDeclaredJavascriptInitializer(node) || node.initializer; - checkTypeAssignableTo(checkExpressionCached(initializer), type, node, /*headMessage*/ undefined); - checkParameterInitializer(node); + var initializer = ts.getEffectiveInitializer(node); + if (initializer) { + var isJSObjectLiteralInitializer = ts.isInJavaScriptFile(node) && + ts.isObjectLiteralExpression(initializer) && + (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) && + ts.hasEntries(symbol.exports); + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 224 /* ForInStatement */) { + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); + checkParameterInitializer(node); + } } } else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); - if (type !== unknownType && declarationType !== unknownType && + if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* JSContainer */)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } - if (node.kind !== 151 /* PropertyDeclaration */ && node.kind !== 150 /* PropertySignature */) { + if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */) { // We know we don't have a binding pattern or computed name here checkExportsOnMergedDeclarations(node); - if (node.kind === 230 /* VariableDeclaration */ || node.kind === 180 /* BindingElement */) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { checkVarDeclaredNamesNotShadowed(node); } - checkCollisionWithCapturedSuperVariable(node, node.name); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } } function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstType, nextDeclaration, nextType) { var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration); - var message = nextDeclaration.kind === 151 /* PropertyDeclaration */ || nextDeclaration.kind === 150 /* PropertySignature */ + var message = nextDeclaration.kind === 152 /* PropertyDeclaration */ || nextDeclaration.kind === 151 /* PropertySignature */ ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2; error(nextDeclarationName, message, ts.declarationNameToString(nextDeclarationName), typeToString(firstType), typeToString(nextType)); } function areDeclarationFlagsIdentical(left, right) { - if ((left.kind === 148 /* Parameter */ && right.kind === 230 /* VariableDeclaration */) || - (left.kind === 230 /* VariableDeclaration */ && right.kind === 148 /* Parameter */)) { + if ((left.kind === 149 /* Parameter */ && right.kind === 235 /* VariableDeclaration */) || + (left.kind === 235 /* VariableDeclaration */ && right.kind === 149 /* Parameter */)) { // Differences in optionality between parameters and variables are allowed. return true; } @@ -45256,7 +50853,7 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); - if (node.thenStatement.kind === 213 /* EmptyStatement */) { + if (node.thenStatement.kind === 218 /* EmptyStatement */) { error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); } checkSourceElement(node.elseStatement); @@ -45276,12 +50873,12 @@ var ts; function checkForStatement(node) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - if (node.initializer && node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer && node.initializer.kind === 236 /* VariableDeclarationList */) { checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { ts.forEach(node.initializer.declarations, checkVariableDeclaration); } else { @@ -45299,36 +50896,34 @@ var ts; } function checkForOfStatement(node) { checkGrammarForInOrForOfStatement(node); - if (node.kind === 220 /* ForOfStatement */) { - if (node.awaitModifier) { - var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { - // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper - checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); - } - } - else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { - // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled - checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + if (node.awaitModifier) { + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 6 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled + checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); + } // Check the LHS and RHS // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS // via checkRightHandSideOfForOf. // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { checkForInOrForOfVariableDeclaration(node); } else { var varExpr = node.initializer; var iteratedType = checkRightHandSideOfForOf(node.expression, node.awaitModifier); // There may be a destructuring assignment on the left side - if (varExpr.kind === 181 /* ArrayLiteralExpression */ || varExpr.kind === 182 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { // iteratedType may be undefined. In this case, we still want to check the structure of // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like // to short circuit the type relation checking as much as possible, so we pass the unknownType. - checkDestructuringAssignment(varExpr, iteratedType || unknownType); + checkDestructuringAssignment(varExpr, iteratedType || errorType); } else { var leftType = checkExpression(varExpr); @@ -45338,7 +50933,7 @@ var ts; // because we accessed properties from anyType, or it may have led to an error inside // getElementTypeOfIterable. if (iteratedType) { - checkTypeAssignableTo(iteratedType, leftType, varExpr, /*headMessage*/ undefined); + checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression); } } } @@ -45356,7 +50951,7 @@ var ts; // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.initializer.kind === 231 /* VariableDeclarationList */) { + if (node.initializer.kind === 236 /* VariableDeclarationList */) { var variable = node.initializer.declarations[0]; if (variable && ts.isBindingPattern(variable.name)) { error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); @@ -45370,7 +50965,7 @@ var ts; // and Expr must be an expression of type Any, an object type, or a type parameter type. var varExpr = node.initializer; var leftType = checkExpression(varExpr); - if (varExpr.kind === 181 /* ArrayLiteralExpression */ || varExpr.kind === 182 /* ObjectLiteralExpression */) { + if (varExpr.kind === 185 /* ArrayLiteralExpression */ || varExpr.kind === 186 /* ObjectLiteralExpression */) { error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) { @@ -45383,8 +50978,8 @@ 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 (!isTypeAssignableToKind(rightType, 134217728 /* NonPrimitive */ | 7372800 /* InstantiableNonPrimitive */)) { - 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); + if (rightType === neverType || !isTypeAssignableToKind(rightType, 16777216 /* NonPrimitive */ | 14745600 /* InstantiableNonPrimitive */)) { + 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_but_here_has_type_0, typeToString(rightType)); } checkSourceElement(node.statement); if (node.locals) { @@ -45415,6 +51010,10 @@ var ts; * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier. */ function getIteratedTypeOrElementType(inputType, errorNode, allowStringInput, allowAsyncIterables, checkAssignability) { + if (inputType === neverType) { + reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217 + return undefined; + } var uplevelIteration = languageVersion >= 2 /* ES2015 */; var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration; // Get the iterated type of an `Iterable` or `IterableIterator` only in ES2015 @@ -45434,16 +51033,16 @@ var ts; // This allows us to find other non-string element types from an array unioned with // a string. if (allowStringInput) { - if (arrayType.flags & 131072 /* Union */) { + if (arrayType.flags & 262144 /* Union */) { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the result of filter is a new array. var arrayTypes = inputType.types; - var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 524322 /* StringLike */); }); + var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 68 /* StringLike */); }); if (filteredTypes !== arrayTypes) { arrayType = getUnionType(filteredTypes, 2 /* Subtype */); } } - else if (arrayType.flags & 524322 /* StringLike */) { + else if (arrayType.flags & 68 /* StringLike */) { arrayType = neverType; } hasStringConstituent = arrayType !== inputType; @@ -45456,7 +51055,7 @@ var ts; } // Now that we've removed all the StringLike types, if no constituents remain, then the entire // arrayOrStringType was a string. - if (arrayType.flags & 16384 /* Never */) { + if (arrayType.flags & 32768 /* Never */) { return stringType; } } @@ -45468,13 +51067,18 @@ var ts; // want to say that number is not an array type. But if the input was just // number and string input is allowed, we want to say that number is not an // array type or a string type. + var isIterable = !!getIteratedTypeOfIterable(inputType, /* errorNode */ undefined, allowAsyncIterables, /*allowSyncIterables*/ true, checkAssignability); var diagnostic = !allowStringInput || hasStringConstituent ? downlevelIteration ? ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type : downlevelIteration ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator - : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; + : isIterable + ? ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators + : ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); } return hasStringConstituent ? stringType : undefined; @@ -45482,7 +51086,7 @@ var ts; var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */); if (hasStringConstituent && arrayElementType) { // This is just an optimization for the case where arrayOrStringType is string | string[] - if (arrayElementType.flags & 524322 /* StringLike */) { + if (arrayElementType.flags & 68 /* StringLike */) { return stringType; } return getUnionType([arrayElementType, stringType], 2 /* Subtype */); @@ -45557,17 +51161,15 @@ var ts; } } var asyncMethodType = allowAsyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("asyncIterator")); - var methodType = asyncMethodType || (allowSyncIterables && getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator"))); + var methodType = asyncMethodType || (allowSyncIterables ? getTypeOfPropertyOfType(type, ts.getPropertyNameForKnownSymbolName("iterator")) : undefined); if (isTypeAny(methodType)) { return undefined; } - var signatures = methodType && getSignaturesOfType(methodType, 0 /* Call */); + var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined; if (!ts.some(signatures)) { if (errorNode) { - error(errorNode, allowAsyncIterables - ? ts.Diagnostics.Type_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator - : ts.Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); // only report on the first error + reportTypeNotIterableError(errorNode, type, allowAsyncIterables); errorNode = undefined; } return undefined; @@ -45587,6 +51189,11 @@ var ts; : typeAsIterable.iteratedTypeOfIterable = iteratedType; } } + function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) { + error(errorNode, allowAsyncIterables + ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator + : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator, typeToString(type)); + } /** * This function has very similar logic as getIteratedTypeOfIterable, except that it operates on * Iterators instead of Iterables. Here is the structure: @@ -45684,14 +51291,14 @@ var ts; // TODO: Check that target label is valid } function isGetAccessorWithAnnotatedSetAccessor(node) { - return node.kind === 155 /* GetAccessor */ - && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 156 /* SetAccessor */)) !== undefined; + return node.kind === 156 /* GetAccessor */ + && ts.getEffectiveSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 157 /* SetAccessor */)) !== undefined; } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function - return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 2048 /* Void */ | 1 /* Any */); + return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 4096 /* Void */ | 3 /* AnyOrUnknown */); } function checkReturnStatement(node) { // Grammar checking @@ -45707,7 +51314,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); var functionFlags = ts.getFunctionFlags(func); var isGenerator = functionFlags & 1 /* Generator */; - if (strictNullChecks || node.expression || returnType.flags & 16384 /* Never */) { + if (strictNullChecks || node.expression || returnType.flags & 32768 /* Never */) { var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType; if (isGenerator) { // AsyncGenerator function or Generator function // A generator does not need its return expressions checked against its return type. @@ -45716,17 +51323,17 @@ var ts; // for generators. return; } - else if (func.kind === 156 /* SetAccessor */) { + else if (func.kind === 157 /* SetAccessor */) { if (node.expression) { error(node, ts.Diagnostics.Setters_cannot_return_a_value); } } - else if (func.kind === 154 /* Constructor */) { - if (node.expression && !checkTypeAssignableTo(exprType, returnType, node)) { + else if (func.kind === 155 /* Constructor */) { + if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) { error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } - else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func)) { + else if (ts.getEffectiveReturnTypeNode(func) || isGetAccessorWithAnnotatedSetAccessor(func) || getReturnTypeOfTypeTag(func)) { if (functionFlags & 2 /* Async */) { // Async function var promisedType = getPromisedTypeOfPromise(returnType); var awaitedType = checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); @@ -45738,11 +51345,11 @@ var ts; } } else { - checkTypeAssignableTo(exprType, returnType, node); + checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression); } } } - else if (func.kind !== 154 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { + else if (func.kind !== 155 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType) && !isGenerator) { // The function has a return type, but the return statement doesn't have an expression. error(node, ts.Diagnostics.Not_all_code_paths_return_a_value); } @@ -45771,7 +51378,7 @@ var ts; var expressionIsLiteral = isLiteralType(expressionType); ts.forEach(node.caseBlock.clauses, function (clause) { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause - if (clause.kind === 265 /* DefaultClause */ && !hasDuplicateDefaultClause) { + if (clause.kind === 270 /* DefaultClause */ && !hasDuplicateDefaultClause) { if (firstDefaultClause === undefined) { firstDefaultClause = clause; } @@ -45783,7 +51390,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (produceDiagnostics && clause.kind === 264 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 269 /* CaseClause */) { // TypeScript 1.0 spec (April 2014): 5.9 // In a 'switch' statement, each 'case' expression must be of a type that is comparable // to or from the type of the 'switch' expression. @@ -45812,10 +51419,11 @@ var ts; if (ts.isFunctionLike(current)) { return "quit"; } - if (current.kind === 226 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { + if (current.kind === 231 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label)); return true; } + return false; }); } // ensure that label is unique @@ -45875,8 +51483,8 @@ var ts; checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); - if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(type.symbol.valueDeclaration)) { - var classDeclaration = type.symbol.valueDeclaration; + var classDeclaration = type.symbol.valueDeclaration; + if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) { for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; // Only process instance properties with computed names here. @@ -45900,7 +51508,7 @@ var ts; errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } - if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { + if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { @@ -45909,16 +51517,17 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; + var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration); // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.escapedName))) { + if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) { return; } // perform property check if property or indexer is declared in 'type' // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && - (propDeclaration.kind === 198 /* BinaryExpression */ || - ts.getNameOfDeclaration(propDeclaration).kind === 146 /* ComputedPropertyName */ || + if (propDeclaration && name && + (propDeclaration.kind === 202 /* BinaryExpression */ || + name.kind === 147 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { errorNode = propDeclaration; } @@ -45945,6 +51554,7 @@ var ts; // The predefined type keywords are reserved and cannot be used as names of user defined types. switch (name.escapedText) { case "any": + case "unknown": case "number": case "boolean": case "string": @@ -45954,6 +51564,15 @@ var ts; error(name, message, name.escapedText); } } + /** + * The name cannot be used as 'Object' of user defined types with special target. + */ + function checkClassNameCollisionWithObject(name) { + if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object" + && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { + error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 + } + } /** * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ @@ -45995,26 +51614,27 @@ var ts; if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) { // Report an error on every conflicting declaration. var name = symbolToString(symbol); - for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { - var declaration = declarations_5[_i]; + 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); } } } } - function areTypeParametersIdentical(declarations, typeParameters) { - var maxTypeArgumentCount = ts.length(typeParameters); - var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { - var declaration = declarations_6[_i]; + function areTypeParametersIdentical(declarations, targetParameters) { + var maxTypeArgumentCount = ts.length(targetParameters); + var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters); + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; // If this declaration has too few or too many type parameters, we report an error - var numTypeParameters = ts.length(declaration.typeParameters); + var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration); + var numTypeParameters = sourceParameters.length; if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) { return false; } for (var i = 0; i < numTypeParameters; i++) { - var source = declaration.typeParameters[i]; - var target = typeParameters[i]; + var source = sourceParameters[i]; + var target = targetParameters[i]; // If the type parameter node does not have the same as the resolved type // parameter at this position, we report an error. if (source.name.escapedText !== target.symbol.escapedName) { @@ -46023,7 +51643,7 @@ var ts; // If the type parameter node does not have an identical constraint as the resolved // type parameter at this position, we report an error. var sourceConstraint = source.constraint && getTypeFromTypeNode(source.constraint); - var targetConstraint = getConstraintFromTypeParameter(target); + var targetConstraint = getConstraintOfTypeParameter(target); if (sourceConstraint) { // relax check if later interface augmentation has no constraint if (!targetConstraint || !isTypeIdenticalTo(sourceConstraint, targetConstraint)) { @@ -46063,12 +51683,13 @@ var ts; checkDecorators(node); if (node.name) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (!(node.flags & 4194304 /* Ambient */)) { + checkClassNameCollisionWithObject(node.name); + } } - checkTypeParameters(node.typeParameters); + checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); var type = getDeclaredTypeOfSymbol(symbol); @@ -46077,10 +51698,10 @@ var ts; checkTypeParameterListsIdentical(symbol); checkClassForDuplicateDeclarations(node); // Only check for reserved static identifiers on non-ambient context. - if (!(node.flags & 2097152 /* Ambient */)) { + if (!(node.flags & 4194304 /* Ambient */)) { checkClassForStaticPropertyNameConflicts(node); } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var baseTypeNode = ts.getEffectiveBaseTypeNode(node); if (baseTypeNode) { if (languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); @@ -46092,6 +51713,10 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); + var extendsNode = ts.getClassExtendsHeritageElement(node); + if (extendsNode && extendsNode !== baseTypeNode) { + checkExpression(extendsNode.expression); + } if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { @@ -46106,10 +51731,10 @@ var ts; issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); - if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { + if (baseConstructorType.flags & 2162688 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); } - if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 1081344 /* TypeVariable */)) { + if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 2162688 /* TypeVariable */)) { // When the static base type is a "class-like" constructor function (but not actually a class), we verify // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked @@ -46132,7 +51757,7 @@ var ts; checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { var t = getTypeFromTypeNode(typeRefNode); - if (t !== unknownType) { + if (t !== errorType) { if (isValidBaseType(t)) { var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : @@ -46158,7 +51783,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_5 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -46177,7 +51802,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_5(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -46203,7 +51828,7 @@ var ts; } function getClassOrInterfaceDeclarationsOfSymbol(symbol) { return ts.filter(symbol.declarations, function (d) { - return d.kind === 233 /* ClassDeclaration */ || d.kind === 234 /* InterfaceDeclaration */; + return d.kind === 238 /* ClassDeclaration */ || d.kind === 239 /* InterfaceDeclaration */; }); } function checkKindsOfPropertyMemberOverrides(type, baseType) { @@ -46228,7 +51853,7 @@ var ts; if (base.flags & 4194304 /* Prototype */) { continue; } - var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); + var derived = getTargetSymbol(getPropertyOfObjectType(type, base.escapedName)); // TODO: GH#18217 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base); ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); if (derived) { @@ -46242,7 +51867,7 @@ var ts; // 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.hasModifier(derivedClassDecl, 128 /* Abstract */))) { - if (derivedClassDecl.kind === 203 /* ClassExpression */) { + if (derivedClassDecl.kind === 207 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } else { @@ -46257,12 +51882,12 @@ var ts; // either base or derived property is private - not override, skip it continue; } - if (isMethodLike(base) && isMethodLike(derived) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { + if (isPrototypeProperty(base) || base.flags & 98308 /* PropertyOrAccessor */ && derived.flags & 98308 /* PropertyOrAccessor */) { // method is overridden with method or property/accessor is overridden with property/accessor - correct case continue; } var errorMessage = void 0; - if (isMethodLike(base)) { + if (isPrototypeProperty(base)) { if (derived.flags & 98304 /* Accessor */) { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } @@ -46270,11 +51895,11 @@ var ts; errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; } } - else if (base.flags & 4 /* Property */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + else if (base.flags & 98304 /* Accessor */) { + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; } error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } @@ -46314,7 +51939,7 @@ var ts; return ok; } function checkPropertyInitialization(node) { - if (!strictNullChecks || !strictPropertyInitialization || node.flags & 2097152 /* Ambient */) { + if (!strictNullChecks || !strictPropertyInitialization || node.flags & 4194304 /* Ambient */) { return; } var constructor = findConstructorDeclaration(node); @@ -46324,7 +51949,7 @@ var ts; var propName = member.name; if (ts.isIdentifier(propName)) { var type = getTypeOfSymbol(getSymbolOfNode(member)); - if (!(type.flags & 1 /* Any */ || getFalsyFlags(type) & 4096 /* Undefined */)) { + if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 8192 /* Undefined */)) { if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) { error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName)); } @@ -46334,7 +51959,7 @@ var ts; } } function isInstancePropertyWithoutInitializer(node) { - return node.kind === 151 /* PropertyDeclaration */ && + return node.kind === 152 /* PropertyDeclaration */ && !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) && !node.exclamationToken && !node.initializer; @@ -46343,7 +51968,7 @@ var ts; var reference = ts.createPropertyAccess(ts.createThis(), propName); reference.flowNode = constructor.returnFlowNode; var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType)); - return !(getFalsyFlags(flowType) & 4096 /* Undefined */); + return !(getFalsyFlags(flowType) & 8192 /* Undefined */); } function checkInterfaceDeclaration(node) { // Grammar checking @@ -46356,7 +51981,7 @@ var ts; var symbol = getSymbolOfNode(node); checkTypeParameterListsIdentical(symbol); // Only check this symbol once - var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 234 /* InterfaceDeclaration */); + var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 239 /* InterfaceDeclaration */); if (node === firstInterfaceDecl) { var type = getDeclaredTypeOfSymbol(symbol); var typeWithThis = getTypeWithThisArgument(type); @@ -46419,7 +52044,7 @@ var ts; } // In ambient enum declarations that specify no const modifier, enum member declarations that omit // a value are considered computed members (as opposed to having auto-incremented values). - if (member.parent.flags & 2097152 /* Ambient */ && !ts.isConst(member.parent)) { + if (member.parent.flags & 4194304 /* Ambient */ && !ts.isEnumConst(member.parent)) { return undefined; } // If the member declaration specifies no value, the member is considered a constant enum member. @@ -46434,7 +52059,7 @@ var ts; } function computeConstantValue(member) { var enumKind = getEnumKind(getSymbolOfNode(member.parent)); - var isConstEnum = ts.isConst(member.parent); + var isConstEnum = ts.isEnumConst(member.parent); var initializer = member.initializer; var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer); if (value !== undefined) { @@ -46451,7 +52076,7 @@ var ts; else if (isConstEnum) { error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); } - else if (member.parent.flags & 2097152 /* Ambient */) { + else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); } else { @@ -46461,7 +52086,7 @@ var ts; return value; function evaluate(expr) { switch (expr.kind) { - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: var value_2 = evaluate(expr.operand); if (typeof value_2 === "number") { switch (expr.operator) { @@ -46471,7 +52096,7 @@ var ts; } } break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: var left = evaluate(expr.left); var right = evaluate(expr.right); if (typeof left === "number" && typeof right === "number") { @@ -46490,24 +52115,31 @@ var ts; case 40 /* AsteriskAsteriskToken */: return Math.pow(left, right); } } + else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 37 /* PlusToken */) { + return left + right; + } break; case 9 /* StringLiteral */: return expr.text; case 8 /* NumericLiteral */: checkGrammarNumericLiteral(expr); return +expr.text; - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return evaluate(expr.expression); case 71 /* Identifier */: - return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), expr.escapedText); - case 184 /* ElementAccessExpression */: - case 183 /* PropertyAccessExpression */: + var identifier = expr; + if (isInfinityOrNaNString(identifier.escapedText)) { + return +(identifier.escapedText); + } + return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: var ex = expr; if (isConstantMemberAccess(ex)) { var type = getTypeOfExpression(ex.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 183 /* PropertyAccessExpression */) { + if (ex.kind === 187 /* PropertyAccessExpression */) { name = ex.name.escapedText; } else { @@ -46539,8 +52171,8 @@ var ts; } function isConstantMemberAccess(node) { return node.kind === 71 /* Identifier */ || - node.kind === 183 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || - node.kind === 184 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && + node.kind === 187 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || + node.kind === 188 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && node.argumentExpression.kind === 9 /* StringLiteral */; } function checkEnumDeclaration(node) { @@ -46550,14 +52182,12 @@ var ts; // Grammar checking checkGrammarDecoratorsAndModifiers(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithCapturedNewTargetVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); computeEnumMemberValues(node); - var enumIsConst = ts.isConst(node); - if (compilerOptions.isolatedModules && enumIsConst && node.flags & 2097152 /* Ambient */) { + var enumIsConst = ts.isEnumConst(node); + if (compilerOptions.isolatedModules && enumIsConst && node.flags & 4194304 /* Ambient */) { error(node.name, ts.Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } // Spec 2014 - Section 9.3: @@ -46572,7 +52202,7 @@ var ts; if (enumSymbol.declarations.length > 1) { // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { - if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { + if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst) { error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); @@ -46580,7 +52210,7 @@ var ts; var seenEnumMissingInitialInitializer_1 = false; ts.forEach(enumSymbol.declarations, function (declaration) { // return true if we hit a violation of the rule, false otherwise - if (declaration.kind !== 236 /* EnumDeclaration */) { + if (declaration.kind !== 241 /* EnumDeclaration */) { return false; } var enumDeclaration = declaration; @@ -46601,11 +52231,11 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { - var declaration = declarations_7[_i]; - if ((declaration.kind === 233 /* ClassDeclaration */ || - (declaration.kind === 232 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && - !(declaration.flags & 2097152 /* Ambient */)) { + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; + if ((declaration.kind === 238 /* ClassDeclaration */ || + (declaration.kind === 237 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && + !(declaration.flags & 4194304 /* Ambient */)) { return declaration; } } @@ -46628,7 +52258,7 @@ var ts; if (produceDiagnostics) { // Grammar checking var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node); - var inAmbientContext = node.flags & 2097152 /* Ambient */; + var inAmbientContext = node.flags & 4194304 /* Ambient */; if (isGlobalAugmentation && !inAmbientContext) { error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context); } @@ -46646,7 +52276,6 @@ var ts; } } if (ts.isIdentifier(node.name)) { - checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); } @@ -46656,7 +52285,7 @@ var ts; if (symbol.flags & 512 /* ValueModule */ && symbol.declarations.length > 1 && !inAmbientContext - && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { + && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) { @@ -46668,7 +52297,7 @@ var ts; } // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - var mergedClass = ts.getDeclarationOfKind(symbol, 233 /* ClassDeclaration */); + var mergedClass = ts.getDeclarationOfKind(symbol, 238 /* ClassDeclaration */); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */; @@ -46718,23 +52347,23 @@ var ts; } function checkModuleAugmentationElement(node, isGlobalAugmentation) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // error each individual name in variable statement instead of marking the entire variable statement for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { var decl = _a[_i]; checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; - case 241 /* ImportEqualsDeclaration */: - case 242 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; - case 180 /* BindingElement */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var name = node.name; if (ts.isBindingPattern(name)) { for (var _b = 0, _c = name.elements; _b < _c.length; _b++) { @@ -46745,12 +52374,12 @@ var ts; break; } // falls through - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 232 /* FunctionDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 237 /* FunctionDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 240 /* TypeAliasDeclaration */: if (isGlobalAugmentation) { return; } @@ -46773,12 +52402,12 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node; - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: do { node = node.left; } while (node.kind !== 71 /* Identifier */); return node; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: do { node = node.expression; } while (node.kind !== 71 /* Identifier */); @@ -46787,7 +52416,7 @@ var ts; } function checkExternalImportOrExportDeclaration(node) { var moduleName = ts.getExternalModuleName(node); - if (ts.nodeIsMissing(moduleName)) { + if (!moduleName || ts.nodeIsMissing(moduleName)) { // Should be a parse error. return false; } @@ -46795,9 +52424,9 @@ var ts; error(moduleName, ts.Diagnostics.String_literal_expected); return false; } - var inAmbientExternalModule = node.parent.kind === 238 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - if (node.parent.kind !== 272 /* SourceFile */ && !inAmbientExternalModule) { - error(moduleName, node.kind === 248 /* ExportDeclaration */ ? + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule) { + error(moduleName, node.kind === 253 /* ExportDeclaration */ ? ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module); return false; @@ -46830,22 +52459,21 @@ var ts; (symbol.flags & 67901928 /* Type */ ? 67901928 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0); if (target.flags & excludedMeanings) { - var message = node.kind === 250 /* ExportSpecifier */ ? + var message = node.kind === 255 /* ExportSpecifier */ ? ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); } // Don't allow to re-export something with no value side when `--isolatedModules` is set. if (compilerOptions.isolatedModules - && node.kind === 250 /* ExportSpecifier */ + && node.kind === 255 /* ExportSpecifier */ && !(target.flags & 67216319 /* Value */) - && !(node.flags & 2097152 /* Ambient */)) { + && !(node.flags & 4194304 /* Ambient */)) { error(node, ts.Diagnostics.Cannot_re_export_a_type_when_the_isolatedModules_flag_is_provided); } } } function checkImportBinding(node) { - checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); checkAliasSymbol(node); @@ -46865,11 +52493,14 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 244 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); } else { - ts.forEach(importClause.namedBindings.elements, checkImportBinding); + var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleExisted) { + ts.forEach(importClause.namedBindings.elements, checkImportBinding); + } } } } @@ -46886,7 +52517,7 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { markExportAsReferenced(node); } - if (node.moduleReference.kind !== 252 /* ExternalModuleReference */) { + if (node.moduleReference.kind !== 257 /* ExternalModuleReference */) { var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 67216319 /* Value */) { @@ -46902,7 +52533,7 @@ var ts; } } else { - if (modulekind >= ts.ModuleKind.ES2015 && !(node.flags & 2097152 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 4194304 /* Ambient */)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, ts.Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -46922,27 +52553,27 @@ var ts; // export { x, y } // export { x, y } from "foo" ts.forEach(node.exportClause.elements, checkExportSpecifier); - var inAmbientExternalModule = node.parent.kind === 238 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); - var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 238 /* ModuleBlock */ && - !node.moduleSpecifier && node.flags & 2097152 /* Ambient */; - if (node.parent.kind !== 272 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { + var inAmbientExternalModule = node.parent.kind === 243 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent); + var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 243 /* ModuleBlock */ && + !node.moduleSpecifier && node.flags & 4194304 /* Ambient */; + if (node.parent.kind !== 277 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) { error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" - var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) { - error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); + var moduleSymbol_2 = resolveExternalModuleName(node, node.moduleSpecifier); + if (moduleSymbol_2 && hasExportAssignmentSymbol(moduleSymbol_2)) { + error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol_2)); } - if (modulekind !== ts.ModuleKind.System && modulekind !== ts.ModuleKind.ES2015 && modulekind !== ts.ModuleKind.ESNext) { + if (moduleKind !== ts.ModuleKind.System && moduleKind !== ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.ESNext) { checkExternalEmitHelpers(node, 32768 /* ExportStar */); } } } } function checkGrammarModuleElementContext(node, errorMessage) { - var isInAppropriateContext = node.parent.kind === 272 /* SourceFile */ || node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 237 /* ModuleDeclaration */; + var isInAppropriateContext = node.parent.kind === 277 /* SourceFile */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 242 /* ModuleDeclaration */; if (!isInAppropriateContext) { grammarErrorOnFirstToken(node, errorMessage); } @@ -46971,8 +52602,8 @@ var ts; // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors. return; } - var container = node.parent.kind === 272 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 237 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { if (node.isExportEquals) { error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); } @@ -46995,15 +52626,15 @@ var ts; checkExpressionCached(node.expression); } checkExternalModuleExports(container); - if ((node.flags & 2097152 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { + if ((node.flags & 4194304 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) { grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } - if (node.isExportEquals && !(node.flags & 2097152 /* Ambient */)) { - if (modulekind >= ts.ModuleKind.ES2015) { + if (node.isExportEquals && !(node.flags & 4194304 /* Ambient */)) { + if (moduleKind >= ts.ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } - else if (modulekind === ts.ModuleKind.System) { + else if (moduleKind === ts.ModuleKind.System) { // system modules does not support export assignment grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); } @@ -47019,14 +52650,14 @@ var ts; var exportEqualsSymbol = moduleSymbol.exports.get("export="); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJavaScriptFile(declaration)) { error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } // Checks for export * conflicts - var exports = getExportsOfModule(moduleSymbol); - if (exports) { - exports.forEach(function (_a, id) { + var exports_2 = getExportsOfModule(moduleSymbol); + if (exports_2) { + exports_2.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -47043,8 +52674,8 @@ var ts; return; } if (exportedDeclarationsCount > 1) { - for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { - var declaration = declarations_8[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; if (isNotOverload(declaration)) { diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id))); } @@ -47060,167 +52691,172 @@ var ts; return !ts.isAccessor(declaration); } function isNotOverload(declaration) { - return (declaration.kind !== 232 /* FunctionDeclaration */ && declaration.kind !== 153 /* MethodDeclaration */) || + return (declaration.kind !== 237 /* FunctionDeclaration */ && declaration.kind !== 154 /* MethodDeclaration */) || !!declaration.body; } function checkSourceElement(node) { if (!node) { return; } - if (ts.isInJavaScriptFile(node) && node.jsDoc) { - for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) { - var tags = _a[_i].tags; - ts.forEach(tags, checkSourceElement); - } + if (ts.isInJavaScriptFile(node)) { + ts.forEach(node.jsDoc, function (_a) { + var tags = _a.tags; + return ts.forEach(tags, checkSourceElement); + }); } var kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessively // hitting the cancellation token on every node we check. switch (kind) { - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } switch (kind) { - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return checkTypeParameter(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return checkParameter(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return checkPropertyDeclaration(node); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 160 /* IndexSignature */: return checkSignatureDeclaration(node); - case 159 /* IndexSignature */: - return checkSignatureDeclaration(node); - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: return checkMethodDeclaration(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return checkConstructorDeclaration(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return checkAccessorDeclaration(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return checkTypeReferenceNode(node); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return checkTypePredicate(node); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return checkTypeQuery(node); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return checkTypeLiteral(node); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return checkArrayType(node); - case 167 /* TupleType */: + case 168 /* TupleType */: return checkTupleType(node); - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return checkUnionOrIntersectionType(node); - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: + case 169 /* OptionalType */: + case 170 /* RestType */: return checkSourceElement(node.type); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return checkTypeOperator(node); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return checkConditionalType(node); - case 171 /* InferType */: + case 174 /* InferType */: return checkInferType(node); - case 285 /* JSDocAugmentsTag */: + case 181 /* ImportType */: + return checkImportType(node); + case 293 /* JSDocAugmentsTag */: return checkJSDocAugmentsTag(node); - case 291 /* JSDocTypedefTag */: - return checkJSDocTypedefTag(node); - case 287 /* JSDocParameterTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + return checkJSDocTypeAliasTag(node); + case 299 /* JSDocTypeTag */: + return checkJSDocTypeTag(node); + case 296 /* JSDocParameterTag */: return checkJSDocParameterTag(node); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: checkSignatureDeclaration(node); // falls through - case 278 /* JSDocNonNullableType */: - case 277 /* JSDocNullableType */: - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 285 /* JSDocNonNullableType */: + case 284 /* JSDocNullableType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: + case 290 /* JSDocTypeLiteral */: checkJSDocTypeIsInJsFile(node); ts.forEachChild(node, checkSourceElement); return; - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: checkJSDocVariadicType(node); return; - case 274 /* JSDocTypeExpression */: + case 281 /* JSDocTypeExpression */: return checkSourceElement(node.type); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return checkIndexedAccessType(node); - case 176 /* MappedType */: + case 179 /* MappedType */: return checkMappedType(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 211 /* Block */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return checkBlock(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return checkVariableStatement(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return checkExpressionStatement(node); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return checkIfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return checkDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return checkWhileStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return checkForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return checkForInStatement(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return checkForOfStatement(node); - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return checkReturnStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return checkWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return checkSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return checkLabeledStatement(node); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return checkThrowStatement(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return checkTryStatement(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return checkVariableDeclaration(node); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return checkBindingElement(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return checkClassDeclaration(node); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return checkInterfaceDeclaration(node); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return checkTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return checkEnumDeclaration(node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return checkModuleDeclaration(node); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return checkImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return checkImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return checkExportDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return checkExportAssignment(node); - case 213 /* EmptyStatement */: + case 218 /* EmptyStatement */: + case 234 /* DebuggerStatement */: checkGrammarStatementInAmbientContext(node); return; - case 229 /* DebuggerStatement */: - checkGrammarStatementInAmbientContext(node); - return; - case 251 /* MissingDeclaration */: + case 256 /* MissingDeclaration */: return checkMissingDeclaration(node); } } @@ -47232,12 +52868,18 @@ var ts; function checkJSDocVariadicType(node) { checkJSDocTypeIsInJsFile(node); checkSourceElement(node.type); - // Only legal location is in the *last* parameter tag. + // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function. var parent = node.parent; + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + if (ts.last(parent.parent.parameters) !== parent) { + error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); + } + return; + } if (!ts.isJSDocTypeExpression(parent)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); } - var paramTag = parent.parent; + var paramTag = node.parent.parent; if (!ts.isJSDocParameterTag(paramTag)) { error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature); return; @@ -47255,8 +52897,8 @@ var ts; function getTypeFromJSDocVariadicType(node) { var type = getTypeFromTypeNode(node.type); var parent = node.parent; - var paramTag = parent.parent; - if (ts.isJSDocTypeExpression(parent) && ts.isJSDocParameterTag(paramTag)) { + var paramTag = node.parent.parent; + if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) { // Else we will add a diagnostic, see `checkJSDocVariadicType`. var host_1 = ts.getHostSignatureFromJSDoc(paramTag); if (host_1) { @@ -47275,6 +52917,9 @@ var ts; } } } + if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) { + return createArrayType(type); + } return addOptionality(type); } // Function and class expression bodies are checked after all statements in the enclosing body. This is @@ -47288,28 +52933,34 @@ var ts; // Delaying the type check of the body ensures foo has been assigned a type. function checkNodeDeferred(node) { if (deferredNodes) { - deferredNodes.push(node); + var id = "" + getNodeId(node); + deferredNodes.set(id, node); } } function checkDeferredNodes() { - for (var _i = 0, deferredNodes_1 = deferredNodes; _i < deferredNodes_1.length; _i++) { - var node = deferredNodes_1[_i]; + deferredNodes.forEach(function (node) { switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: checkFunctionExpressionOrObjectLiteralMethodDeferred(node); break; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: checkAccessorDeclaration(node); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: checkClassExpressionDeferred(node); break; + case 259 /* JsxSelfClosingElement */: + checkJsxSelfClosingElementDeferred(node); + break; + case 258 /* JsxElement */: + checkJsxElementDeferred(node); + break; } - } + }); } function checkSourceFile(node) { ts.performance.mark("beforeCheck"); @@ -47317,6 +52968,19 @@ var ts; ts.performance.mark("afterCheck"); ts.performance.measure("Check", "beforeCheck", "afterCheck"); } + function unusedIsError(kind) { + switch (kind) { + case 0 /* Local */: + return !!compilerOptions.noUnusedLocals; + case 1 /* Parameter */: + return !!compilerOptions.noUnusedParameters; + default: + return ts.Debug.assertNever(kind); + } + } + function getPotentiallyUnusedIdentifiers(sourceFile) { + return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray; + } // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node) { var links = getNodeLinks(node); @@ -47331,19 +52995,20 @@ var ts; checkGrammarSourceFile(node); ts.clear(potentialThisCollisions); ts.clear(potentialNewTargetCollisions); - deferredNodes = []; - deferredUnusedIdentifierNodes = produceDiagnostics && noUnusedIdentifiers ? [] : undefined; - flowAnalysisDisabled = false; + deferredNodes = ts.createMap(); ts.forEach(node.statements, checkSourceElement); checkDeferredNodes(); if (ts.isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); } - if (!node.isDeclarationFile) { - checkUnusedIdentifiers(); + if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) { + checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) { + if (!ts.containsParseError(containingNode) && unusedIsError(kind)) { + diagnostics.add(diag); + } + }); } deferredNodes = undefined; - deferredUnusedIdentifierNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -47410,7 +53075,7 @@ var ts; } // Language service support function getSymbolsInScope(location, meaning) { - if (location.flags & 4194304 /* InWithStatement */) { + if (location.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return []; } @@ -47424,13 +53089,13 @@ var ts; copySymbols(location.locals, meaning); } switch (location.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: var className = location.name; if (className) { copySymbol(location.symbol, meaning); @@ -47438,8 +53103,8 @@ var ts; // falls through // this fall-through is necessary because we would like to handle // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: // If we didn't come from static member of class or interface, // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. @@ -47448,7 +53113,7 @@ var ts; copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 67901928 /* Type */); } break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: var funcName = location.name; if (funcName) { copySymbol(location.symbol, meaning); @@ -47496,28 +53161,28 @@ var ts; } function isTypeDeclaration(node) { switch (node.kind) { - case 147 /* TypeParameter */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: + case 148 /* TypeParameter */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: return true; + default: + return false; } } // True if the given identifier is part of a type reference - function isTypeReferenceIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 145 /* QualifiedName */) { + function isTypeReferenceIdentifier(node) { + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } - return node.parent && node.parent.kind === 161 /* TypeReference */; + return node.parent.kind === 162 /* TypeReference */; } - function isHeritageClauseElementIdentifier(entityName) { - var node = entityName; - while (node.parent && node.parent.kind === 183 /* PropertyAccessExpression */) { + function isHeritageClauseElementIdentifier(node) { + while (node.parent.kind === 187 /* PropertyAccessExpression */) { node = node.parent; } - return node.parent && node.parent.kind === 205 /* ExpressionWithTypeArguments */; + return node.parent.kind === 209 /* ExpressionWithTypeArguments */; } function forEachEnclosingClass(node, callback) { var result; @@ -47545,14 +53210,14 @@ var ts; return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; }); } function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) { - while (nodeOnRightSide.parent.kind === 145 /* QualifiedName */) { + while (nodeOnRightSide.parent.kind === 146 /* QualifiedName */) { nodeOnRightSide = nodeOnRightSide.parent; } - if (nodeOnRightSide.parent.kind === 241 /* ImportEqualsDeclaration */) { - return nodeOnRightSide.parent.moduleReference === nodeOnRightSide && nodeOnRightSide.parent; + if (nodeOnRightSide.parent.kind === 246 /* ImportEqualsDeclaration */) { + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } - if (nodeOnRightSide.parent.kind === 247 /* ExportAssignment */) { - return nodeOnRightSide.parent.expression === nodeOnRightSide && nodeOnRightSide.parent; + if (nodeOnRightSide.parent.kind === 252 /* ExportAssignment */) { + return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } return undefined; } @@ -47571,12 +53236,23 @@ var ts; return getSymbolOfNode(entityName.parent.parent); } } + function isImportTypeQualifierPart(node) { + var parent = node.parent; + while (ts.isQualifiedName(parent)) { + node = parent; + parent = parent.parent; + } + if (parent && parent.kind === 181 /* ImportType */ && parent.qualifier === node) { + return parent; + } + return undefined; + } function getSymbolOfEntityNameOrPropertyAccessExpression(entityName) { if (ts.isDeclarationName(entityName)) { return getSymbolOfNode(entityName.parent); } if (ts.isInJavaScriptFile(entityName) && - entityName.parent.kind === 183 /* PropertyAccessExpression */ && + entityName.parent.kind === 187 /* PropertyAccessExpression */ && entityName.parent === entityName.parent.parent.left) { // Check if this is a special property assignment var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(entityName); @@ -47584,23 +53260,35 @@ var ts; return specialPropertyAssignmentSymbol; } } - if (entityName.parent.kind === 247 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { - return resolveEntityName(entityName, - /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + if (entityName.parent.kind === 252 /* ExportAssignment */ && ts.isEntityNameExpression(entityName)) { + // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression + var success = resolveEntityName(entityName, + /*all meanings*/ 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true); + if (success && success !== unknownSymbol) { + return success; + } } - if (entityName.kind !== 183 /* PropertyAccessExpression */ && isInRightSideOfImportOrExportAssignment(entityName)) { + else if (!ts.isPropertyAccessExpression(entityName) && isInRightSideOfImportOrExportAssignment(entityName)) { // Since we already checked for ExportAssignment, this really could only be an Import - var importEqualsDeclaration = ts.getAncestor(entityName, 241 /* ImportEqualsDeclaration */); + var importEqualsDeclaration = ts.getAncestor(entityName, 246 /* ImportEqualsDeclaration */); ts.Debug.assert(importEqualsDeclaration !== undefined); return getSymbolOfPartOfRightHandSideOfImportEquals(entityName, /*dontResolveAlias*/ true); } - if (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { + if (!ts.isPropertyAccessExpression(entityName)) { + var possibleImportNode = isImportTypeQualifierPart(entityName); + if (possibleImportNode) { + getTypeFromTypeNode(possibleImportNode); + var sym = getNodeLinks(entityName).resolvedSymbol; + return sym === unknownSymbol ? undefined : sym; + } + } + while (ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; } if (isHeritageClauseElementIdentifier(entityName)) { var meaning = 0 /* None */; // In an interface or class, we're definitely interested in a type. - if (entityName.parent.kind === 205 /* ExpressionWithTypeArguments */) { + if (entityName.parent.kind === 209 /* ExpressionWithTypeArguments */) { meaning = 67901928 /* Type */; // In a class 'extends' clause we are also looking for a value. if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent)) { @@ -47616,10 +53304,10 @@ var ts; return entityNameSymbol; } } - if (entityName.parent.kind === 287 /* JSDocParameterTag */) { + if (entityName.parent.kind === 296 /* JSDocParameterTag */) { return ts.getParameterSymbolFromJSDoc(entityName.parent); } - if (entityName.parent.kind === 147 /* TypeParameter */ && entityName.parent.parent.kind === 290 /* JSDocTemplateTag */) { + if (entityName.parent.kind === 148 /* TypeParameter */ && entityName.parent.parent.kind === 300 /* JSDocTemplateTag */) { ts.Debug.assert(!ts.isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. var typeParameter = ts.getTypeParameterFromJsDoc(entityName.parent); return typeParameter && typeParameter.symbol; @@ -47636,12 +53324,12 @@ var ts; } return resolveEntityName(entityName, 67216319 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.kind === 183 /* PropertyAccessExpression */ || entityName.kind === 145 /* QualifiedName */) { + else if (entityName.kind === 187 /* PropertyAccessExpression */ || entityName.kind === 146 /* QualifiedName */) { var links = getNodeLinks(entityName); if (links.resolvedSymbol) { return links.resolvedSymbol; } - if (entityName.kind === 183 /* PropertyAccessExpression */) { + if (entityName.kind === 187 /* PropertyAccessExpression */) { checkPropertyAccessExpression(entityName); } else { @@ -47651,41 +53339,43 @@ var ts; } } else if (isTypeReferenceIdentifier(entityName)) { - var meaning = entityName.parent.kind === 161 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; + var meaning = entityName.parent.kind === 162 /* TypeReference */ ? 67901928 /* Type */ : 1920 /* Namespace */; return resolveEntityName(entityName, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); } - else if (entityName.parent.kind === 260 /* JsxAttribute */) { + else if (entityName.parent.kind === 265 /* JsxAttribute */) { return getJsxAttributePropertySymbol(entityName.parent); } - if (entityName.parent.kind === 160 /* TypePredicate */) { + if (entityName.parent.kind === 161 /* TypePredicate */) { return resolveEntityName(entityName, /*meaning*/ 1 /* FunctionScopedVariable */); } // Do we want to return undefined here? return undefined; } function getSymbolAtLocation(node) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined; } - if (node.flags & 4194304 /* InWithStatement */) { + var parent = node.parent; + var grandParent = parent.parent; + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; } if (isDeclarationNameOrImportPropertyName(node)) { // This is a declaration, call getSymbolOfNode - return getSymbolOfNode(node.parent); + return getSymbolOfNode(parent); } else if (ts.isLiteralComputedPropertyDeclarationName(node)) { - return getSymbolOfNode(node.parent.parent); + return getSymbolOfNode(parent.parent); } if (node.kind === 71 /* Identifier */) { if (isInRightSideOfImportOrExportAssignment(node)) { return getSymbolOfEntityNameOrPropertyAccessExpression(node); } - else if (node.parent.kind === 180 /* BindingElement */ && - node.parent.parent.kind === 178 /* ObjectBindingPattern */ && - node === node.parent.propertyName) { - var typeOfPattern = getTypeOfNode(node.parent.parent); + else if (parent.kind === 184 /* BindingElement */ && + grandParent.kind === 182 /* ObjectBindingPattern */ && + node === parent.propertyName) { + var typeOfPattern = getTypeOfNode(grandParent); var propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; @@ -47694,8 +53384,8 @@ var ts; } switch (node.kind) { case 71 /* Identifier */: - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: return getSymbolOfEntityNameOrPropertyAccessExpression(node); case 99 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); @@ -47709,14 +53399,14 @@ var ts; return checkExpression(node).symbol; } // falls through - case 173 /* ThisType */: + case 176 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 97 /* SuperKeyword */: return checkExpression(node).symbol; case 123 /* ConstructorKeyword */: // constructor keyword for an overload, should take us to the definition if it exist var constructorDeclaration = node.parent; - if (constructorDeclaration && constructorDeclaration.kind === 154 /* Constructor */) { + if (constructorDeclaration && constructorDeclaration.kind === 155 /* Constructor */) { return constructorDeclaration.parent.symbol; } return undefined; @@ -47725,33 +53415,34 @@ var ts; // 1). import x = require("./mo/*gotToDefinitionHere*/d") // 2). External module name in an import declaration // 3). Dynamic import call or require in javascript + // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 242 /* ImportDeclaration */ || node.parent.kind === 248 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || - ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { + ((node.parent.kind === 247 /* ImportDeclaration */ || node.parent.kind === 253 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) || + (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) { return resolveExternalModuleName(node, node); } // falls through case 8 /* NumericLiteral */: // index access - var objectType = ts.isElementAccessExpression(node.parent) - ? node.parent.argumentExpression === node ? getTypeOfExpression(node.parent.expression) : undefined - : ts.isLiteralTypeNode(node.parent) && ts.isIndexedAccessTypeNode(node.parent.parent) - ? getTypeFromTypeNode(node.parent.parent.objectType) + var objectType = ts.isElementAccessExpression(parent) + ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined + : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent) + ? getTypeFromTypeNode(grandParent.objectType) : undefined; return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text)); case 79 /* DefaultKeyword */: case 89 /* FunctionKeyword */: case 36 /* EqualsGreaterThanToken */: return getSymbolOfNode(node.parent); + case 181 /* ImportType */: + return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal) : undefined; default: return undefined; } } function getShorthandAssignmentValueSymbol(location) { - // The function returns a value symbol of an identifier in the short-hand property assignment. - // This is necessary as an identifier in short-hand property assignment can contains two meaning: - // property name and property value. - if (location && location.kind === 269 /* ShorthandPropertyAssignment */) { + if (location && location.kind === 274 /* ShorthandPropertyAssignment */) { return resolveEntityName(location.name, 67216319 /* Value */ | 2097152 /* Alias */); } return undefined; @@ -47763,9 +53454,9 @@ var ts; resolveEntityName(node.propertyName || node.name, 67216319 /* Value */ | 67901928 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } function getTypeOfNode(node) { - if (node.flags & 4194304 /* InWithStatement */) { + if (node.flags & 8388608 /* InWithStatement */) { // We cannot answer semantic questions within a with block, do not proceed any further - return unknownType; + return errorType; } if (ts.isPartOfTypeNode(node)) { var typeFromTypeNode = getTypeFromTypeNode(node); @@ -47794,7 +53485,7 @@ var ts; } if (isTypeDeclarationName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getDeclaredTypeOfSymbol(symbol); + return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType; } if (ts.isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration @@ -47803,19 +53494,19 @@ var ts; } if (isDeclarationNameOrImportPropertyName(node)) { var symbol = getSymbolAtLocation(node); - return symbol && getTypeOfSymbol(symbol); + return symbol ? getTypeOfSymbol(symbol) : errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true); + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); if (symbol) { var declaredType = getDeclaredTypeOfSymbol(symbol); - return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); + return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol); } } - return unknownType; + return errorType; } // Gets the type of object literal or array literal of destructuring assignment. // { a } from @@ -47824,32 +53515,32 @@ var ts; // [ a ] from // [a] = [ some array ...] function getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr) { - ts.Debug.assert(expr.kind === 182 /* ObjectLiteralExpression */ || expr.kind === 181 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.kind === 186 /* ObjectLiteralExpression */ || expr.kind === 185 /* ArrayLiteralExpression */); // If this is from "for of" // for ( { a } of elems) { // } - if (expr.parent.kind === 220 /* ForOfStatement */) { + if (expr.parent.kind === 225 /* ForOfStatement */) { var iteratedType = checkRightHandSideOfForOf(expr.parent.expression, expr.parent.awaitModifier); - return checkDestructuringAssignment(expr, iteratedType || unknownType); + return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } - if (expr.parent.kind === 198 /* BinaryExpression */) { + if (expr.parent.kind === 202 /* BinaryExpression */) { var iteratedType = getTypeOfExpression(expr.parent.right); - return checkDestructuringAssignment(expr, iteratedType || unknownType); + return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern // for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) { - if (expr.parent.kind === 268 /* PropertyAssignment */) { + if (expr.parent.kind === 273 /* PropertyAssignment */) { var typeOfParentObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent.parent); - return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || unknownType, expr.parent); + return checkObjectLiteralDestructuringPropertyAssignment(typeOfParentObjectLiteral || errorType, expr.parent); // TODO: GH#18217 } // Array literal assignment - array destructuring pattern - ts.Debug.assert(expr.parent.kind === 181 /* ArrayLiteralExpression */); + ts.Debug.assert(expr.parent.kind === 185 /* ArrayLiteralExpression */); // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); - var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); + var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || errorType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || errorType; + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || errorType); // TODO: GH#18217 } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -47920,11 +53611,11 @@ var ts; return target; } // Emitter support - function isArgumentsLocalBinding(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function isArgumentsLocalBinding(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { - var isPropertyName_1 = node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node; + var isPropertyName_1 = node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol; } } @@ -47955,13 +53646,12 @@ var ts; } } function isNameOfModuleOrEnumDeclaration(node) { - var parent = node.parent; - return parent && ts.isModuleOrEnumDeclaration(parent) && node === parent.name; + return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name; } // When resolved as an expression identifier, if the given node references an exported entity, return the declaration // node of the exported entity's container. Otherwise, return undefined. - function getReferencedExportContainer(node, prefixLocals) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedExportContainer(nodeIn, prefixLocals) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { // When resolving the export container for the name of a module or enum // declaration, we need to start resolution at the declaration's container. @@ -47981,7 +53671,7 @@ var ts; } var parentSymbol_1 = getParentOfSymbol(symbol); if (parentSymbol_1) { - if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 272 /* SourceFile */) { + if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 277 /* SourceFile */) { var symbolFile = parentSymbol_1.valueDeclaration; var referenceFile = ts.getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. @@ -47995,8 +53685,8 @@ var ts; } // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. - function getReferencedImportDeclaration(node) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedImportDeclaration(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); // We should only get the declaration of an alias if there isn't a local value @@ -48036,7 +53726,7 @@ var ts; // they will not collide with anything var isDeclaredInLoop = nodeLinks_1.flags & 262144 /* BlockScopedBindingInLoop */; var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false); - var inLoopBodyBlock = container.kind === 211 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); + var inLoopBodyBlock = container.kind === 216 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false); links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock)); } else { @@ -48051,9 +53741,9 @@ var ts; // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that either hides an existing name or might hide it when compiled downlevel, // return the declaration of that entity. Otherwise, return undefined. - function getReferencedDeclarationWithCollidingName(node) { - if (!ts.isGeneratedIdentifier(node)) { - node = ts.getParseTreeNode(node, ts.isIdentifier); + function getReferencedDeclarationWithCollidingName(nodeIn) { + if (!ts.isGeneratedIdentifier(nodeIn)) { + var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier); if (node) { var symbol = getReferencedValueSymbol(node); if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) { @@ -48065,8 +53755,8 @@ var ts; } // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an // existing name or might hide a name when compiled downlevel - function isDeclarationWithCollidingName(node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + function isDeclarationWithCollidingName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); if (node) { var symbol = getSymbolOfNode(node); if (symbol) { @@ -48077,16 +53767,16 @@ var ts; } function isValueAliasDeclaration(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: var exportClause = node.exportClause; - return exportClause && ts.forEach(exportClause.elements, isValueAliasDeclaration); - case 247 /* ExportAssignment */: + return !!exportClause && ts.some(exportClause.elements, isValueAliasDeclaration); + case 252 /* ExportAssignment */: return node.expression && node.expression.kind === 71 /* Identifier */ ? isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) @@ -48094,9 +53784,9 @@ var ts; } return false; } - function isTopLevelValueImportEqualsWithEntityName(node) { - node = ts.getParseTreeNode(node, ts.isImportEqualsDeclaration); - if (node === undefined || node.parent.kind !== 272 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { + function isTopLevelValueImportEqualsWithEntityName(nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration); + if (node === undefined || node.parent.kind !== 277 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) { // parent is not source file or it is not reference to internal module return false; } @@ -48110,11 +53800,11 @@ var ts; } // const enums and modules that contain only const enums are not considered values from the emit perspective // unless 'preserveConstEnums' option is set to true - return target.flags & 67216319 /* Value */ && + return !!(target.flags & 67216319 /* Value */) && (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s) { - return isConstEnumSymbol(s) || s.constEnumOnlyModule; + return isConstEnumSymbol(s) || !!s.constEnumOnlyModule; } function isReferencedAliasDeclaration(node, checkChildren) { if (ts.isAliasSymbolDeclaration(node)) { @@ -48122,19 +53812,21 @@ var ts; if (symbol && getSymbolLinks(symbol).referenced) { return true; } - var target = getSymbolLinks(symbol).target; + var target = getSymbolLinks(symbol).target; // TODO: GH#18217 if (target && ts.getModifierFlags(node) & 1 /* Export */ && target.flags & 67216319 /* Value */) { // An `export import ... =` of a value symbol is always considered referenced return true; } } if (checkChildren) { - return ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); + return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); }); } return false; } function isImplementationOfOverload(node) { if (ts.nodeIsPresent(node.body)) { + if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) + return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -48154,9 +53846,10 @@ var ts; return false; } function isRequiredInitializedParameter(parameter) { - return strictNullChecks && + return !!strictNullChecks && !isOptionalParameter(parameter) && - parameter.initializer && + !ts.isJSDocParameterTag(parameter) && + !!parameter.initializer && !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function isOptionalUninitializedParameterProperty(parameter) { @@ -48166,7 +53859,7 @@ var ts; ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */); } function getNodeCheckFlags(node) { - return getNodeLinks(node).flags; + return getNodeLinks(node).flags || 0; } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); @@ -48174,32 +53867,33 @@ var ts; } function canHaveConstantValue(node) { switch (node.kind) { - case 271 /* EnumMember */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: + case 276 /* EnumMember */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: return true; } return false; } function getConstantValue(node) { - if (node.kind === 271 /* EnumMember */) { + if (node.kind === 276 /* EnumMember */) { return getEnumMemberValue(node); } var symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & 8 /* EnumMember */)) { // inline property\index accesses only for const enums - if (ts.isConstEnumDeclaration(symbol.valueDeclaration.parent)) { - return getEnumMemberValue(symbol.valueDeclaration); + var member = symbol.valueDeclaration; + if (ts.isEnumConst(member.parent)) { + return getEnumMemberValue(member); } } return undefined; } function isFunctionType(type) { - return type.flags & 65536 /* Object */ && getSignaturesOfType(type, 0 /* Call */).length > 0; + return !!(type.flags & 131072 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0; } - function getTypeReferenceSerializationKind(typeName, location) { + function getTypeReferenceSerializationKind(typeNameIn, location) { // ensure both `typeName` and `location` are parse tree nodes. - typeName = ts.getParseTreeNode(typeName, ts.isEntityName); + var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName); if (!typeName) return ts.TypeReferenceSerializationKind.Unknown; if (location) { @@ -48223,31 +53917,31 @@ var ts; } // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { - return ts.TypeReferenceSerializationKind.ObjectType; - } - var type = getDeclaredTypeOfSymbol(typeSymbol); - if (type === unknownType) { return ts.TypeReferenceSerializationKind.Unknown; } - else if (type.flags & 1 /* Any */) { + var type = getDeclaredTypeOfSymbol(typeSymbol); + if (type === errorType) { + return ts.TypeReferenceSerializationKind.Unknown; + } + else if (type.flags & 3 /* AnyOrUnknown */) { return ts.TypeReferenceSerializationKind.ObjectType; } - else if (isTypeAssignableToKind(type, 2048 /* Void */ | 12288 /* Nullable */ | 16384 /* Never */)) { + else if (isTypeAssignableToKind(type, 4096 /* Void */ | 24576 /* Nullable */ | 32768 /* Never */)) { return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType; } - else if (isTypeAssignableToKind(type, 136 /* BooleanLike */)) { + else if (isTypeAssignableToKind(type, 272 /* BooleanLike */)) { return ts.TypeReferenceSerializationKind.BooleanType; } - else if (isTypeAssignableToKind(type, 84 /* NumberLike */)) { + else if (isTypeAssignableToKind(type, 168 /* NumberLike */)) { return ts.TypeReferenceSerializationKind.NumberLikeType; } - else if (isTypeAssignableToKind(type, 524322 /* StringLike */)) { + else if (isTypeAssignableToKind(type, 68 /* StringLike */)) { return ts.TypeReferenceSerializationKind.StringLikeType; } else if (isTupleType(type)) { return ts.TypeReferenceSerializationKind.ArrayLikeType; } - else if (isTypeAssignableToKind(type, 1536 /* ESSymbolLike */)) { + else if (isTypeAssignableToKind(type, 3072 /* ESSymbolLike */)) { return ts.TypeReferenceSerializationKind.ESSymbolType; } else if (isFunctionType(type)) { @@ -48260,28 +53954,40 @@ var ts; return ts.TypeReferenceSerializationKind.ObjectType; } } - function writeTypeOfDeclaration(declaration, enclosingDeclaration, flags, writer) { + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) { + var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor); + if (!declaration) { + return ts.createToken(119 /* AnyKeyword */); + } // Get type of the symbol if this is the valid symbol otherwise get type at location var symbol = getSymbolOfNode(declaration); var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) - : unknownType; - if (type.flags & 1024 /* UniqueESSymbol */ && + : errorType; + if (type.flags & 2048 /* UniqueESSymbol */ && type.symbol === symbol) { flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 131072 /* AddUndefined */) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike); + if (!signatureDeclaration) { + return ts.createToken(119 /* AnyKeyword */); + } var signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } - function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + var expr = ts.getParseTreeNode(exprIn, ts.isExpression); + if (!expr) { + return ts.createToken(119 /* AnyKeyword */); + } var type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -48302,9 +54008,9 @@ var ts; } return resolveName(location, reference.escapedText, 67216319 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); } - function getReferencedValueDeclaration(reference) { - if (!ts.isGeneratedIdentifier(reference)) { - reference = ts.getParseTreeNode(reference, ts.isIdentifier); + function getReferencedValueDeclaration(referenceIn) { + if (!ts.isGeneratedIdentifier(referenceIn)) { + var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier); if (reference) { var symbol = getReferencedValueSymbol(reference); if (symbol) { @@ -48315,15 +54021,18 @@ var ts; return undefined; } function isLiteralConstDeclaration(node) { - if (ts.isConst(node)) { + if (ts.isVariableDeclaration(node) && ts.isVarConst(node)) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - return !!(type.flags & 96 /* StringOrNumberLiteral */ && type.flags & 8388608 /* FreshLiteral */); + return !!(type.flags & 192 /* StringOrNumberLiteral */ && type.flags & 33554432 /* FreshLiteral */); } return false; } - function writeLiteralConstValue(node, writer) { + function literalTypeToNode(type) { + return ts.createLiteral(type.value); + } + function createLiteralConstValue(node) { var type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver() { // this variable and functions that use it are deliberately moved here from the outer scope @@ -48334,7 +54043,7 @@ var ts; // populate reverse mapping: file path -> type reference directive that was resolved to this file fileToDirective = ts.createMap(); resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) { - if (!resolvedDirective) { + if (!resolvedDirective || !resolvedDirective.resolvedFileName) { return; } var file = host.getSourceFile(resolvedDirective.resolvedFileName); @@ -48359,20 +54068,21 @@ var ts; }, getNodeCheckFlags: function (node) { node = ts.getParseTreeNode(node); - return node ? getNodeCheckFlags(node) : undefined; + return node ? getNodeCheckFlags(node) : 0; }, isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration: writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression: writeTypeOfExpression, + createTypeOfDeclaration: createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, + createTypeOfExpression: createTypeOfExpression, + createLiteralConstValue: createLiteralConstValue, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, - getConstantValue: function (node) { - node = ts.getParseTreeNode(node, canHaveConstantValue); + getConstantValue: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; }, collectLinkedAliases: collectLinkedAliases, @@ -48385,26 +54095,44 @@ var ts; getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName, getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol, isLiteralConstDeclaration: isLiteralConstDeclaration, - isLateBound: function (node) { - node = ts.getParseTreeNode(node, ts.isDeclaration); + isLateBound: function (nodeIn) { + var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); }, - writeLiteralConstValue: writeLiteralConstValue, - getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; } + getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, + getAllAccessorDeclarations: function (accessor) { + accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217 + var otherKind = accessor.kind === 157 /* SetAccessor */ ? 156 /* GetAccessor */ : 157 /* SetAccessor */; + var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind); + var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor; + var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor; + var setAccessor = accessor.kind === 157 /* SetAccessor */ ? accessor : otherAccessor; + var getAccessor = accessor.kind === 156 /* GetAccessor */ ? accessor : otherAccessor; + return { + firstAccessor: firstAccessor, + secondAccessor: secondAccessor, + setAccessor: setAccessor, + getAccessor: getAccessor + }; + } }; + function isInHeritageClause(node) { + return node.parent && node.parent.kind === 209 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 271 /* HeritageClause */; + } // defined here to avoid outer scope pollution function getTypeReferenceDirectivesForEntityName(node) { // program does not have any files with type reference directives - bail out if (!fileToDirective) { return undefined; } - // property access can only be used as values + // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause // qualified names can only be used as types\namespaces // identifiers are treated as values only if they appear in type queries - var meaning = (node.kind === 183 /* PropertyAccessExpression */) || (node.kind === 71 /* Identifier */ && isInTypeQuery(node)) - ? 67216319 /* Value */ | 1048576 /* ExportValue */ - : 67901928 /* Type */ | 1920 /* Namespace */; + var meaning = 67901928 /* Type */ | 1920 /* Namespace */; + if ((node.kind === 71 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 187 /* PropertyAccessExpression */ && !isInHeritageClause(node))) { + meaning = 67216319 /* Value */ | 1048576 /* ExportValue */; + } var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true); return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined; } @@ -48453,7 +54181,7 @@ var ts; break; } } - if (current.valueDeclaration && current.valueDeclaration.kind === 272 /* SourceFile */ && current.flags & 512 /* ValueModule */) { + if (current.valueDeclaration && current.valueDeclaration.kind === 277 /* SourceFile */ && current.flags & 512 /* ValueModule */) { return false; } // check that at least one declaration of top level symbol originates from type declaration file @@ -48468,12 +54196,12 @@ var ts; } } function getExternalModuleFileFromDeclaration(declaration) { - var specifier = ts.getExternalModuleName(declaration); - var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); + var specifier = declaration.kind === 242 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration); + var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217 if (!moduleSymbol) { return undefined; } - return ts.getDeclarationOfKind(moduleSymbol, 272 /* SourceFile */); + return ts.getDeclarationOfKind(moduleSymbol, 277 /* SourceFile */); } function initializeTypeChecker() { // Bind all source files and propagate errors @@ -48481,10 +54209,14 @@ var ts; var file = _a[_i]; ts.bindSourceFile(file, compilerOptions); } + amalgamatedDuplicates = ts.createMap(); // Initialize global symbol table var augmentations; for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) { var file = _c[_b]; + if (file.redirectInfo) { + continue; + } if (!ts.isExternalOrCommonJsModule(file)) { mergeSymbolTable(globals, file.locals); } @@ -48504,7 +54236,7 @@ var ts; }); } } - // We do global augmentations seperately from module augmentations (and before creating global types) because they + // We do global augmentations separately from module augmentations (and before creating global types) because they // 1. Affect global types. We won't have the correct global types until global augmentations are merged. Also, // 2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require // checking for an export or property on the module (if export=) which, in turn, can fall back to the @@ -48527,7 +54259,7 @@ var ts; addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0); getSymbolLinks(undefinedSymbol).type = undefinedWideningType; getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true); - getSymbolLinks(unknownSymbol).type = unknownType; + getSymbolLinks(unknownSymbol).type = errorType; // Initialize special types globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true); globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true); @@ -48558,11 +54290,37 @@ var ts; } } } + amalgamatedDuplicates.forEach(function (_a) { + var firstFile = _a.firstFile, secondFile = _a.secondFile, firstFileInstances = _a.firstFileInstances, secondFileInstances = _a.secondFileInstances; + var conflictingKeys = ts.arrayFrom(firstFileInstances.keys()); + // If not many things conflict, issue individual errors + if (conflictingKeys.length < 8) { + addErrorsForDuplicates(firstFileInstances, secondFileInstances); + addErrorsForDuplicates(secondFileInstances, firstFileInstances); + return; + } + // Otheriwse issue top-level error since the files appear very identical in terms of what they appear + var list = conflictingKeys.join(", "); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Conflicts_are_in_this_file))); + diagnostics.add(addRelatedInfo(ts.createDiagnosticForNode(secondFile, ts.Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list), ts.createDiagnosticForNode(firstFile, ts.Diagnostics.Conflicts_are_in_this_file))); + }); + amalgamatedDuplicates = undefined; + function addErrorsForDuplicates(secondFileInstances, firstFileInstances) { + secondFileInstances.forEach(function (locations, symbolName) { + var firstFileEquivalent = firstFileInstances.get(symbolName); + var message = locations.blockScoped + ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + : ts.Diagnostics.Duplicate_identifier_0; + locations.instances.forEach(function (node) { + addDuplicateDeclarationError(node, message, symbolName, firstFileEquivalent.instances[0]); + }); + }); + } } function checkExternalEmitHelpers(location, helpers) { if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { var sourceFile = ts.getSourceFileOfNode(location); - if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 2097152 /* Ambient */)) { + if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 4194304 /* Ambient */)) { var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; @@ -48599,7 +54357,7 @@ var ts; case 16384 /* AsyncValues */: return "__asyncValues"; case 32768 /* ExportStar */: return "__exportStar"; case 65536 /* MakeTemplateObject */: return "__makeTemplateObject"; - default: ts.Debug.fail("Unrecognized helper"); + default: return ts.Debug.fail("Unrecognized helper"); } } function resolveHelpersModule(node, errorNode) { @@ -48617,14 +54375,14 @@ var ts; return false; } if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) { - if (node.kind === 153 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { + if (node.kind === 154 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload); } else { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here); } } - else if (node.kind === 155 /* GetAccessor */ || node.kind === 156 /* SetAccessor */) { + else if (node.kind === 156 /* GetAccessor */ || node.kind === 157 /* SetAccessor */) { var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); @@ -48642,16 +54400,16 @@ var ts; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; if (modifier.kind !== 132 /* ReadonlyKeyword */) { - if (node.kind === 150 /* PropertySignature */ || node.kind === 152 /* MethodSignature */) { + if (node.kind === 151 /* PropertySignature */ || node.kind === 153 /* MethodSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind)); } - if (node.kind === 159 /* IndexSignature */) { + if (node.kind === 160 /* IndexSignature */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind)); } } switch (modifier.kind) { case 76 /* ConstKeyword */: - if (node.kind !== 236 /* EnumDeclaration */ && node.parent.kind === 233 /* ClassDeclaration */) { + if (node.kind !== 241 /* EnumDeclaration */) { return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(76 /* ConstKeyword */)); } break; @@ -48671,7 +54429,7 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } - else if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text); } else if (flags & 128 /* Abstract */) { @@ -48694,10 +54452,10 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } - else if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + else if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } else if (flags & 128 /* Abstract */) { @@ -48710,7 +54468,7 @@ var ts; if (flags & 64 /* Readonly */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly"); } - else if (node.kind !== 151 /* PropertyDeclaration */ && node.kind !== 150 /* PropertySignature */ && node.kind !== 159 /* IndexSignature */ && node.kind !== 148 /* Parameter */) { + else if (node.kind !== 152 /* PropertyDeclaration */ && node.kind !== 151 /* PropertySignature */ && node.kind !== 160 /* IndexSignature */ && node.kind !== 149 /* Parameter */) { // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property. return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } @@ -48730,17 +54488,17 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } - else if (node.parent.kind === 233 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } flags |= 1 /* Export */; break; case 79 /* DefaultKeyword */: - var container = node.parent.kind === 272 /* SourceFile */ ? node.parent : node.parent.parent; - if (container.kind === 237 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { + var container = node.parent.kind === 277 /* SourceFile */ ? node.parent : node.parent.parent; + if (container.kind === 242 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); } flags |= 512 /* Default */; @@ -48752,13 +54510,13 @@ var ts; else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.parent.kind === 233 /* ClassDeclaration */) { + else if (node.parent.kind === 238 /* ClassDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); } - else if ((node.parent.flags & 2097152 /* Ambient */) && node.parent.kind === 238 /* ModuleBlock */) { + else if ((node.parent.flags & 4194304 /* Ambient */) && node.parent.kind === 243 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } flags |= 2 /* Ambient */; @@ -48768,14 +54526,14 @@ var ts; if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } - if (node.kind !== 233 /* ClassDeclaration */) { - if (node.kind !== 153 /* MethodDeclaration */ && - node.kind !== 151 /* PropertyDeclaration */ && - node.kind !== 155 /* GetAccessor */ && - node.kind !== 156 /* SetAccessor */) { + if (node.kind !== 238 /* ClassDeclaration */) { + if (node.kind !== 154 /* MethodDeclaration */ && + node.kind !== 152 /* PropertyDeclaration */ && + node.kind !== 156 /* GetAccessor */ && + node.kind !== 157 /* SetAccessor */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration); } - if (!(node.parent.kind === 233 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) { + if (!(node.parent.kind === 238 /* 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 */) { @@ -48791,10 +54549,10 @@ var ts; if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || node.parent.flags & 2097152 /* Ambient */) { + else if (flags & 2 /* Ambient */ || node.parent.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } - else if (node.kind === 148 /* Parameter */) { + else if (node.kind === 149 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } flags |= 256 /* Async */; @@ -48802,12 +54560,12 @@ var ts; break; } } - if (node.kind === 154 /* Constructor */) { + if (node.kind === 155 /* Constructor */) { if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); + return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 } else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); @@ -48815,20 +54573,21 @@ var ts; else if (flags & 64 /* Readonly */) { return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); } - return; + return false; } - else if ((node.kind === 242 /* ImportDeclaration */ || node.kind === 241 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 247 /* ImportDeclaration */ || node.kind === 246 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 148 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern); } - else if (node.kind === 148 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { + else if (node.kind === 149 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter); } if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } + return false; } /** * true | false: Early return this value from checkGrammarModifiers. @@ -48843,37 +54602,37 @@ var ts; } function shouldReportBadModifier(node) { switch (node.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 159 /* IndexSignature */: - case 237 /* ModuleDeclaration */: - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - case 247 /* ExportAssignment */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 148 /* Parameter */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 160 /* IndexSignature */: + case 242 /* ModuleDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 149 /* Parameter */: return false; default: - if (node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + if (node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { return false; } switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return nodeHasAnyModifiersExcept(node, 120 /* AsyncKeyword */); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return nodeHasAnyModifiersExcept(node, 117 /* AbstractKeyword */); - case 234 /* InterfaceDeclaration */: - case 212 /* VariableStatement */: - case 235 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 217 /* VariableStatement */: + case 240 /* TypeAliasDeclaration */: return true; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return nodeHasAnyModifiersExcept(node, 76 /* ConstKeyword */); default: ts.Debug.fail(); @@ -48886,20 +54645,20 @@ var ts; } function checkGrammarAsyncModifier(node, asyncModifier) { switch (node.kind) { - case 153 /* MethodDeclaration */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return false; } return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async"); } - function checkGrammarForDisallowedTrailingComma(list) { + function checkGrammarForDisallowedTrailingComma(list, diag) { + if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; } if (list && list.hasTrailingComma) { - var start = list.end - ",".length; - var end = list.end; - return grammarErrorAtPos(list[0], start, end - start, ts.Diagnostics.Trailing_comma_not_allowed); + return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag); } + return false; } function checkGrammarTypeParameterList(typeParameters, file) { if (typeParameters && typeParameters.length === 0) { @@ -48907,6 +54666,7 @@ var ts; var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty); } + return false; } function checkGrammarParameterList(parameters) { var seenOptionalParameter = false; @@ -48917,6 +54677,9 @@ var ts; if (i !== (parameterCount - 1)) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); } + if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 + checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + } if (ts.isBindingPattern(parameter.name)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } @@ -48984,10 +54747,10 @@ var ts; } if (parameter.type.kind !== 137 /* StringKeyword */ && parameter.type.kind !== 134 /* NumberKeyword */) { var type = getTypeFromTypeNode(parameter.type); - if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); } - if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 262144 /* Union */ && allTypesAssignableToKind(type, 64 /* StringLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); @@ -48995,6 +54758,7 @@ var ts; if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); } + return false; } function checkGrammarIndexSignature(node) { // Prevent cascading error by short-circuit @@ -49007,6 +54771,7 @@ var ts; var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty); } + return false; } function checkGrammarTypeArguments(node, typeArguments) { return checkGrammarForDisallowedTrailingComma(typeArguments) || @@ -49016,11 +54781,12 @@ var ts; if (args) { for (var _i = 0, args_5 = args; _i < args_5.length; _i++) { var arg = args_5[_i]; - if (arg.kind === 204 /* OmittedExpression */) { + if (arg.kind === 208 /* OmittedExpression */) { return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } } + return false; } function checkGrammarArguments(args) { return checkGrammarForOmittedArgument(args); @@ -49034,7 +54800,7 @@ var ts; var listType = ts.tokenToString(node.token); return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } - return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + return ts.some(types, checkGrammarExpressionWithTypeArguments); } function checkGrammarExpressionWithTypeArguments(node) { return checkGrammarTypeArguments(node, node.typeArguments); @@ -49092,20 +54858,21 @@ var ts; } function checkGrammarComputedPropertyName(node) { // If node is not a computedPropertyName, just skip the grammar checking - if (node.kind !== 146 /* ComputedPropertyName */) { + if (node.kind !== 147 /* ComputedPropertyName */) { return false; } var computedPropertyName = node; - if (computedPropertyName.expression.kind === 198 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { + if (computedPropertyName.expression.kind === 202 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 26 /* CommaToken */) { return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } + return false; } function checkGrammarForGenerator(node) { if (node.asteriskToken) { - ts.Debug.assert(node.kind === 232 /* FunctionDeclaration */ || - node.kind === 190 /* FunctionExpression */ || - node.kind === 153 /* MethodDeclaration */); - if (node.flags & 2097152 /* Ambient */) { + ts.Debug.assert(node.kind === 237 /* FunctionDeclaration */ || + node.kind === 194 /* FunctionExpression */ || + node.kind === 154 /* MethodDeclaration */); + if (node.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context); } if (!node.body) { @@ -49114,9 +54881,7 @@ var ts; } } function checkGrammarForInvalidQuestionMark(questionToken, message) { - if (questionToken) { - return grammarErrorOnNode(questionToken, message); - } + return !!questionToken && grammarErrorOnNode(questionToken, message); } function checkGrammarObjectLiteralExpression(node, inDestructuring) { var Flags; @@ -49129,24 +54894,24 @@ var ts; var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - if (prop.kind === 270 /* SpreadAssignment */) { + if (prop.kind === 275 /* SpreadAssignment */) { continue; } var name = prop.name; - if (name.kind === 146 /* ComputedPropertyName */) { + if (name.kind === 147 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name); } - if (prop.kind === 269 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { + if (prop.kind === 274 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 var mod = _c[_b]; - if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 153 /* MethodDeclaration */) { + if (mod.kind !== 120 /* AsyncKeyword */ || prop.kind !== 154 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); } } @@ -49161,25 +54926,25 @@ var ts; // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields var currentKind = void 0; switch (prop.kind) { - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === 8 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } // falls through - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: currentKind = 1 /* Property */; break; - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: currentKind = 2 /* GetAccessor */; break; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: currentKind = 4 /* SetAccessor */; break; default: - ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); + throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind); } var effectiveName = ts.getPropertyNameForPropertyNameNode(name); if (effectiveName === undefined) { @@ -49208,10 +54973,11 @@ var ts; } } function checkGrammarJsxElement(node) { + checkGrammarTypeArguments(node, node.typeArguments); var seen = ts.createUnderscoreEscapedMap(); for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) { var attr = _a[_i]; - if (attr.kind === 262 /* JsxSpreadAttribute */) { + if (attr.kind === 267 /* JsxSpreadAttribute */) { continue; } var name = attr.name, initializer = attr.initializer; @@ -49221,7 +54987,7 @@ var ts; else { return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - if (initializer && initializer.kind === 263 /* JsxExpression */ && !initializer.expression) { + if (initializer && initializer.kind === 268 /* JsxExpression */ && !initializer.expression) { return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } } @@ -49230,12 +54996,12 @@ var ts; if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) { return true; } - if (forInOrOfStatement.kind === 220 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { + if (forInOrOfStatement.kind === 225 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) { if ((forInOrOfStatement.flags & 16384 /* AwaitContext */) === 0 /* None */) { return grammarErrorOnNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator); } } - if (forInOrOfStatement.initializer.kind === 231 /* VariableDeclarationList */) { + if (forInOrOfStatement.initializer.kind === 236 /* VariableDeclarationList */) { var variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { var declarations = variableList.declarations; @@ -49250,20 +55016,20 @@ var ts; return false; } if (declarations.length > 1) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } var firstDeclaration = declarations[0]; if (firstDeclaration.initializer) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - var diagnostic = forInOrOfStatement.kind === 219 /* ForInStatement */ + var diagnostic = forInOrOfStatement.kind === 224 /* ForInStatement */ ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -49277,7 +55043,7 @@ var ts; if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } - else if (accessor.flags & 2097152 /* Ambient */) { + else if (accessor.flags & 4194304 /* Ambient */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_be_declared_in_an_ambient_context); } else if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) { @@ -49290,11 +55056,11 @@ var ts; return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters); } else if (!doesAccessorHaveCorrectParameterCount(accessor)) { - return grammarErrorOnNode(accessor.name, kind === 155 /* GetAccessor */ ? + return grammarErrorOnNode(accessor.name, kind === 156 /* GetAccessor */ ? ts.Diagnostics.A_get_accessor_cannot_have_parameters : ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } - else if (kind === 156 /* SetAccessor */) { + else if (kind === 157 /* SetAccessor */) { if (accessor.type) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation); } @@ -49311,16 +55077,17 @@ var ts; } } } + return false; } /** Does the accessor have the right number of parameters? * A get accessor has no parameters or a single `this` parameter. * A set accessor has one parameter or a `this` parameter and one more parameter. */ function doesAccessorHaveCorrectParameterCount(accessor) { - return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 155 /* GetAccessor */ ? 0 : 1); + return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 155 /* GetAccessor */ ? 1 : 2)) { + if (accessor.parameters.length === (accessor.kind === 156 /* GetAccessor */ ? 1 : 2)) { return ts.getThisParameter(accessor); } } @@ -49331,7 +55098,7 @@ var ts; } var parent = ts.walkUpParenthesizedTypes(node.parent); switch (parent.kind) { - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: var decl = parent; if (decl.name.kind !== 71 /* Identifier */) { return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); @@ -49343,13 +55110,13 @@ var ts; return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: if (!ts.hasModifier(parent, 32 /* Static */) || !ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: if (!ts.hasModifier(parent, 64 /* Readonly */)) { return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } @@ -49368,8 +55135,8 @@ var ts; if (checkGrammarFunctionLikeDeclaration(node)) { return true; } - if (node.kind === 153 /* MethodDeclaration */) { - if (node.parent.kind === 182 /* ObjectLiteralExpression */) { + if (node.kind === 154 /* MethodDeclaration */) { + if (node.parent.kind === 186 /* ObjectLiteralExpression */) { // We only disallow modifier on a method declaration if it is a property of object-literal-expression if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 120 /* AsyncKeyword */)) { return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); @@ -49391,17 +55158,17 @@ var ts; // However, property declarations disallow computed names in general, // and accessors are not allowed in ambient contexts in general, // so this error only really matters for methods. - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_ambient_context_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.kind === 153 /* MethodDeclaration */ && !node.body) { + else if (node.kind === 154 /* MethodDeclaration */ && !node.body) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_method_overload_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } - else if (node.parent.kind === 234 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } - else if (node.parent.kind === 165 /* TypeLiteral */) { + else if (node.parent.kind === 166 /* TypeLiteral */) { return checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type); } } @@ -49412,11 +55179,11 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - var isMisplacedContinueLabel = node.kind === 221 /* ContinueStatement */ + var isMisplacedContinueLabel = node.kind === 226 /* ContinueStatement */ && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -49424,8 +55191,8 @@ var ts; return false; } break; - case 225 /* SwitchStatement */: - if (node.kind === 222 /* BreakStatement */ && !node.label) { + case 230 /* SwitchStatement */: + if (node.kind === 227 /* BreakStatement */ && !node.label) { // unlabeled break within switch statement - ok return false; } @@ -49440,13 +55207,13 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 222 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 222 /* BreakStatement */ + var message = node.kind === 227 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -49458,7 +55225,8 @@ var ts; if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } - if (node.name.kind === 179 /* ArrayBindingPattern */ || node.name.kind === 178 /* ObjectBindingPattern */) { + checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + if (node.name.kind === 183 /* ArrayBindingPattern */ || node.name.kind === 182 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } if (node.propertyName) { @@ -49472,14 +55240,14 @@ var ts; } function isStringOrNumberLiteralExpression(expr) { return expr.kind === 9 /* StringLiteral */ || expr.kind === 8 /* NumericLiteral */ || - expr.kind === 196 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && + expr.kind === 200 /* PrefixUnaryExpression */ && expr.operator === 38 /* MinusToken */ && expr.operand.kind === 8 /* NumericLiteral */; } function checkGrammarVariableDeclaration(node) { - if (node.parent.parent.kind !== 219 /* ForInStatement */ && node.parent.parent.kind !== 220 /* ForOfStatement */) { - if (node.flags & 2097152 /* Ambient */) { + if (node.parent.parent.kind !== 224 /* ForInStatement */ && node.parent.parent.kind !== 225 /* ForOfStatement */) { + if (node.flags & 4194304 /* Ambient */) { if (node.initializer) { - if (ts.isConst(node) && !node.type) { + if (ts.isVarConst(node) && !node.type) { if (!isStringOrNumberLiteralExpression(node.initializer)) { return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); } @@ -49490,7 +55258,7 @@ var ts; 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))) { + if (node.initializer && !(ts.isVarConst(node) && isStringOrNumberLiteralExpression(node.initializer))) { // Error on equals token which immediate precedes the initializer var equalsTokenLength = "=".length; return grammarErrorAtPos(node, node.initializer.pos - equalsTokenLength, equalsTokenLength, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); @@ -49500,19 +55268,19 @@ var ts; if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) { return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer); } - if (ts.isConst(node)) { + if (ts.isVarConst(node)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized); } } } - if (node.exclamationToken && (node.parent.parent.kind !== 212 /* VariableStatement */ || !node.type || node.initializer || node.flags & 2097152 /* Ambient */)) { + if (node.exclamationToken && (node.parent.parent.kind !== 217 /* VariableStatement */ || !node.type || node.initializer || node.flags & 4194304 /* Ambient */)) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.ESNext && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && - !(node.parent.parent.flags & 2097152 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + !(node.parent.parent.flags & 4194304 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { checkESModuleMarker(node.name); } - var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); + var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding @@ -49536,6 +55304,7 @@ var ts; } } } + return false; } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 71 /* Identifier */) { @@ -49552,6 +55321,7 @@ var ts; } } } + return false; } function checkGrammarVariableDeclarationList(declarationList) { var declarations = declarationList.declarations; @@ -49561,18 +55331,19 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } + return false; } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 215 /* IfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 220 /* IfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: return false; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; @@ -49582,16 +55353,24 @@ var ts; if (ts.isLet(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (ts.isConst(node.declarationList)) { + else if (ts.isVarConst(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } } function checkGrammarMetaProperty(node) { - if (node.keywordToken === 94 /* NewKeyword */) { - if (node.name.escapedText !== "target") { - return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); - } + var escapedText = node.name.escapedText; + switch (node.keywordToken) { + case 94 /* NewKeyword */: + if (escapedText !== "target") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "target"); + } + break; + case 91 /* ImportKeyword */: + if (escapedText !== "meta") { + return grammarErrorOnNode(node.name, ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2, node.name.escapedText, ts.tokenToString(node.keywordToken), "meta"); + } + break; } } function hasParseDiagnostics(sourceFile) { @@ -49600,10 +55379,11 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_4 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, span_4.start, span_4.length, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile); @@ -49611,6 +55391,7 @@ var ts; diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2)); return true; } + return false; } function grammarErrorOnNode(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); @@ -49618,11 +55399,12 @@ var ts; diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; } + return false; } function checkGrammarConstructorTypeParameters(node) { - var typeParameters = ts.getEffectiveTypeParameterDeclarations(node); - if (typeParameters) { - var _a = ts.isNodeArray(typeParameters) ? typeParameters : ts.first(typeParameters), pos = _a.pos, end = _a.end; + var jsdocTypeParameters = ts.isInJavaScriptFile(node) && ts.getJSDocTypeParameterDeclarations(node); + if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { + var _a = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node, pos = _a.pos, end = _a.end; return grammarErrorAtPos(node, pos, end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } @@ -49638,7 +55420,7 @@ var ts; return true; } } - else if (node.parent.kind === 234 /* InterfaceDeclaration */) { + else if (node.parent.kind === 239 /* InterfaceDeclaration */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_an_interface_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -49646,7 +55428,7 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer); } } - else if (node.parent.kind === 165 /* TypeLiteral */) { + else if (node.parent.kind === 166 /* TypeLiteral */) { if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_type_literal_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) { return true; } @@ -49654,11 +55436,11 @@ var ts; return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer); } } - if (node.flags & 2097152 /* Ambient */ && node.initializer) { + if (node.flags & 4194304 /* Ambient */ && node.initializer) { return grammarErrorOnFirstToken(node.initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer || - node.flags & 2097152 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { + node.flags & 4194304 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) { return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); } } @@ -49675,13 +55457,13 @@ var ts; // export_opt AmbientDeclaration // // TODO: The spec needs to be amended to reflect this grammar. - if (node.kind === 234 /* InterfaceDeclaration */ || - node.kind === 235 /* TypeAliasDeclaration */ || - node.kind === 242 /* ImportDeclaration */ || - node.kind === 241 /* ImportEqualsDeclaration */ || - node.kind === 248 /* ExportDeclaration */ || - node.kind === 247 /* ExportAssignment */ || - node.kind === 240 /* NamespaceExportDeclaration */ || + if (node.kind === 239 /* InterfaceDeclaration */ || + node.kind === 240 /* TypeAliasDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 246 /* ImportEqualsDeclaration */ || + node.kind === 253 /* ExportDeclaration */ || + node.kind === 252 /* ExportAssignment */ || + node.kind === 245 /* NamespaceExportDeclaration */ || ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) { return false; } @@ -49690,18 +55472,19 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isDeclaration(decl) || decl.kind === 212 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 217 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } } } + return false; } function checkGrammarSourceFile(node) { - return !!(node.flags & 2097152 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); + return !!(node.flags & 4194304 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node); } function checkGrammarStatementInAmbientContext(node) { - if (node.flags & 2097152 /* Ambient */) { + if (node.flags & 4194304 /* Ambient */) { // An accessors is already reported about the ambient context if (ts.isAccessor(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = true; @@ -49716,7 +55499,7 @@ var ts; // to prevent noisiness. So use a bit on the block to indicate if // this has already been reported, and don't report if it has. // - if (node.parent.kind === 211 /* Block */ || node.parent.kind === 238 /* ModuleBlock */ || node.parent.kind === 272 /* SourceFile */) { + if (node.parent.kind === 216 /* Block */ || node.parent.kind === 243 /* ModuleBlock */ || node.parent.kind === 277 /* SourceFile */) { var links_1 = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links_1.hasReportedStatementInAmbientContext) { @@ -49729,6 +55512,7 @@ var ts; // Debug.assert(isStatement(node.parent)); } } + return false; } function checkGrammarNumericLiteral(node) { // Grammar checking @@ -49737,10 +55521,10 @@ var ts; if (languageVersion >= 1 /* ES5 */) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 177 /* LiteralType */)) { + else if (ts.isChildOfNodeWithKind(node, 180 /* LiteralType */)) { diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0; } - else if (ts.isChildOfNodeWithKind(node, 271 /* EnumMember */)) { + else if (ts.isChildOfNodeWithKind(node, 276 /* EnumMember */)) { diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0; } if (diagnosticMessage) { @@ -49749,14 +55533,16 @@ var ts; return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal); } } + return false; } function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var span_5 = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span_5), /*length*/ 0, message, arg0, arg1, arg2)); + var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } + return false; } function getAmbientModules() { if (!ambientModulesCache) { @@ -49771,8 +55557,8 @@ var ts; return ambientModulesCache; } function checkGrammarImportCallExpression(node) { - if (modulekind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_be_used_when_targeting_ECMAScript_2015_modules); + if (moduleKind === ts.ModuleKind.ES2015) { + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -49786,14 +55572,15 @@ var ts; if (ts.isSpreadElement(nodeArguments[0])) { return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element); } + return false; } } ts.createTypeChecker = createTypeChecker; /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: return ts.isIdentifier(name); default: return ts.isDeclarationName(name); @@ -49801,14 +55588,14 @@ var ts; } function isSomeImportDeclaration(decl) { switch (decl.kind) { - case 243 /* ImportClause */: // For default import - case 241 /* ImportEqualsDeclaration */: - case 244 /* NamespaceImport */: - case 246 /* ImportSpecifier */: // For rename import `x as y` + case 248 /* ImportClause */: // For default import + case 246 /* ImportEqualsDeclaration */: + case 249 /* NamespaceImport */: + case 251 /* ImportSpecifier */: // For rename import `x as y` return true; case 71 /* Identifier */: // For regular import, `decl` is an Identifier under the ImportSpecifier. - return decl.parent.kind === 246 /* ImportSpecifier */; + return decl.parent.kind === 251 /* ImportSpecifier */; default: return false; } @@ -49819,16 +55606,18 @@ var ts; JsxNames.JSX = "JSX"; JsxNames.IntrinsicElements = "IntrinsicElements"; JsxNames.ElementClass = "ElementClass"; - JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; + JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute"; JsxNames.Element = "Element"; JsxNames.IntrinsicAttributes = "IntrinsicAttributes"; JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; + JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); + function typeIsLiteralType(type) { + return !!(type.flags & 448 /* Literal */); + } })(ts || (ts = {})); -/// -/// var ts; (function (ts) { function createSynthesizedNode(kind) { @@ -49850,14 +55639,12 @@ var ts; * Make `elements` into a `NodeArray`. If `elements` is `undefined`, returns an empty `NodeArray`. */ function createNodeArray(elements, hasTrailingComma) { - if (elements) { - if (ts.isNodeArray(elements)) { - return elements; - } - } - else { + if (!elements || elements === ts.emptyArray) { elements = []; } + else if (ts.isNodeArray(elements)) { + return elements; + } var array = elements; array.pos = -1; array.end = -1; @@ -49874,7 +55661,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). if (node === undefined) { - return undefined; + return node; } var clone = createSynthesizedNode(node.kind); clone.flags |= node.flags; @@ -49888,7 +55675,7 @@ var ts; return clone; } ts.getSynthesizedClone = getSynthesizedClone; - function createLiteral(value) { + function createLiteral(value, isSingleQuote) { if (typeof value === "number") { return createNumericLiteral(value + ""); } @@ -49896,7 +55683,10 @@ var ts; return value ? createTrue() : createFalse(); } if (ts.isString(value)) { - return createStringLiteral(value); + var res = createStringLiteral(value); + if (isSingleQuote) + res.singleQuote = true; + return res; } return createLiteralFromNode(value); } @@ -49913,6 +55703,13 @@ var ts; node.text = text; return node; } + ts.createStringLiteral = createStringLiteral; + function createRegularExpressionLiteral(text) { + var node = createSynthesizedNode(12 /* RegularExpressionLiteral */); + node.text = text; + return node; + } + ts.createRegularExpressionLiteral = createRegularExpressionLiteral; function createLiteralFromNode(sourceNode) { var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode)); node.textSourceNode = sourceNode; @@ -49946,7 +55743,7 @@ var ts; recordTempVariable(name); } if (reservedInNestedScopes) { - name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */; } return name; } @@ -49969,14 +55766,26 @@ var ts; return name; } ts.createUniqueName = createUniqueName; - function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { - var name = createIdentifier(""); - name.autoGenerateFlags = 4 /* Node */; + function createOptimisticUniqueName(text) { + var name = createIdentifier(text); + name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + ts.createOptimisticUniqueName = createOptimisticUniqueName; + /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */ + function createFileLevelUniqueName(text) { + var name = createOptimisticUniqueName(text); + name.autoGenerateFlags |= 32 /* FileLevel */; + return name; + } + ts.createFileLevelUniqueName = createFileLevelUniqueName; + function getGeneratedNameForNode(node, flags) { + var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : ""); + name.autoGenerateFlags = 4 /* Node */ | flags; name.autoGenerateId = nextAutoGenerateId; name.original = node; - if (shouldSkipNameGenerationScope) { - name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; - } nextAutoGenerateId++; return name; } @@ -50007,9 +55816,52 @@ var ts; return createSynthesizedNode(86 /* FalseKeyword */); } ts.createFalse = createFalse; + // Modifiers + function createModifier(kind) { + return createToken(kind); + } + ts.createModifier = createModifier; + function createModifiersFromModifierFlags(flags) { + var result = []; + if (flags & 1 /* Export */) { + result.push(createModifier(84 /* ExportKeyword */)); + } + if (flags & 2 /* Ambient */) { + result.push(createModifier(124 /* DeclareKeyword */)); + } + if (flags & 512 /* Default */) { + result.push(createModifier(79 /* DefaultKeyword */)); + } + if (flags & 2048 /* Const */) { + result.push(createModifier(76 /* ConstKeyword */)); + } + if (flags & 4 /* Public */) { + result.push(createModifier(114 /* PublicKeyword */)); + } + if (flags & 8 /* Private */) { + result.push(createModifier(112 /* PrivateKeyword */)); + } + if (flags & 16 /* Protected */) { + result.push(createModifier(113 /* ProtectedKeyword */)); + } + if (flags & 128 /* Abstract */) { + result.push(createModifier(117 /* AbstractKeyword */)); + } + if (flags & 32 /* Static */) { + result.push(createModifier(115 /* StaticKeyword */)); + } + if (flags & 64 /* Readonly */) { + result.push(createModifier(132 /* ReadonlyKeyword */)); + } + if (flags & 256 /* Async */) { + result.push(createModifier(120 /* AsyncKeyword */)); + } + return result; + } + ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags; // Names function createQualifiedName(left, right) { - var node = createSynthesizedNode(145 /* QualifiedName */); + var node = createSynthesizedNode(146 /* QualifiedName */); node.left = left; node.right = asName(right); return node; @@ -50023,13 +55875,12 @@ var ts; } ts.updateQualifiedName = updateQualifiedName; function parenthesizeForComputedName(expression) { - return (ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */) || - expression.kind === 296 /* CommaListExpression */ ? - createParen(expression) : - expression; + return ts.isCommaSequence(expression) + ? createParen(expression) + : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(146 /* ComputedPropertyName */); + var node = createSynthesizedNode(147 /* ComputedPropertyName */); node.expression = parenthesizeForComputedName(expression); return node; } @@ -50042,7 +55893,7 @@ var ts; ts.updateComputedPropertyName = updateComputedPropertyName; // Signature elements function createTypeParameterDeclaration(name, constraint, defaultType) { - var node = createSynthesizedNode(147 /* TypeParameter */); + var node = createSynthesizedNode(148 /* TypeParameter */); node.name = asName(name); node.constraint = constraint; node.default = defaultType; @@ -50058,7 +55909,7 @@ var ts; } ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration; function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) { - var node = createSynthesizedNode(148 /* Parameter */); + var node = createSynthesizedNode(149 /* Parameter */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; @@ -50082,7 +55933,7 @@ var ts; } ts.updateParameter = updateParameter; function createDecorator(expression) { - var node = createSynthesizedNode(149 /* Decorator */); + var node = createSynthesizedNode(150 /* Decorator */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -50095,7 +55946,7 @@ var ts; ts.updateDecorator = updateDecorator; // Type Elements function createPropertySignature(modifiers, name, questionToken, type, initializer) { - var node = createSynthesizedNode(150 /* PropertySignature */); + var node = createSynthesizedNode(151 /* PropertySignature */); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -50115,7 +55966,7 @@ var ts; } ts.updatePropertySignature = updatePropertySignature; function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) { - var node = createSynthesizedNode(151 /* PropertyDeclaration */); + var node = createSynthesizedNode(152 /* PropertyDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50139,7 +55990,7 @@ var ts; } ts.updateProperty = updateProperty; function createMethodSignature(typeParameters, parameters, type, name, questionToken) { - var node = createSignatureDeclaration(152 /* MethodSignature */, typeParameters, parameters, type); + var node = createSignatureDeclaration(153 /* MethodSignature */, typeParameters, parameters, type); node.name = asName(name); node.questionToken = questionToken; return node; @@ -50156,7 +56007,7 @@ var ts; } ts.updateMethodSignature = updateMethodSignature; function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(153 /* MethodDeclaration */); + var node = createSynthesizedNode(154 /* MethodDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -50184,7 +56035,7 @@ var ts; } ts.updateMethod = updateMethod; function createConstructor(decorators, modifiers, parameters, body) { - var node = createSynthesizedNode(154 /* Constructor */); + var node = createSynthesizedNode(155 /* Constructor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.typeParameters = undefined; @@ -50204,7 +56055,7 @@ var ts; } ts.updateConstructor = updateConstructor; function createGetAccessor(decorators, modifiers, name, parameters, type, body) { - var node = createSynthesizedNode(155 /* GetAccessor */); + var node = createSynthesizedNode(156 /* GetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50227,7 +56078,7 @@ var ts; } ts.updateGetAccessor = updateGetAccessor; function createSetAccessor(decorators, modifiers, name, parameters, body) { - var node = createSynthesizedNode(156 /* SetAccessor */); + var node = createSynthesizedNode(157 /* SetAccessor */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50248,7 +56099,7 @@ var ts; } ts.updateSetAccessor = updateSetAccessor; function createCallSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(157 /* CallSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(158 /* CallSignature */, typeParameters, parameters, type); } ts.createCallSignature = createCallSignature; function updateCallSignature(node, typeParameters, parameters, type) { @@ -50256,7 +56107,7 @@ var ts; } ts.updateCallSignature = updateCallSignature; function createConstructSignature(typeParameters, parameters, type) { - return createSignatureDeclaration(158 /* ConstructSignature */, typeParameters, parameters, type); + return createSignatureDeclaration(159 /* ConstructSignature */, typeParameters, parameters, type); } ts.createConstructSignature = createConstructSignature; function updateConstructSignature(node, typeParameters, parameters, type) { @@ -50264,7 +56115,7 @@ var ts; } ts.updateConstructSignature = updateConstructSignature; function createIndexSignature(decorators, modifiers, parameters, type) { - var node = createSynthesizedNode(159 /* IndexSignature */); + var node = createSynthesizedNode(160 /* IndexSignature */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); @@ -50304,7 +56155,7 @@ var ts; } ts.createKeywordTypeNode = createKeywordTypeNode; function createTypePredicateNode(parameterName, type) { - var node = createSynthesizedNode(160 /* TypePredicate */); + var node = createSynthesizedNode(161 /* TypePredicate */); node.parameterName = asName(parameterName); node.type = type; return node; @@ -50318,7 +56169,7 @@ var ts; } ts.updateTypePredicateNode = updateTypePredicateNode; function createTypeReferenceNode(typeName, typeArguments) { - var node = createSynthesizedNode(161 /* TypeReference */); + var node = createSynthesizedNode(162 /* TypeReference */); node.typeName = asName(typeName); node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments); return node; @@ -50332,7 +56183,7 @@ var ts; } ts.updateTypeReferenceNode = updateTypeReferenceNode; function createFunctionTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(162 /* FunctionType */, typeParameters, parameters, type); + return createSignatureDeclaration(163 /* FunctionType */, typeParameters, parameters, type); } ts.createFunctionTypeNode = createFunctionTypeNode; function updateFunctionTypeNode(node, typeParameters, parameters, type) { @@ -50340,7 +56191,7 @@ var ts; } ts.updateFunctionTypeNode = updateFunctionTypeNode; function createConstructorTypeNode(typeParameters, parameters, type) { - return createSignatureDeclaration(163 /* ConstructorType */, typeParameters, parameters, type); + return createSignatureDeclaration(164 /* ConstructorType */, typeParameters, parameters, type); } ts.createConstructorTypeNode = createConstructorTypeNode; function updateConstructorTypeNode(node, typeParameters, parameters, type) { @@ -50348,7 +56199,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(164 /* TypeQuery */); + var node = createSynthesizedNode(165 /* TypeQuery */); node.exprName = exprName; return node; } @@ -50360,7 +56211,7 @@ var ts; } ts.updateTypeQueryNode = updateTypeQueryNode; function createTypeLiteralNode(members) { - var node = createSynthesizedNode(165 /* TypeLiteral */); + var node = createSynthesizedNode(166 /* TypeLiteral */); node.members = createNodeArray(members); return node; } @@ -50372,7 +56223,7 @@ var ts; } ts.updateTypeLiteralNode = updateTypeLiteralNode; function createArrayTypeNode(elementType) { - var node = createSynthesizedNode(166 /* ArrayType */); + var node = createSynthesizedNode(167 /* ArrayType */); node.elementType = ts.parenthesizeArrayTypeMember(elementType); return node; } @@ -50384,19 +56235,43 @@ var ts; } ts.updateArrayTypeNode = updateArrayTypeNode; function createTupleTypeNode(elementTypes) { - var node = createSynthesizedNode(167 /* TupleType */); + var node = createSynthesizedNode(168 /* TupleType */); node.elementTypes = createNodeArray(elementTypes); return node; } ts.createTupleTypeNode = createTupleTypeNode; - function updateTypleTypeNode(node, elementTypes) { + function updateTupleTypeNode(node, elementTypes) { return node.elementTypes !== elementTypes ? updateNode(createTupleTypeNode(elementTypes), node) : node; } - ts.updateTypleTypeNode = updateTypleTypeNode; + ts.updateTupleTypeNode = updateTupleTypeNode; + function createOptionalTypeNode(type) { + var node = createSynthesizedNode(169 /* OptionalType */); + node.type = ts.parenthesizeArrayTypeMember(type); + return node; + } + ts.createOptionalTypeNode = createOptionalTypeNode; + function updateOptionalTypeNode(node, type) { + return node.type !== type + ? updateNode(createOptionalTypeNode(type), node) + : node; + } + ts.updateOptionalTypeNode = updateOptionalTypeNode; + function createRestTypeNode(type) { + var node = createSynthesizedNode(170 /* RestType */); + node.type = type; + return node; + } + ts.createRestTypeNode = createRestTypeNode; + function updateRestTypeNode(node, type) { + return node.type !== type + ? updateNode(createRestTypeNode(type), node) + : node; + } + ts.updateRestTypeNode = updateRestTypeNode; function createUnionTypeNode(types) { - return createUnionOrIntersectionTypeNode(168 /* UnionType */, types); + return createUnionOrIntersectionTypeNode(171 /* UnionType */, types); } ts.createUnionTypeNode = createUnionTypeNode; function updateUnionTypeNode(node, types) { @@ -50404,7 +56279,7 @@ var ts; } ts.updateUnionTypeNode = updateUnionTypeNode; function createIntersectionTypeNode(types) { - return createUnionOrIntersectionTypeNode(169 /* IntersectionType */, types); + return createUnionOrIntersectionTypeNode(172 /* IntersectionType */, types); } ts.createIntersectionTypeNode = createIntersectionTypeNode; function updateIntersectionTypeNode(node, types) { @@ -50423,7 +56298,7 @@ var ts; : node; } function createConditionalTypeNode(checkType, extendsType, trueType, falseType) { - var node = createSynthesizedNode(170 /* ConditionalType */); + var node = createSynthesizedNode(173 /* ConditionalType */); node.checkType = ts.parenthesizeConditionalTypeMember(checkType); node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType); node.trueType = trueType; @@ -50441,7 +56316,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(171 /* InferType */); + var node = createSynthesizedNode(174 /* InferType */); node.typeParameter = typeParameter; return node; } @@ -50452,8 +56327,26 @@ var ts; : node; } ts.updateInferTypeNode = updateInferTypeNode; + function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) { + var node = createSynthesizedNode(181 /* ImportType */); + node.argument = argument; + node.qualifier = qualifier; + node.typeArguments = asNodeArray(typeArguments); + node.isTypeOf = isTypeOf; + return node; + } + ts.createImportTypeNode = createImportTypeNode; + function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) { + return node.argument !== argument + || node.qualifier !== qualifier + || node.typeArguments !== typeArguments + || node.isTypeOf !== isTypeOf + ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node) + : node; + } + ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(172 /* ParenthesizedType */); + var node = createSynthesizedNode(175 /* ParenthesizedType */); node.type = type; return node; } @@ -50465,11 +56358,11 @@ var ts; } ts.updateParenthesizedType = updateParenthesizedType; function createThisTypeNode() { - return createSynthesizedNode(173 /* ThisType */); + return createSynthesizedNode(176 /* ThisType */); } ts.createThisTypeNode = createThisTypeNode; function createTypeOperatorNode(operatorOrType, type) { - var node = createSynthesizedNode(174 /* TypeOperator */); + var node = createSynthesizedNode(177 /* TypeOperator */); node.operator = typeof operatorOrType === "number" ? operatorOrType : 128 /* KeyOfKeyword */; node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType); return node; @@ -50480,7 +56373,7 @@ var ts; } ts.updateTypeOperatorNode = updateTypeOperatorNode; function createIndexedAccessTypeNode(objectType, indexType) { - var node = createSynthesizedNode(175 /* IndexedAccessType */); + var node = createSynthesizedNode(178 /* IndexedAccessType */); node.objectType = ts.parenthesizeElementTypeMember(objectType); node.indexType = indexType; return node; @@ -50494,7 +56387,7 @@ var ts; } ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode; function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) { - var node = createSynthesizedNode(176 /* MappedType */); + var node = createSynthesizedNode(179 /* MappedType */); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.questionToken = questionToken; @@ -50512,7 +56405,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(177 /* LiteralType */); + var node = createSynthesizedNode(180 /* LiteralType */); node.literal = literal; return node; } @@ -50525,7 +56418,7 @@ var ts; ts.updateLiteralTypeNode = updateLiteralTypeNode; // Binding Patterns function createObjectBindingPattern(elements) { - var node = createSynthesizedNode(178 /* ObjectBindingPattern */); + var node = createSynthesizedNode(182 /* ObjectBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -50537,7 +56430,7 @@ var ts; } ts.updateObjectBindingPattern = updateObjectBindingPattern; function createArrayBindingPattern(elements) { - var node = createSynthesizedNode(179 /* ArrayBindingPattern */); + var node = createSynthesizedNode(183 /* ArrayBindingPattern */); node.elements = createNodeArray(elements); return node; } @@ -50549,7 +56442,7 @@ var ts; } ts.updateArrayBindingPattern = updateArrayBindingPattern; function createBindingElement(dotDotDotToken, propertyName, name, initializer) { - var node = createSynthesizedNode(180 /* BindingElement */); + var node = createSynthesizedNode(184 /* BindingElement */); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -50568,7 +56461,7 @@ var ts; ts.updateBindingElement = updateBindingElement; // Expression function createArrayLiteral(elements, multiLine) { - var node = createSynthesizedNode(181 /* ArrayLiteralExpression */); + var node = createSynthesizedNode(185 /* ArrayLiteralExpression */); node.elements = ts.parenthesizeListElements(createNodeArray(elements)); if (multiLine) node.multiLine = true; @@ -50582,7 +56475,7 @@ var ts; } ts.updateArrayLiteral = updateArrayLiteral; function createObjectLiteral(properties, multiLine) { - var node = createSynthesizedNode(182 /* ObjectLiteralExpression */); + var node = createSynthesizedNode(186 /* ObjectLiteralExpression */); node.properties = createNodeArray(properties); if (multiLine) node.multiLine = true; @@ -50596,9 +56489,9 @@ var ts; } ts.updateObjectLiteral = updateObjectLiteral; function createPropertyAccess(expression, name) { - var node = createSynthesizedNode(183 /* PropertyAccessExpression */); + var node = createSynthesizedNode(187 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); - node.name = asName(name); + node.name = asName(name); // TODO: GH#18217 setEmitFlags(node, 131072 /* NoIndentation */); return node; } @@ -50613,7 +56506,7 @@ var ts; } ts.updatePropertyAccess = updatePropertyAccess; function createElementAccess(expression, index) { - var node = createSynthesizedNode(184 /* ElementAccessExpression */); + var node = createSynthesizedNode(188 /* ElementAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.argumentExpression = asExpression(index); return node; @@ -50627,7 +56520,7 @@ var ts; } ts.updateElementAccess = updateElementAccess; function createCall(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(185 /* CallExpression */); + var node = createSynthesizedNode(189 /* CallExpression */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray)); @@ -50643,7 +56536,7 @@ var ts; } ts.updateCall = updateCall; function createNew(expression, typeArguments, argumentsArray) { - var node = createSynthesizedNode(186 /* NewExpression */); + var node = createSynthesizedNode(190 /* NewExpression */); node.expression = ts.parenthesizeForNew(expression); node.typeArguments = asNodeArray(typeArguments); node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined; @@ -50658,22 +56551,31 @@ var ts; : node; } ts.updateNew = updateNew; - function createTaggedTemplate(tag, template) { - var node = createSynthesizedNode(187 /* TaggedTemplateExpression */); + function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) { + var node = createSynthesizedNode(191 /* TaggedTemplateExpression */); node.tag = ts.parenthesizeForAccess(tag); - node.template = template; + if (template) { + node.typeArguments = asNodeArray(typeArgumentsOrTemplate); + node.template = template; + } + else { + node.typeArguments = undefined; + node.template = typeArgumentsOrTemplate; + } return node; } ts.createTaggedTemplate = createTaggedTemplate; - function updateTaggedTemplate(node, tag, template) { + function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) { return node.tag !== tag - || node.template !== template - ? updateNode(createTaggedTemplate(tag, template), node) + || (template + ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template + : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate) + ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node) : node; } ts.updateTaggedTemplate = updateTaggedTemplate; function createTypeAssertion(type, expression) { - var node = createSynthesizedNode(188 /* TypeAssertionExpression */); + var node = createSynthesizedNode(192 /* TypeAssertionExpression */); node.type = type; node.expression = ts.parenthesizePrefixOperand(expression); return node; @@ -50687,7 +56589,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(189 /* ParenthesizedExpression */); + var node = createSynthesizedNode(193 /* ParenthesizedExpression */); node.expression = expression; return node; } @@ -50699,7 +56601,7 @@ var ts; } ts.updateParen = updateParen; function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(190 /* FunctionExpression */); + var node = createSynthesizedNode(194 /* FunctionExpression */); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -50723,7 +56625,7 @@ var ts; } ts.updateFunctionExpression = updateFunctionExpression; function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) { - var node = createSynthesizedNode(191 /* ArrowFunction */); + var node = createSynthesizedNode(195 /* ArrowFunction */); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); @@ -50757,7 +56659,7 @@ var ts; } ts.updateArrowFunction = updateArrowFunction; function createDelete(expression) { - var node = createSynthesizedNode(192 /* DeleteExpression */); + var node = createSynthesizedNode(196 /* DeleteExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50769,7 +56671,7 @@ var ts; } ts.updateDelete = updateDelete; function createTypeOf(expression) { - var node = createSynthesizedNode(193 /* TypeOfExpression */); + var node = createSynthesizedNode(197 /* TypeOfExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50781,7 +56683,7 @@ var ts; } ts.updateTypeOf = updateTypeOf; function createVoid(expression) { - var node = createSynthesizedNode(194 /* VoidExpression */); + var node = createSynthesizedNode(198 /* VoidExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50793,7 +56695,7 @@ var ts; } ts.updateVoid = updateVoid; function createAwait(expression) { - var node = createSynthesizedNode(195 /* AwaitExpression */); + var node = createSynthesizedNode(199 /* AwaitExpression */); node.expression = ts.parenthesizePrefixOperand(expression); return node; } @@ -50805,7 +56707,7 @@ var ts; } ts.updateAwait = updateAwait; function createPrefix(operator, operand) { - var node = createSynthesizedNode(196 /* PrefixUnaryExpression */); + var node = createSynthesizedNode(200 /* PrefixUnaryExpression */); node.operator = operator; node.operand = ts.parenthesizePrefixOperand(operand); return node; @@ -50818,7 +56720,7 @@ var ts; } ts.updatePrefix = updatePrefix; function createPostfix(operand, operator) { - var node = createSynthesizedNode(197 /* PostfixUnaryExpression */); + var node = createSynthesizedNode(201 /* PostfixUnaryExpression */); node.operand = ts.parenthesizePostfixOperand(operand); node.operator = operator; return node; @@ -50831,7 +56733,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right) { - var node = createSynthesizedNode(198 /* BinaryExpression */); + var node = createSynthesizedNode(202 /* BinaryExpression */); var operatorToken = asToken(operator); var operatorKind = operatorToken.kind; node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -50848,7 +56750,7 @@ var ts; } ts.updateBinary = updateBinary; function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) { - var node = createSynthesizedNode(199 /* ConditionalExpression */); + var node = createSynthesizedNode(203 /* ConditionalExpression */); node.condition = ts.parenthesizeForConditionalHead(condition); node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(55 /* QuestionToken */); node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue); @@ -50878,7 +56780,7 @@ var ts; } ts.updateConditional = updateConditional; function createTemplateExpression(head, templateSpans) { - var node = createSynthesizedNode(200 /* TemplateExpression */); + var node = createSynthesizedNode(204 /* TemplateExpression */); node.head = head; node.templateSpans = createNodeArray(templateSpans); return node; @@ -50916,7 +56818,7 @@ var ts; } ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral; function createYield(asteriskTokenOrExpression, expression) { - var node = createSynthesizedNode(201 /* YieldExpression */); + var node = createSynthesizedNode(205 /* YieldExpression */); node.asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 39 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined; node.expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 39 /* AsteriskToken */ ? asteriskTokenOrExpression : expression; return node; @@ -50930,7 +56832,7 @@ var ts; } ts.updateYield = updateYield; function createSpread(expression) { - var node = createSynthesizedNode(202 /* SpreadElement */); + var node = createSynthesizedNode(206 /* SpreadElement */); node.expression = ts.parenthesizeExpressionForList(expression); return node; } @@ -50942,7 +56844,7 @@ var ts; } ts.updateSpread = updateSpread; function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(203 /* ClassExpression */); + var node = createSynthesizedNode(207 /* ClassExpression */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -50963,11 +56865,11 @@ var ts; } ts.updateClassExpression = updateClassExpression; function createOmittedExpression() { - return createSynthesizedNode(204 /* OmittedExpression */); + return createSynthesizedNode(208 /* OmittedExpression */); } ts.createOmittedExpression = createOmittedExpression; function createExpressionWithTypeArguments(typeArguments, expression) { - var node = createSynthesizedNode(205 /* ExpressionWithTypeArguments */); + var node = createSynthesizedNode(209 /* ExpressionWithTypeArguments */); node.expression = ts.parenthesizeForAccess(expression); node.typeArguments = asNodeArray(typeArguments); return node; @@ -50981,7 +56883,7 @@ var ts; } ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments; function createAsExpression(expression, type) { - var node = createSynthesizedNode(206 /* AsExpression */); + var node = createSynthesizedNode(210 /* AsExpression */); node.expression = expression; node.type = type; return node; @@ -50995,7 +56897,7 @@ var ts; } ts.updateAsExpression = updateAsExpression; function createNonNullExpression(expression) { - var node = createSynthesizedNode(207 /* NonNullExpression */); + var node = createSynthesizedNode(211 /* NonNullExpression */); node.expression = ts.parenthesizeForAccess(expression); return node; } @@ -51007,7 +56909,7 @@ var ts; } ts.updateNonNullExpression = updateNonNullExpression; function createMetaProperty(keywordToken, name) { - var node = createSynthesizedNode(208 /* MetaProperty */); + var node = createSynthesizedNode(212 /* MetaProperty */); node.keywordToken = keywordToken; node.name = name; return node; @@ -51021,7 +56923,7 @@ var ts; ts.updateMetaProperty = updateMetaProperty; // Misc function createTemplateSpan(expression, literal) { - var node = createSynthesizedNode(209 /* TemplateSpan */); + var node = createSynthesizedNode(214 /* TemplateSpan */); node.expression = expression; node.literal = literal; return node; @@ -51035,12 +56937,12 @@ var ts; } ts.updateTemplateSpan = updateTemplateSpan; function createSemicolonClassElement() { - return createSynthesizedNode(210 /* SemicolonClassElement */); + return createSynthesizedNode(215 /* SemicolonClassElement */); } ts.createSemicolonClassElement = createSemicolonClassElement; // Element function createBlock(statements, multiLine) { - var block = createSynthesizedNode(211 /* Block */); + var block = createSynthesizedNode(216 /* Block */); block.statements = createNodeArray(statements); if (multiLine) block.multiLine = multiLine; @@ -51054,7 +56956,7 @@ var ts; } ts.updateBlock = updateBlock; function createVariableStatement(modifiers, declarationList) { - var node = createSynthesizedNode(212 /* VariableStatement */); + var node = createSynthesizedNode(217 /* VariableStatement */); node.decorators = undefined; node.modifiers = asNodeArray(modifiers); node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; @@ -51069,23 +56971,27 @@ var ts; } ts.updateVariableStatement = updateVariableStatement; function createEmptyStatement() { - return createSynthesizedNode(213 /* EmptyStatement */); + return createSynthesizedNode(218 /* EmptyStatement */); } ts.createEmptyStatement = createEmptyStatement; - function createStatement(expression) { - var node = createSynthesizedNode(214 /* ExpressionStatement */); + function createExpressionStatement(expression) { + var node = createSynthesizedNode(219 /* ExpressionStatement */); node.expression = ts.parenthesizeExpressionForExpressionStatement(expression); return node; } - ts.createStatement = createStatement; - function updateStatement(node, expression) { + ts.createExpressionStatement = createExpressionStatement; + function updateExpressionStatement(node, expression) { return node.expression !== expression - ? updateNode(createStatement(expression), node) + ? updateNode(createExpressionStatement(expression), node) : node; } - ts.updateStatement = updateStatement; + ts.updateExpressionStatement = updateExpressionStatement; + /** @deprecated Use `createExpressionStatement` instead. */ + ts.createStatement = createExpressionStatement; + /** @deprecated Use `updateExpressionStatement` instead. */ + ts.updateStatement = updateExpressionStatement; function createIf(expression, thenStatement, elseStatement) { - var node = createSynthesizedNode(215 /* IfStatement */); + var node = createSynthesizedNode(220 /* IfStatement */); node.expression = expression; node.thenStatement = thenStatement; node.elseStatement = elseStatement; @@ -51101,7 +57007,7 @@ var ts; } ts.updateIf = updateIf; function createDo(statement, expression) { - var node = createSynthesizedNode(216 /* DoStatement */); + var node = createSynthesizedNode(221 /* DoStatement */); node.statement = statement; node.expression = expression; return node; @@ -51115,7 +57021,7 @@ var ts; } ts.updateDo = updateDo; function createWhile(expression, statement) { - var node = createSynthesizedNode(217 /* WhileStatement */); + var node = createSynthesizedNode(222 /* WhileStatement */); node.expression = expression; node.statement = statement; return node; @@ -51129,7 +57035,7 @@ var ts; } ts.updateWhile = updateWhile; function createFor(initializer, condition, incrementor, statement) { - var node = createSynthesizedNode(218 /* ForStatement */); + var node = createSynthesizedNode(223 /* ForStatement */); node.initializer = initializer; node.condition = condition; node.incrementor = incrementor; @@ -51147,7 +57053,7 @@ var ts; } ts.updateFor = updateFor; function createForIn(initializer, expression, statement) { - var node = createSynthesizedNode(219 /* ForInStatement */); + var node = createSynthesizedNode(224 /* ForInStatement */); node.initializer = initializer; node.expression = expression; node.statement = statement; @@ -51163,7 +57069,7 @@ var ts; } ts.updateForIn = updateForIn; function createForOf(awaitModifier, initializer, expression, statement) { - var node = createSynthesizedNode(220 /* ForOfStatement */); + var node = createSynthesizedNode(225 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; node.expression = expression; @@ -51181,7 +57087,7 @@ var ts; } ts.updateForOf = updateForOf; function createContinue(label) { - var node = createSynthesizedNode(221 /* ContinueStatement */); + var node = createSynthesizedNode(226 /* ContinueStatement */); node.label = asName(label); return node; } @@ -51193,7 +57099,7 @@ var ts; } ts.updateContinue = updateContinue; function createBreak(label) { - var node = createSynthesizedNode(222 /* BreakStatement */); + var node = createSynthesizedNode(227 /* BreakStatement */); node.label = asName(label); return node; } @@ -51205,7 +57111,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(223 /* ReturnStatement */); + var node = createSynthesizedNode(228 /* ReturnStatement */); node.expression = expression; return node; } @@ -51217,7 +57123,7 @@ var ts; } ts.updateReturn = updateReturn; function createWith(expression, statement) { - var node = createSynthesizedNode(224 /* WithStatement */); + var node = createSynthesizedNode(229 /* WithStatement */); node.expression = expression; node.statement = statement; return node; @@ -51231,7 +57137,7 @@ var ts; } ts.updateWith = updateWith; function createSwitch(expression, caseBlock) { - var node = createSynthesizedNode(225 /* SwitchStatement */); + var node = createSynthesizedNode(230 /* SwitchStatement */); node.expression = ts.parenthesizeExpressionForList(expression); node.caseBlock = caseBlock; return node; @@ -51245,7 +57151,7 @@ var ts; } ts.updateSwitch = updateSwitch; function createLabel(label, statement) { - var node = createSynthesizedNode(226 /* LabeledStatement */); + var node = createSynthesizedNode(231 /* LabeledStatement */); node.label = asName(label); node.statement = statement; return node; @@ -51259,7 +57165,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(227 /* ThrowStatement */); + var node = createSynthesizedNode(232 /* ThrowStatement */); node.expression = expression; return node; } @@ -51271,7 +57177,7 @@ var ts; } ts.updateThrow = updateThrow; function createTry(tryBlock, catchClause, finallyBlock) { - var node = createSynthesizedNode(228 /* TryStatement */); + var node = createSynthesizedNode(233 /* TryStatement */); node.tryBlock = tryBlock; node.catchClause = catchClause; node.finallyBlock = finallyBlock; @@ -51287,11 +57193,11 @@ var ts; } ts.updateTry = updateTry; function createDebuggerStatement() { - return createSynthesizedNode(229 /* DebuggerStatement */); + return createSynthesizedNode(234 /* DebuggerStatement */); } ts.createDebuggerStatement = createDebuggerStatement; function createVariableDeclaration(name, type, initializer) { - var node = createSynthesizedNode(230 /* VariableDeclaration */); + var node = createSynthesizedNode(235 /* VariableDeclaration */); node.name = asName(name); node.type = type; node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined; @@ -51307,7 +57213,8 @@ var ts; } ts.updateVariableDeclaration = updateVariableDeclaration; function createVariableDeclarationList(declarations, flags) { - var node = createSynthesizedNode(231 /* VariableDeclarationList */); + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(236 /* VariableDeclarationList */); node.flags |= flags & 3 /* BlockScoped */; node.declarations = createNodeArray(declarations); return node; @@ -51320,7 +57227,7 @@ var ts; } ts.updateVariableDeclarationList = updateVariableDeclarationList; function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) { - var node = createSynthesizedNode(232 /* FunctionDeclaration */); + var node = createSynthesizedNode(237 /* FunctionDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; @@ -51346,7 +57253,7 @@ var ts; } ts.updateFunctionDeclaration = updateFunctionDeclaration; function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(233 /* ClassDeclaration */); + var node = createSynthesizedNode(238 /* ClassDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51368,7 +57275,7 @@ var ts; } ts.updateClassDeclaration = updateClassDeclaration; function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) { - var node = createSynthesizedNode(234 /* InterfaceDeclaration */); + var node = createSynthesizedNode(239 /* InterfaceDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51390,7 +57297,7 @@ var ts; } ts.updateInterfaceDeclaration = updateInterfaceDeclaration; function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) { - var node = createSynthesizedNode(235 /* TypeAliasDeclaration */); + var node = createSynthesizedNode(240 /* TypeAliasDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51410,7 +57317,7 @@ var ts; } ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration; function createEnumDeclaration(decorators, modifiers, name, members) { - var node = createSynthesizedNode(236 /* EnumDeclaration */); + var node = createSynthesizedNode(241 /* EnumDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51428,7 +57335,8 @@ var ts; } ts.updateEnumDeclaration = updateEnumDeclaration; function createModuleDeclaration(decorators, modifiers, name, body, flags) { - var node = createSynthesizedNode(237 /* ModuleDeclaration */); + if (flags === void 0) { flags = 0 /* None */; } + var node = createSynthesizedNode(242 /* ModuleDeclaration */); node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 512 /* GlobalAugmentation */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); @@ -51447,7 +57355,7 @@ var ts; } ts.updateModuleDeclaration = updateModuleDeclaration; function createModuleBlock(statements) { - var node = createSynthesizedNode(238 /* ModuleBlock */); + var node = createSynthesizedNode(243 /* ModuleBlock */); node.statements = createNodeArray(statements); return node; } @@ -51459,7 +57367,7 @@ var ts; } ts.updateModuleBlock = updateModuleBlock; function createCaseBlock(clauses) { - var node = createSynthesizedNode(239 /* CaseBlock */); + var node = createSynthesizedNode(244 /* CaseBlock */); node.clauses = createNodeArray(clauses); return node; } @@ -51471,7 +57379,7 @@ var ts; } ts.updateCaseBlock = updateCaseBlock; function createNamespaceExportDeclaration(name) { - var node = createSynthesizedNode(240 /* NamespaceExportDeclaration */); + var node = createSynthesizedNode(245 /* NamespaceExportDeclaration */); node.name = asName(name); return node; } @@ -51483,7 +57391,7 @@ var ts; } ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration; function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) { - var node = createSynthesizedNode(241 /* ImportEqualsDeclaration */); + var node = createSynthesizedNode(246 /* ImportEqualsDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.name = asName(name); @@ -51501,7 +57409,7 @@ var ts; } ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration; function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) { - var node = createSynthesizedNode(242 /* ImportDeclaration */); + var node = createSynthesizedNode(247 /* ImportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; @@ -51519,7 +57427,7 @@ var ts; } ts.updateImportDeclaration = updateImportDeclaration; function createImportClause(name, namedBindings) { - var node = createSynthesizedNode(243 /* ImportClause */); + var node = createSynthesizedNode(248 /* ImportClause */); node.name = name; node.namedBindings = namedBindings; return node; @@ -51533,7 +57441,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(244 /* NamespaceImport */); + var node = createSynthesizedNode(249 /* NamespaceImport */); node.name = name; return node; } @@ -51545,7 +57453,7 @@ var ts; } ts.updateNamespaceImport = updateNamespaceImport; function createNamedImports(elements) { - var node = createSynthesizedNode(245 /* NamedImports */); + var node = createSynthesizedNode(250 /* NamedImports */); node.elements = createNodeArray(elements); return node; } @@ -51557,7 +57465,7 @@ var ts; } ts.updateNamedImports = updateNamedImports; function createImportSpecifier(propertyName, name) { - var node = createSynthesizedNode(246 /* ImportSpecifier */); + var node = createSynthesizedNode(251 /* ImportSpecifier */); node.propertyName = propertyName; node.name = name; return node; @@ -51571,7 +57479,7 @@ var ts; } ts.updateImportSpecifier = updateImportSpecifier; function createExportAssignment(decorators, modifiers, isExportEquals, expression) { - var node = createSynthesizedNode(247 /* ExportAssignment */); + var node = createSynthesizedNode(252 /* ExportAssignment */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; @@ -51588,7 +57496,7 @@ var ts; } ts.updateExportAssignment = updateExportAssignment; function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier) { - var node = createSynthesizedNode(248 /* ExportDeclaration */); + var node = createSynthesizedNode(253 /* ExportDeclaration */); node.decorators = asNodeArray(decorators); node.modifiers = asNodeArray(modifiers); node.exportClause = exportClause; @@ -51606,7 +57514,7 @@ var ts; } ts.updateExportDeclaration = updateExportDeclaration; function createNamedExports(elements) { - var node = createSynthesizedNode(249 /* NamedExports */); + var node = createSynthesizedNode(254 /* NamedExports */); node.elements = createNodeArray(elements); return node; } @@ -51618,7 +57526,7 @@ var ts; } ts.updateNamedExports = updateNamedExports; function createExportSpecifier(propertyName, name) { - var node = createSynthesizedNode(250 /* ExportSpecifier */); + var node = createSynthesizedNode(255 /* ExportSpecifier */); node.propertyName = asName(propertyName); node.name = asName(name); return node; @@ -51633,7 +57541,7 @@ var ts; ts.updateExportSpecifier = updateExportSpecifier; // Module references function createExternalModuleReference(expression) { - var node = createSynthesizedNode(252 /* ExternalModuleReference */); + var node = createSynthesizedNode(257 /* ExternalModuleReference */); node.expression = expression; return node; } @@ -51646,7 +57554,7 @@ var ts; ts.updateExternalModuleReference = updateExternalModuleReference; // JSX function createJsxElement(openingElement, children, closingElement) { - var node = createSynthesizedNode(253 /* JsxElement */); + var node = createSynthesizedNode(258 /* JsxElement */); node.openingElement = openingElement; node.children = createNodeArray(children); node.closingElement = closingElement; @@ -51661,36 +57569,40 @@ var ts; : node; } ts.updateJsxElement = updateJsxElement; - function createJsxSelfClosingElement(tagName, attributes) { - var node = createSynthesizedNode(254 /* JsxSelfClosingElement */); + function createJsxSelfClosingElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(259 /* JsxSelfClosingElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxSelfClosingElement = createJsxSelfClosingElement; - function updateJsxSelfClosingElement(node, tagName, attributes) { + function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxSelfClosingElement(tagName, attributes), node) + ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement; - function createJsxOpeningElement(tagName, attributes) { - var node = createSynthesizedNode(255 /* JsxOpeningElement */); + function createJsxOpeningElement(tagName, typeArguments, attributes) { + var node = createSynthesizedNode(260 /* JsxOpeningElement */); node.tagName = tagName; + node.typeArguments = typeArguments && createNodeArray(typeArguments); node.attributes = attributes; return node; } ts.createJsxOpeningElement = createJsxOpeningElement; - function updateJsxOpeningElement(node, tagName, attributes) { + function updateJsxOpeningElement(node, tagName, typeArguments, attributes) { return node.tagName !== tagName + || node.typeArguments !== typeArguments || node.attributes !== attributes - ? updateNode(createJsxOpeningElement(tagName, attributes), node) + ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node) : node; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(256 /* JsxClosingElement */); + var node = createSynthesizedNode(261 /* JsxClosingElement */); node.tagName = tagName; return node; } @@ -51702,7 +57614,7 @@ var ts; } ts.updateJsxClosingElement = updateJsxClosingElement; function createJsxFragment(openingFragment, children, closingFragment) { - var node = createSynthesizedNode(257 /* JsxFragment */); + var node = createSynthesizedNode(262 /* JsxFragment */); node.openingFragment = openingFragment; node.children = createNodeArray(children); node.closingFragment = closingFragment; @@ -51718,7 +57630,7 @@ var ts; } ts.updateJsxFragment = updateJsxFragment; function createJsxAttribute(name, initializer) { - var node = createSynthesizedNode(260 /* JsxAttribute */); + var node = createSynthesizedNode(265 /* JsxAttribute */); node.name = name; node.initializer = initializer; return node; @@ -51732,7 +57644,7 @@ var ts; } ts.updateJsxAttribute = updateJsxAttribute; function createJsxAttributes(properties) { - var node = createSynthesizedNode(261 /* JsxAttributes */); + var node = createSynthesizedNode(266 /* JsxAttributes */); node.properties = createNodeArray(properties); return node; } @@ -51744,7 +57656,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(262 /* JsxSpreadAttribute */); + var node = createSynthesizedNode(267 /* JsxSpreadAttribute */); node.expression = expression; return node; } @@ -51756,7 +57668,7 @@ var ts; } ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute; function createJsxExpression(dotDotDotToken, expression) { - var node = createSynthesizedNode(263 /* JsxExpression */); + var node = createSynthesizedNode(268 /* JsxExpression */); node.dotDotDotToken = dotDotDotToken; node.expression = expression; return node; @@ -51770,7 +57682,7 @@ var ts; ts.updateJsxExpression = updateJsxExpression; // Clauses function createCaseClause(expression, statements) { - var node = createSynthesizedNode(264 /* CaseClause */); + var node = createSynthesizedNode(269 /* CaseClause */); node.expression = ts.parenthesizeExpressionForList(expression); node.statements = createNodeArray(statements); return node; @@ -51784,7 +57696,7 @@ var ts; } ts.updateCaseClause = updateCaseClause; function createDefaultClause(statements) { - var node = createSynthesizedNode(265 /* DefaultClause */); + var node = createSynthesizedNode(270 /* DefaultClause */); node.statements = createNodeArray(statements); return node; } @@ -51796,7 +57708,7 @@ var ts; } ts.updateDefaultClause = updateDefaultClause; function createHeritageClause(token, types) { - var node = createSynthesizedNode(266 /* HeritageClause */); + var node = createSynthesizedNode(271 /* HeritageClause */); node.token = token; node.types = createNodeArray(types); return node; @@ -51809,7 +57721,7 @@ var ts; } ts.updateHeritageClause = updateHeritageClause; function createCatchClause(variableDeclaration, block) { - var node = createSynthesizedNode(267 /* CatchClause */); + var node = createSynthesizedNode(272 /* CatchClause */); node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration; node.block = block; return node; @@ -51824,7 +57736,7 @@ var ts; ts.updateCatchClause = updateCatchClause; // Property assignments function createPropertyAssignment(name, initializer) { - var node = createSynthesizedNode(268 /* PropertyAssignment */); + var node = createSynthesizedNode(273 /* PropertyAssignment */); node.name = asName(name); node.questionToken = undefined; node.initializer = ts.parenthesizeExpressionForList(initializer); @@ -51839,7 +57751,7 @@ var ts; } ts.updatePropertyAssignment = updatePropertyAssignment; function createShorthandPropertyAssignment(name, objectAssignmentInitializer) { - var node = createSynthesizedNode(269 /* ShorthandPropertyAssignment */); + var node = createSynthesizedNode(274 /* ShorthandPropertyAssignment */); node.name = asName(name); node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined; return node; @@ -51853,8 +57765,8 @@ var ts; } ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment; function createSpreadAssignment(expression) { - var node = createSynthesizedNode(270 /* SpreadAssignment */); - node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; + var node = createSynthesizedNode(275 /* SpreadAssignment */); + node.expression = expression !== undefined ? ts.parenthesizeExpressionForList(expression) : undefined; // TODO: GH#18217 return node; } ts.createSpreadAssignment = createSpreadAssignment; @@ -51866,7 +57778,7 @@ var ts; ts.updateSpreadAssignment = updateSpreadAssignment; // Enum function createEnumMember(name, initializer) { - var node = createSynthesizedNode(271 /* EnumMember */); + var node = createSynthesizedNode(276 /* EnumMember */); node.name = asName(name); node.initializer = initializer && ts.parenthesizeExpressionForList(initializer); return node; @@ -51880,31 +57792,33 @@ var ts; } ts.updateEnumMember = updateEnumMember; // Top-level nodes - function updateSourceFileNode(node, statements) { - if (node.statements !== statements) { - var updated = createSynthesizedNode(272 /* SourceFile */); + function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) { + if (node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) || + (libReferences !== undefined && node.libReferenceDirectives !== libReferences) || + (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) { + var updated = createSynthesizedNode(277 /* SourceFile */); updated.flags |= node.flags; updated.statements = createNodeArray(statements); updated.endOfFileToken = node.endOfFileToken; updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; + updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib; + updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) - updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) - updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) - updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; - if (node.hasNoDefaultLib !== undefined) - updated.hasNoDefaultLib = node.hasNoDefaultLib; if (node.languageVersion !== undefined) updated.languageVersion = node.languageVersion; if (node.scriptKind !== undefined) @@ -51925,6 +57839,8 @@ var ts; updated.parseDiagnostics = node.parseDiagnostics; if (node.bindDiagnostics !== undefined) updated.bindDiagnostics = node.bindDiagnostics; + if (node.bindSuggestionDiagnostics !== undefined) + updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics; if (node.lineMap !== undefined) updated.lineMap = node.lineMap; if (node.classifiableNames !== undefined) @@ -51967,7 +57883,7 @@ var ts; * @param original The original statement. */ function createNotEmittedStatement(original) { - var node = createSynthesizedNode(294 /* NotEmittedStatement */); + var node = createSynthesizedNode(304 /* NotEmittedStatement */); node.original = original; setTextRange(node, original); return node; @@ -51979,7 +57895,7 @@ var ts; */ /* @internal */ function createEndOfDeclarationMarker(original) { - var node = createSynthesizedNode(298 /* EndOfDeclarationMarker */); + var node = createSynthesizedNode(308 /* EndOfDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -51991,7 +57907,7 @@ var ts; */ /* @internal */ function createMergeDeclarationMarker(original) { - var node = createSynthesizedNode(297 /* MergeDeclarationMarker */); + var node = createSynthesizedNode(307 /* MergeDeclarationMarker */); node.emitNode = {}; node.original = original; return node; @@ -52006,7 +57922,7 @@ var ts; * @param location The location for the expression. Defaults to the positions from "original" if provided. */ function createPartiallyEmittedExpression(expression, original) { - var node = createSynthesizedNode(295 /* PartiallyEmittedExpression */); + var node = createSynthesizedNode(305 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; setTextRange(node, original); @@ -52022,7 +57938,7 @@ var ts; ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression; function flattenCommaElements(node) { if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { - if (node.kind === 296 /* CommaListExpression */) { + if (node.kind === 306 /* CommaListExpression */) { return node.elements; } if (ts.isBinaryExpression(node) && node.operatorToken.kind === 26 /* CommaToken */) { @@ -52032,7 +57948,7 @@ var ts; return node; } function createCommaList(elements) { - var node = createSynthesizedNode(296 /* CommaListExpression */); + var node = createSynthesizedNode(306 /* CommaListExpression */); node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements)); return node; } @@ -52043,15 +57959,37 @@ var ts; : node; } ts.updateCommaList = updateCommaList; - function createBundle(sourceFiles) { - var node = ts.createNode(273 /* Bundle */); + function createBundle(sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + var node = ts.createNode(278 /* Bundle */); + node.prepends = prepends; node.sourceFiles = sourceFiles; return node; } ts.createBundle = createBundle; - function updateBundle(node, sourceFiles) { - if (node.sourceFiles !== sourceFiles) { - return createBundle(sourceFiles); + function createUnparsedSourceFile(text, mapPath, map) { + var node = ts.createNode(279 /* UnparsedSource */); + node.text = text; + node.sourceMapPath = mapPath; + node.sourceMapText = map; + return node; + } + ts.createUnparsedSourceFile = createUnparsedSourceFile; + function createInputFiles(javascript, declaration, javascriptMapPath, javascriptMapText, declarationMapPath, declarationMapText) { + var node = ts.createNode(280 /* InputFiles */); + node.javascriptText = javascript; + node.javascriptMapPath = javascriptMapPath; + node.javascriptMapText = javascriptMapText; + node.declarationText = declaration; + node.declarationMapPath = declarationMapPath; + node.declarationMapText = declarationMapText; + return node; + } + ts.createInputFiles = createInputFiles; + function updateBundle(node, sourceFiles, prepends) { + if (prepends === void 0) { prepends = ts.emptyArray; } + if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) { + return createBundle(sourceFiles, prepends); } return node; } @@ -52135,6 +58073,7 @@ var ts; return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)])); } ts.createExternalModuleExport = createExternalModuleExport; + // Utilities function asName(name) { return ts.isString(name) ? createIdentifier(name) : name; } @@ -52180,7 +58119,7 @@ var ts; // To avoid holding onto transformation artifacts, we keep track of any // parse tree node we are annotating. This allows us to clean them up after // all transformations have completed. - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return node.emitNode = { annotatedNodes: [node] }; } var sourceFile = ts.getSourceFileOfNode(node); @@ -52323,6 +58262,15 @@ var ts; return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text })); } ts.addSyntheticTrailingComment = addSyntheticTrailingComment; + function moveSyntheticComments(node, original) { + setSyntheticLeadingComments(node, getSyntheticLeadingComments(original)); + setSyntheticTrailingComments(node, getSyntheticTrailingComments(original)); + var emit = getOrCreateEmitNode(original); + emit.leadingComments = undefined; + emit.trailingComments = undefined; + return node; + } + ts.moveSyntheticComments = moveSyntheticComments; /** * Gets the constant value to emit for an expression. */ @@ -52486,7 +58434,8 @@ var ts; requestEmitHelper: ts.noop, resumeLexicalEnvironment: ts.noop, startLexicalEnvironment: ts.noop, - suspendLexicalEnvironment: ts.noop + suspendLexicalEnvironment: ts.noop, + addDiagnostic: ts.noop, }; function createTypeCheck(value, tag) { return tag === "undefined" @@ -52619,7 +58568,7 @@ var ts; var valuesHelper = { name: "typescript:values", scoped: false, - text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };\n " + text: "\n var __values = (this && this.__values) || function (o) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\n if (m) return m.call(o);\n return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n };" }; function createValuesHelper(context, expression, location) { context.requestEmitHelper(valuesHelper); @@ -52630,7 +58579,7 @@ var ts; var readHelper = { name: "typescript:read", scoped: false, - text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };\n " + text: "\n var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n };" }; function createReadHelper(context, iteratorRecord, count, location) { context.requestEmitHelper(readHelper); @@ -52655,7 +58604,7 @@ var ts; // Utilities function createForOfBindingStatement(node, boundValue) { if (ts.isVariableDeclarationList(node)) { - var firstDeclaration = ts.firstOrUndefined(node.declarations); + var firstDeclaration = ts.first(node.declarations); var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, /*typeNode*/ undefined, boundValue); return ts.setTextRange(ts.createVariableStatement( @@ -52681,7 +58630,7 @@ var ts; if (!outermostLabeledStatement) { return node; } - var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 226 /* LabeledStatement */ + var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 231 /* LabeledStatement */ ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) : node); if (afterRestoreLabelCallback) { @@ -52699,19 +58648,20 @@ var ts; case 8 /* NumericLiteral */: case 9 /* StringLiteral */: return false; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: var elements = target.elements; if (elements.length === 0) { return false; } return true; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return target.properties.length > 0; default: return true; } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) { + if (cacheIdentifiers === void 0) { cacheIdentifiers = false; } var callee = skipOuterExpressions(expression, 7 /* All */); var thisArg; var target; @@ -52731,7 +58681,7 @@ var ts; } else { switch (callee.kind) { - case 183 /* PropertyAccessExpression */: { + case 187 /* PropertyAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -52744,7 +58694,7 @@ var ts; } break; } - case 184 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = ts.createTempVariable(recordTempVariable); @@ -52801,14 +58751,14 @@ var ts; ts.createExpressionForPropertyName = createExpressionForPropertyName; function createExpressionForObjectLiteralElementLike(node, property, receiver) { switch (property.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return createExpressionForAccessorDeclaration(node.properties, property, receiver, node.multiLine); - case 268 /* PropertyAssignment */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine); + case 273 /* PropertyAssignment */: return createExpressionForPropertyAssignment(property, receiver); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return createExpressionForShorthandPropertyAssignment(property, receiver); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return createExpressionForMethodDeclaration(property, receiver); } } @@ -52822,7 +58772,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, getAccessor.parameters, - /*type*/ undefined, getAccessor.body); + /*type*/ undefined, getAccessor.body // TODO: GH#18217 + ); ts.setTextRange(getterFunction, getAccessor); ts.setOriginalNode(getterFunction, getAccessor); var getter = ts.createPropertyAssignment("get", getterFunction); @@ -52833,7 +58784,8 @@ var ts; /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, setAccessor.parameters, - /*type*/ undefined, setAccessor.body); + /*type*/ undefined, setAccessor.body // TODO: GH#18217 + ); ts.setTextRange(setterFunction, setAccessor); ts.setOriginalNode(setterFunction, setAccessor); var setter = ts.createPropertyAssignment("set", setterFunction); @@ -52864,7 +58816,8 @@ var ts; return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, method.parameters, - /*type*/ undefined, method.body), + /*type*/ undefined, method.body // TODO: GH#18217 + ), /*location*/ method), /*original*/ method)), /*location*/ method), @@ -52947,6 +58900,7 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { + if (emitFlags === void 0) { emitFlags = 0; } var nodeName = ts.getNameOfDeclaration(node); if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { var name = ts.getMutableClone(nodeName); @@ -52990,7 +58944,7 @@ var ts; function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) { var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name)); ts.setTextRange(qualifiedName, name); - var emitFlags; + var emitFlags = 0; if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -53005,7 +58959,8 @@ var ts; } ts.convertToFunctionBody = convertToFunctionBody; function convertFunctionDeclarationToExpression(node) { - ts.Debug.assert(!!node.body); + if (!node.body) + return ts.Debug.fail(); var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body); ts.setOriginalNode(updated, node); ts.setTextRange(updated, node); @@ -53065,15 +59020,9 @@ var ts; return statementOffset; } ts.addStandardPrologue = addStandardPrologue; - /** - * Add just the custom prologue-directives into target statement-array. - * The function needs to be called during each transformation step. - * This function needs to be called whenever we transform the statement - * list of a source file, namespace, or function-like body. - */ function addCustomPrologue(target, source, statementOffset, visitor) { var numStatements = source.length; - while (statementOffset < numStatements) { + while (statementOffset !== undefined && statementOffset < numStatements) { var statement = source[statementOffset]; if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); @@ -53132,7 +59081,7 @@ var ts; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = ts.skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. - if (skipped.kind === 189 /* ParenthesizedExpression */) { + if (skipped.kind === 193 /* ParenthesizedExpression */) { return operand; } return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) @@ -53166,8 +59115,8 @@ var ts; // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - var binaryOperatorPrecedence = ts.getOperatorPrecedence(198 /* BinaryExpression */, binaryOperator); - var binaryOperatorAssociativity = ts.getOperatorAssociativity(198 /* BinaryExpression */, binaryOperator); + var binaryOperatorPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, binaryOperator); + var binaryOperatorAssociativity = ts.getOperatorAssociativity(202 /* BinaryExpression */, binaryOperator); var emittedOperand = ts.skipPartiallyEmittedExpressions(operand); var operandPrecedence = ts.getExpressionPrecedence(emittedOperand); switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) { @@ -53176,7 +59125,7 @@ var ts; // and is a yield expression, then we do not need parentheses. if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 /* Right */ - && operand.kind === 201 /* YieldExpression */) { + && operand.kind === 205 /* YieldExpression */) { return false; } return true; @@ -53264,7 +59213,7 @@ var ts; if (ts.isLiteralKind(node.kind)) { return node.kind; } - if (node.kind === 198 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { + if (node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 37 /* PlusToken */) { if (node.cachedLiteralKind !== undefined) { return node.cachedLiteralKind; } @@ -53279,7 +59228,7 @@ var ts; return 0 /* Unknown */; } function parenthesizeForConditionalHead(condition) { - var conditionalPrecedence = ts.getOperatorPrecedence(199 /* ConditionalExpression */, 55 /* QuestionToken */); + var conditionalPrecedence = ts.getOperatorPrecedence(203 /* ConditionalExpression */, 55 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { @@ -53293,8 +59242,7 @@ var ts; // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence var emittedExpression = ts.skipPartiallyEmittedExpressions(e); - return emittedExpression.kind === 198 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || - emittedExpression.kind === 296 /* CommaListExpression */ + return isCommaSequence(emittedExpression) ? ts.createParen(e) : e; } @@ -53312,12 +59260,15 @@ var ts; */ function parenthesizeDefaultExpression(e) { var check = ts.skipPartiallyEmittedExpressions(e); - return (check.kind === 203 /* ClassExpression */ || - check.kind === 190 /* FunctionExpression */ || - check.kind === 296 /* CommaListExpression */ || - ts.isBinaryExpression(check) && check.operatorToken.kind === 26 /* CommaToken */) - ? ts.createParen(e) - : e; + var needsParens = isCommaSequence(check); + if (!needsParens) { + switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) { + case 207 /* ClassExpression */: + case 194 /* FunctionExpression */: + needsParens = true; + } + } + return needsParens ? ts.createParen(e) : e; } ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression; /** @@ -53329,9 +59280,9 @@ var ts; function parenthesizeForNew(expression) { var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); switch (leftmostExpr.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: return ts.createParen(expression); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return !leftmostExpr.arguments ? ts.createParen(expression) : expression; @@ -53354,7 +59305,7 @@ var ts; // var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== 186 /* NewExpression */ || emittedExpression.arguments)) { + && (emittedExpression.kind !== 190 /* NewExpression */ || emittedExpression.arguments)) { return expression; } return ts.setTextRange(ts.createParen(expression), expression); @@ -53392,7 +59343,7 @@ var ts; function parenthesizeExpressionForList(expression) { var emittedExpression = ts.skipPartiallyEmittedExpressions(expression); var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression); - var commaPrecedence = ts.getOperatorPrecedence(198 /* BinaryExpression */, 26 /* CommaToken */); + var commaPrecedence = ts.getOperatorPrecedence(202 /* BinaryExpression */, 26 /* CommaToken */); return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(ts.createParen(expression), expression); @@ -53403,29 +59354,29 @@ var ts; if (ts.isCallExpression(emittedExpression)) { var callee = emittedExpression.expression; var kind = ts.skipPartiallyEmittedExpressions(callee).kind; - if (kind === 190 /* FunctionExpression */ || kind === 191 /* ArrowFunction */) { + if (kind === 194 /* FunctionExpression */ || kind === 195 /* ArrowFunction */) { var mutableCall = ts.getMutableClone(emittedExpression); mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee); return recreateOuterExpressions(expression, mutableCall, 4 /* PartiallyEmittedExpressions */); } } var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === 182 /* ObjectLiteralExpression */ || leftmostExpressionKind === 190 /* FunctionExpression */) { + if (leftmostExpressionKind === 186 /* ObjectLiteralExpression */ || leftmostExpressionKind === 194 /* FunctionExpression */) { return ts.setTextRange(ts.createParen(expression), expression); } return expression; } ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement; function parenthesizeConditionalTypeMember(member) { - return member.kind === 170 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; + return member.kind === 173 /* ConditionalType */ ? ts.createParenthesizedType(member) : member; } ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember; function parenthesizeElementTypeMember(member) { switch (member.kind) { - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return ts.createParenthesizedType(member); } return parenthesizeConditionalTypeMember(member); @@ -53433,8 +59384,9 @@ var ts; ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember; function parenthesizeArrayTypeMember(member) { switch (member.kind) { - case 164 /* TypeQuery */: - case 174 /* TypeOperator */: + case 165 /* TypeQuery */: + case 177 /* TypeOperator */: + case 174 /* InferType */: return ts.createParenthesizedType(member); } return parenthesizeElementTypeMember(member); @@ -53460,25 +59412,28 @@ var ts; function getLeftmostExpression(node, stopAtCallExpressions) { while (true) { switch (node.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: node = node.operand; continue; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: node = node.left; continue; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: node = node.condition; continue; - case 185 /* CallExpression */: + case 191 /* TaggedTemplateExpression */: + node = node.tag; + continue; + case 189 /* CallExpression */: if (stopAtCallExpressions) { return node; } // falls through - case 184 /* ElementAccessExpression */: - case 183 /* PropertyAccessExpression */: - node = node.expression; - continue; - case 295 /* PartiallyEmittedExpression */: + case 210 /* AsExpression */: + case 188 /* ElementAccessExpression */: + case 187 /* PropertyAccessExpression */: + case 211 /* NonNullExpression */: + case 305 /* PartiallyEmittedExpression */: node = node.expression; continue; } @@ -53486,12 +59441,17 @@ var ts; } } function parenthesizeConciseBody(body) { - if (!ts.isBlock(body) && getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 182 /* ObjectLiteralExpression */) { + if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 186 /* ObjectLiteralExpression */)) { return ts.setTextRange(ts.createParen(body), body); } return body; } ts.parenthesizeConciseBody = parenthesizeConciseBody; + function isCommaSequence(node) { + return node.kind === 202 /* BinaryExpression */ && node.operatorToken.kind === 26 /* CommaToken */ || + node.kind === 306 /* CommaListExpression */; + } + ts.isCommaSequence = isCommaSequence; var OuterExpressionKinds; (function (OuterExpressionKinds) { OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses"; @@ -53502,13 +59462,13 @@ var ts; function isOuterExpression(node, kinds) { if (kinds === void 0) { kinds = 7 /* All */; } switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return (kinds & 1 /* Parentheses */) !== 0; - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: - case 207 /* NonNullExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: + case 211 /* NonNullExpression */: return (kinds & 2 /* Assertions */) !== 0; - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return (kinds & 4 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -53533,7 +59493,7 @@ var ts; } ts.skipOuterExpressions = skipOuterExpressions; function skipAssertions(node) { - while (ts.isAssertionExpression(node) || node.kind === 207 /* NonNullExpression */) { + while (ts.isAssertionExpression(node) || node.kind === 211 /* NonNullExpression */) { node = node.expression; } return node; @@ -53541,11 +59501,11 @@ var ts; ts.skipAssertions = skipAssertions; function updateOuterExpression(outerExpression, expression) { switch (outerExpression.kind) { - case 189 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); - case 188 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); - case 206 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); - case 207 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); - case 295 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); + case 193 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression); + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression); + case 210 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type); + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression); + case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression); } } /** @@ -53563,7 +59523,7 @@ var ts; * the containing expression is created/updated. */ function isIgnorableParen(node) { - return node.kind === 189 /* ParenthesizedExpression */ + return node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node) && ts.nodeIsSynthesized(ts.getSourceMapRange(node)) && ts.nodeIsSynthesized(ts.getCommentRange(node)) @@ -53628,10 +59588,10 @@ var ts; var name = namespaceDeclaration.name; return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name)); } - if (node.kind === 242 /* ImportDeclaration */ && node.importClause) { + if (node.kind === 247 /* ImportDeclaration */ && node.importClause) { return ts.getGeneratedNameForNode(node); } - if (node.kind === 248 /* ExportDeclaration */ && node.moduleSpecifier) { + if (node.kind === 253 /* ExportDeclaration */ && node.moduleSpecifier) { return ts.getGeneratedNameForNode(node); } return undefined; @@ -53646,7 +59606,7 @@ var ts; * Otherwise, a new StringLiteral node representing the module name will be returned. */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { - var moduleName = ts.getExternalModuleName(importNode); + var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217 if (moduleName.kind === 9 /* StringLiteral */) { return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions) || tryRenameExternalModule(moduleName, sourceFile) @@ -53704,8 +59664,9 @@ var ts; // `1` in `({ a: b = 1 } = ...)` // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` - return ts.isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true) - ? bindingElement.initializer.right + var initializer = bindingElement.initializer; + return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + ? initializer.right : undefined; } if (ts.isShorthandPropertyAssignment(bindingElement)) { @@ -53749,7 +59710,7 @@ var ts; } if (ts.isObjectLiteralElementLike(bindingElement)) { switch (bindingElement.kind) { - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `b` in `({ a: b } = ...)` // `b` in `({ a: b = 1 } = ...)` // `{b}` in `({ a: {b} } = ...)` @@ -53761,11 +59722,11 @@ var ts; // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.initializer); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: // `a` in `({ a } = ...)` // `a` in `({ a = 1 } = ...)` return bindingElement.name; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return getTargetOfBindingOrAssignmentElement(bindingElement.expression); } @@ -53797,12 +59758,12 @@ var ts; */ function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 148 /* Parameter */: - case 180 /* BindingElement */: + case 149 /* Parameter */: + case 184 /* BindingElement */: // `...` in `let [...a] = ...` return bindingElement.dotDotDotToken; - case 202 /* SpreadElement */: - case 270 /* SpreadAssignment */: + case 206 /* SpreadElement */: + case 275 /* SpreadAssignment */: // `...` in `[...a] = ...` return bindingElement; } @@ -53814,7 +59775,7 @@ var ts; */ function getPropertyNameOfBindingOrAssignmentElement(bindingElement) { switch (bindingElement.kind) { - case 180 /* BindingElement */: + case 184 /* BindingElement */: // `a` in `let { a: b } = ...` // `[a]` in `let { [a]: b } = ...` // `"a"` in `let { "a": b } = ...` @@ -53826,7 +59787,7 @@ var ts; : propertyName; } break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // `a` in `({ a: b } = ...)` // `[a]` in `({ [a]: b } = ...)` // `"a"` in `({ "a": b } = ...)` @@ -53838,7 +59799,7 @@ var ts; : propertyName; } break; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -53856,13 +59817,13 @@ var ts; */ function getElementsOfBindingOrAssignmentPattern(name) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: // `a` in `{a}` // `a` in `[a]` return name.elements; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: // `a` in `{a}` return name.properties; } @@ -53902,11 +59863,11 @@ var ts; ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement; function convertToAssignmentPattern(node) { switch (node.kind) { - case 179 /* ArrayBindingPattern */: - case 181 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 185 /* ArrayLiteralExpression */: return convertToArrayAssignmentPattern(node); - case 178 /* ObjectBindingPattern */: - case 182 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 186 /* ObjectLiteralExpression */: return convertToObjectAssignmentPattern(node); } } @@ -53936,9 +59897,6 @@ var ts; } ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget; })(ts || (ts = {})); -/// -/// -/// var ts; (function (ts) { var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); @@ -54033,10 +59991,10 @@ var ts; context.startLexicalEnvironment(); statements = visitNodes(statements, visitor, ts.isStatement, start); if (ensureUseStrict && !ts.startsWithUseStrict(statements)) { - statements = ts.setTextRange(ts.createNodeArray([ts.createStatement(ts.createLiteral("use strict"))].concat(statements)), statements); + statements = ts.setTextRange(ts.createNodeArray([ts.createExpressionStatement(ts.createLiteral("use strict"))].concat(statements)), statements); } var declarations = context.endLexicalEnvironment(); - return ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements); + return ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, statements)), statements); } ts.visitLexicalEnvironment = visitLexicalEnvironment; /** @@ -54070,270 +60028,276 @@ var ts; } var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 144 /* LastToken */) || kind === 173 /* ThisType */) { + if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */) || kind === 176 /* ThisType */) { return node; } switch (kind) { // Names case 71 /* Identifier */: return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression)); // Signature elements - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode)); - case 148 /* Parameter */: + case 149 /* Parameter */: return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 149 /* Decorator */: + case 150 /* Decorator */: return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression)); // Type elements - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 152 /* MethodSignature */: + case 153 /* MethodSignature */: return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken)); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 154 /* Constructor */: + case 155 /* Constructor */: return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context)); - case 157 /* CallSignature */: + case 158 /* CallSignature */: return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); // Types - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: return ts.updateTypePredicateNode(node, visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode)); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); - case 162 /* FunctionType */: + case 163 /* FunctionType */: return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 163 /* ConstructorType */: + case 164 /* ConstructorType */: return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName)); - case 165 /* TypeLiteral */: + case 166 /* TypeLiteral */: return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 166 /* ArrayType */: + case 167 /* ArrayType */: return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode)); - case 167 /* TupleType */: - return ts.updateTypleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); - case 168 /* UnionType */: + case 168 /* TupleType */: + return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode)); + case 169 /* OptionalType */: + return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 170 /* RestType */: + return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode)); + case 171 /* UnionType */: return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 169 /* IntersectionType */: + case 172 /* IntersectionType */: return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode)); - case 170 /* ConditionalType */: + case 173 /* ConditionalType */: return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode)); - case 171 /* InferType */: + case 174 /* InferType */: return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration)); - case 172 /* ParenthesizedType */: + case 181 /* ImportType */: + return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf); + case 175 /* ParenthesizedType */: return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 174 /* TypeOperator */: + case 177 /* TypeOperator */: return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode)); - case 175 /* IndexedAccessType */: + case 178 /* IndexedAccessType */: return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode)); - case 176 /* MappedType */: + case 179 /* MappedType */: return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode)); - case 177 /* LiteralType */: + case 180 /* LiteralType */: return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression)); // Binding patterns - case 178 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement)); - case 179 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement)); - case 180 /* BindingElement */: + case 184 /* BindingElement */: return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression)); // Expression - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression)); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike)); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifier)); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression)); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression)); - case 187 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); - case 188 /* TypeAssertionExpression */: + case 191 /* TaggedTemplateExpression */: + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); + case 192 /* TypeAssertionExpression */: return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, visitor, ts.isToken), visitFunctionBody(node.body, visitor, context)); - case 192 /* DeleteExpression */: + case 196 /* DeleteExpression */: return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression)); - case 193 /* TypeOfExpression */: + case 197 /* TypeOfExpression */: return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression)); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression)); - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression)); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression)); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, visitor, ts.isToken)); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, visitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression)); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan)); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression)); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression)); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); - case 206 /* AsExpression */: + case 210 /* AsExpression */: return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode)); - case 207 /* NonNullExpression */: + case 211 /* NonNullExpression */: return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier)); // Misc - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element - case 211 /* Block */: + case 216 /* Block */: return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList)); - case 214 /* ExpressionStatement */: - return ts.updateStatement(node, visitNode(node.expression, visitor, ts.isExpression)); - case 215 /* IfStatement */: + case 219 /* ExpressionStatement */: + return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression)); + case 220 /* IfStatement */: return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock)); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression)); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier)); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression)); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock)); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression)); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock)); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return ts.updateVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression)); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration)); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context)); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement)); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement)); - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode)); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember)); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody)); - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause)); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference)); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 243 /* ImportClause */: + case 248 /* ImportClause */: return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings)); - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier)); - case 245 /* NamedImports */: + case 250 /* NamedImports */: return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier)); - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression)); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExports), visitNode(node.moduleSpecifier, visitor, ts.isExpression)); - case 249 /* NamedExports */: + case 254 /* NamedExports */: return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier)); - case 250 /* ExportSpecifier */: + case 255 /* ExportSpecifier */: return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier)); // Module references - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression)); // JSX - case 253 /* JsxElement */: + case 258 /* JsxElement */: return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement)); - case 254 /* JsxSelfClosingElement */: - return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 255 /* JsxOpeningElement */: - return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), visitNode(node.attributes, visitor, ts.isJsxAttributes)); - case 256 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: + return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 260 /* JsxOpeningElement */: + return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes)); + case 261 /* JsxClosingElement */: return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression)); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment)); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression)); - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike)); - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression)); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression)); // Clauses - case 264 /* CaseClause */: + case 269 /* CaseClause */: return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement)); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement)); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments)); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock)); // Property assignments - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression)); - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression)); // Enum - case 271 /* EnumMember */: + case 276 /* EnumMember */: return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression)); // Top-level nodes - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context)); // Transformation nodes - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression)); - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression)); default: // No need to visit nodes with no children. @@ -54375,58 +60339,58 @@ var ts; var cbNodes = cbNodeArray || cbNode; var kind = node.kind; // No need to visit nodes with no children. - if ((kind > 0 /* FirstToken */ && kind <= 144 /* LastToken */)) { + if ((kind > 0 /* FirstToken */ && kind <= 145 /* LastToken */)) { return initial; } // We do not yet support types. - if ((kind >= 160 /* TypePredicate */ && kind <= 177 /* LiteralType */)) { + if ((kind >= 161 /* TypePredicate */ && kind <= 180 /* LiteralType */)) { return initial; } var result = initial; switch (node.kind) { // Leaf nodes - case 210 /* SemicolonClassElement */: - case 213 /* EmptyStatement */: - case 204 /* OmittedExpression */: - case 229 /* DebuggerStatement */: - case 294 /* NotEmittedStatement */: + case 215 /* SemicolonClassElement */: + case 218 /* EmptyStatement */: + case 208 /* OmittedExpression */: + case 234 /* DebuggerStatement */: + case 304 /* NotEmittedStatement */: // No need to visit nodes with no children. break; // Names - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: result = reduceNode(node.expression, cbNode, result); break; // Signature elements - case 148 /* Parameter */: + case 149 /* Parameter */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 149 /* Decorator */: + case 150 /* Decorator */: result = reduceNode(node.expression, cbNode, result); break; // Type member - case 150 /* PropertySignature */: + case 151 /* PropertySignature */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.questionToken, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54435,12 +60399,12 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 154 /* Constructor */: + case 155 /* Constructor */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.body, cbNode, result); break; - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54448,7 +60412,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54456,49 +60420,49 @@ var ts; result = reduceNode(node.body, cbNode, result); break; // Binding patterns - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: result = reduceNodes(node.elements, cbNodes, result); break; - case 180 /* BindingElement */: + case 184 /* BindingElement */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Expression - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: result = reduceNodes(node.elements, cbNodes, result); break; - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: result = reduceNodes(node.properties, cbNodes, result); break; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.argumentExpression, cbNode, result); break; - case 185 /* CallExpression */: + case 189 /* CallExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 186 /* NewExpression */: + case 190 /* NewExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); result = reduceNodes(node.arguments, cbNodes, result); break; - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: result = reduceNode(node.tag, cbNode, result); result = reduceNode(node.template, cbNode, result); break; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: result = reduceNode(node.type, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); @@ -54506,123 +60470,123 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.parameters, cbNodes, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 189 /* ParenthesizedExpression */: - case 192 /* DeleteExpression */: - case 193 /* TypeOfExpression */: - case 194 /* VoidExpression */: - case 195 /* AwaitExpression */: - case 201 /* YieldExpression */: - case 202 /* SpreadElement */: - case 207 /* NonNullExpression */: + case 193 /* ParenthesizedExpression */: + case 196 /* DeleteExpression */: + case 197 /* TypeOfExpression */: + case 198 /* VoidExpression */: + case 199 /* AwaitExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: + case 211 /* NonNullExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: result = reduceNode(node.operand, cbNode, result); break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: result = reduceNode(node.left, cbNode, result); result = reduceNode(node.right, cbNode, result); break; - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.whenTrue, cbNode, result); result = reduceNode(node.whenFalse, cbNode, result); break; - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: result = reduceNode(node.head, cbNode, result); result = reduceNodes(node.templateSpans, cbNodes, result); break; - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.typeParameters, cbNodes, result); result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: result = reduceNode(node.expression, cbNode, result); result = reduceNodes(node.typeArguments, cbNodes, result); break; - case 206 /* AsExpression */: + case 210 /* AsExpression */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.type, cbNode, result); break; // Misc - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.literal, cbNode, result); break; // Element - case 211 /* Block */: + case 216 /* Block */: result = reduceNodes(node.statements, cbNodes, result); break; - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.declarationList, cbNode, result); break; - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 215 /* IfStatement */: + case 220 /* IfStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.thenStatement, cbNode, result); result = reduceNode(node.elseStatement, cbNode, result); break; - case 216 /* DoStatement */: + case 221 /* DoStatement */: result = reduceNode(node.statement, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 217 /* WhileStatement */: - case 224 /* WithStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 218 /* ForStatement */: + case 223 /* ForStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.condition, cbNode, result); result = reduceNode(node.incrementor, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: result = reduceNode(node.initializer, cbNode, result); result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: result = reduceNode(node.expression, cbNode, result); break; - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: result = reduceNode(node.expression, cbNode, result); result = reduceNode(node.caseBlock, cbNode, result); break; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: result = reduceNode(node.label, cbNode, result); result = reduceNode(node.statement, cbNode, result); break; - case 228 /* TryStatement */: + case 233 /* TryStatement */: result = reduceNode(node.tryBlock, cbNode, result); result = reduceNode(node.catchClause, cbNode, result); result = reduceNode(node.finallyBlock, cbNode, result); break; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.type, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: result = reduceNodes(node.declarations, cbNodes, result); break; - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54631,7 +60595,7 @@ var ts; result = reduceNode(node.type, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); @@ -54639,139 +60603,139 @@ var ts; result = reduceNodes(node.heritageClauses, cbNodes, result); result = reduceNodes(node.members, cbNodes, result); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNodes(node.members, cbNodes, result); break; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.body, cbNode, result); break; - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: result = reduceNodes(node.statements, cbNodes, result); break; - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: result = reduceNodes(node.clauses, cbNodes, result); break; - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.name, cbNode, result); result = reduceNode(node.moduleReference, cbNode, result); break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: result = reduceNodes(node.decorators, cbNodes, result); result = reduceNodes(node.modifiers, cbNodes, result); result = reduceNode(node.importClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; - case 243 /* ImportClause */: + case 248 /* ImportClause */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.namedBindings, cbNode, result); break; - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: result = reduceNode(node.name, cbNode, result); break; - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: result = reduceNodes(node.elements, cbNodes, result); break; - case 246 /* ImportSpecifier */: - case 250 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: result = reduceNode(node.propertyName, cbNode, result); result = reduceNode(node.name, cbNode, result); break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.expression, cbNode, result); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: result = ts.reduceLeft(node.decorators, cbNode, result); result = ts.reduceLeft(node.modifiers, cbNode, result); result = reduceNode(node.exportClause, cbNode, result); result = reduceNode(node.moduleSpecifier, cbNode, result); break; // Module references - case 252 /* ExternalModuleReference */: + case 257 /* ExternalModuleReference */: result = reduceNode(node.expression, cbNode, result); break; // JSX - case 253 /* JsxElement */: + case 258 /* JsxElement */: result = reduceNode(node.openingElement, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingElement, cbNode, result); break; - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: result = reduceNode(node.openingFragment, cbNode, result); result = ts.reduceLeft(node.children, cbNode, result); result = reduceNode(node.closingFragment, cbNode, result); break; - case 254 /* JsxSelfClosingElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: result = reduceNode(node.tagName, cbNode, result); result = reduceNode(node.attributes, cbNode, result); break; - case 261 /* JsxAttributes */: + case 266 /* JsxAttributes */: result = reduceNodes(node.properties, cbNodes, result); break; - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: result = reduceNode(node.tagName, cbNode, result); break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 262 /* JsxSpreadAttribute */: + case 267 /* JsxSpreadAttribute */: result = reduceNode(node.expression, cbNode, result); break; - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: result = reduceNode(node.expression, cbNode, result); break; // Clauses - case 264 /* CaseClause */: + case 269 /* CaseClause */: result = reduceNode(node.expression, cbNode, result); // falls through - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: result = reduceNodes(node.statements, cbNodes, result); break; - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: result = reduceNodes(node.types, cbNodes, result); break; - case 267 /* CatchClause */: + case 272 /* CatchClause */: result = reduceNode(node.variableDeclaration, cbNode, result); result = reduceNode(node.block, cbNode, result); break; // Property assignments - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.objectAssignmentInitializer, cbNode, result); break; - case 270 /* SpreadAssignment */: + case 275 /* SpreadAssignment */: result = reduceNode(node.expression, cbNode, result); break; // Enum - case 271 /* EnumMember */: + case 276 /* EnumMember */: result = reduceNode(node.name, cbNode, result); result = reduceNode(node.initializer, cbNode, result); break; // Top-level nodes - case 272 /* SourceFile */: + case 277 /* SourceFile */: result = reduceNodes(node.statements, cbNodes, result); break; // Transformation nodes - case 295 /* PartiallyEmittedExpression */: + case 305 /* PartiallyEmittedExpression */: result = reduceNode(node.expression, cbNode, result); break; - case 296 /* CommaListExpression */: + case 306 /* CommaListExpression */: result = reduceNodes(node.elements, cbNodes, result); break; default: @@ -54785,8 +60749,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, declarations)), statements) - : ts.addRange(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) + : ts.addStatementsAfterPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -54844,7 +60808,7 @@ var ts; function aggregateTransformFlagsForSubtree(node) { // We do not transform ambient declarations or types, so there is no need to // recursively aggregate transform flags. - if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 205 /* ExpressionWithTypeArguments */)) { + if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 209 /* ExpressionWithTypeArguments */)) { return 0 /* None */; } // Aggregate the transform flags of each child. @@ -54863,9 +60827,10 @@ var ts; var Debug; (function (Debug) { var isDebugInfoEnabled = false; - Debug.failBadSyntaxKind = Debug.shouldAssert(1 /* Normal */) - ? function (node, message) { return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", Debug.failBadSyntaxKind); } - : ts.noop; // TODO: GH#22091 + function failBadSyntaxKind(node, message) { + return Debug.fail((message || "Unexpected node.") + "\r\nNode " + ts.formatSyntaxKind(node.kind) + " was unexpected.", failBadSyntaxKind); + } + Debug.failBadSyntaxKind = failBadSyntaxKind; Debug.assertEachNode = Debug.shouldAssert(1 /* Normal */) ? function (nodes, test, message) { return Debug.assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + Debug.getFunctionName(test) + "'."; }, Debug.assertEachNode); } : ts.noop; @@ -54893,7 +60858,7 @@ var ts; }); Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, { __debugFlags: { get: function () { return ts.formatTypeFlags(this.flags); } }, - __debugObjectFlags: { get: function () { return this.flags & 65536 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, + __debugObjectFlags: { get: function () { return this.flags & 131072 /* Object */ ? ts.formatObjectFlags(this.objectFlags) : ""; } }, __debugTypeToString: { value: function () { return this.checker.typeToString(this); } }, }); var nodeConstructors = [ @@ -54929,22 +60894,297 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function createSourceFileLikeCache(host) { + var cached = ts.createMap(); + return { + get: function (path) { + if (cached.has(path)) { + return cached.get(path); + } + if (!host.fileExists || !host.readFile || !host.fileExists(path)) + return; + // And failing that, check the disk + var text = host.readFile(path); // TODO: GH#18217 + var file = { + text: text, + lineMap: undefined, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); + } + }; + cached.set(path, file); + return file; + } + }; + } + ts.createSourceFileLikeCache = createSourceFileLikeCache; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + var sourcemaps; + (function (sourcemaps) { + sourcemaps.identitySourceMapper = { getOriginalPosition: ts.identity, getGeneratedPosition: ts.identity }; + function decode(host, mapPath, map, program, fallbackCache) { + if (fallbackCache === void 0) { fallbackCache = ts.createSourceFileLikeCache(host); } + var currentDirectory = ts.getDirectoryPath(mapPath); + var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, currentDirectory) : currentDirectory; + var decodedMappings; + var generatedOrderedMappings; + var sourceOrderedMappings; + return { + getOriginalPosition: getOriginalPosition, + getGeneratedPosition: getGeneratedPosition + }; + function getGeneratedPosition(loc) { + var maps = getSourceOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { sourcePath: loc.fileName, sourcePosition: loc.position }, ts.identity, compareProcessedPositionSourcePositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + if (!maps[targetIndex] || ts.comparePaths(loc.fileName, maps[targetIndex].sourcePath, sourceRoot) !== 0) { + return loc; + } + return { fileName: ts.toPath(map.file, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].emittedPosition }; // Closest pos + } + function getOriginalPosition(loc) { + var maps = getGeneratedOrderedMappings(); + if (!ts.length(maps)) + return loc; + var targetIndex = ts.binarySearch(maps, { emittedPosition: loc.position }, ts.identity, compareProcessedPositionEmittedPositions); + if (targetIndex < 0 && maps.length > 0) { + // if no exact match, closest is 2's compliment of result + targetIndex = ~targetIndex; + } + return { fileName: ts.toPath(maps[targetIndex].sourcePath, sourceRoot, host.getCanonicalFileName), position: maps[targetIndex].sourcePosition }; // Closest pos + } + function getSourceFileLike(fileName, location) { + // Lookup file in program, if provided + var path = ts.toPath(fileName, location, host.getCanonicalFileName); + var file = program && program.getSourceFile(path); + if (!file) { + // Otherwise check the cache (which may hit disk) + return fallbackCache.get(path); + } + return file; + } + function getPositionOfLineAndCharacterUsingName(fileName, directory, line, character) { + var file = getSourceFileLike(fileName, directory); + if (!file) { + return -1; + } + return ts.getPositionOfLineAndCharacter(file, line, character); + } + function getDecodedMappings() { + return decodedMappings || (decodedMappings = calculateDecodedMappings(map, processPosition, host)); + } + function getSourceOrderedMappings() { + return sourceOrderedMappings || (sourceOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionSourcePositions)); + } + function getGeneratedOrderedMappings() { + return generatedOrderedMappings || (generatedOrderedMappings = getDecodedMappings().slice().sort(compareProcessedPositionEmittedPositions)); + } + function compareProcessedPositionSourcePositions(a, b) { + return ts.comparePaths(a.sourcePath, b.sourcePath, sourceRoot) || + ts.compareValues(a.sourcePosition, b.sourcePosition); + } + function compareProcessedPositionEmittedPositions(a, b) { + return ts.compareValues(a.emittedPosition, b.emittedPosition); + } + function processPosition(position) { + var sourcePath = map.sources[position.sourceIndex]; + return { + emittedPosition: getPositionOfLineAndCharacterUsingName(map.file, currentDirectory, position.emittedLine, position.emittedColumn), + sourcePosition: getPositionOfLineAndCharacterUsingName(sourcePath, sourceRoot, position.sourceLine, position.sourceColumn), + sourcePath: sourcePath, + }; + } + } + sourcemaps.decode = decode; + /*@internal*/ + function decodeMappings(map) { + var state = { + encodedText: map.mappings, + currentNameIndex: undefined, + sourceMapNamesLength: map.names ? map.names.length : undefined, + currentEmittedColumn: 0, + currentEmittedLine: 0, + currentSourceColumn: 0, + currentSourceLine: 0, + currentSourceIndex: 0, + decodingIndex: 0 + }; + function captureSpan() { + return { + emittedColumn: state.currentEmittedColumn, + emittedLine: state.currentEmittedLine, + sourceColumn: state.currentSourceColumn, + sourceIndex: state.currentSourceIndex, + sourceLine: state.currentSourceLine, + nameIndex: state.currentNameIndex + }; + } + return { + get decodingIndex() { return state.decodingIndex; }, + get error() { return state.error; }, + get lastSpan() { return captureSpan(); }, + next: function () { + if (hasCompletedDecoding(state) || state.error) + return { done: true, value: undefined }; + if (!decodeSinglePosition(state)) + return { done: true, value: undefined }; + return { done: false, value: captureSpan() }; + } + }; + } + sourcemaps.decodeMappings = decodeMappings; + function calculateDecodedMappings(map, processPosition, host) { + var decoder = decodeMappings(map); + var positions = ts.arrayFrom(decoder, processPosition); + if (decoder.error) { + if (host && host.log) { + host.log("Encountered error while decoding sourcemap: " + decoder.error); + } + return []; + } + return positions; + } + function hasCompletedDecoding(state) { + return state.decodingIndex === state.encodedText.length; + } + function decodeSinglePosition(state) { + while (state.decodingIndex < state.encodedText.length) { + var char = state.encodedText.charCodeAt(state.decodingIndex); + if (char === 59 /* semicolon */) { + // New line + state.currentEmittedLine++; + state.currentEmittedColumn = 0; + state.decodingIndex++; + continue; + } + if (char === 44 /* comma */) { + // Next entry is on same line - no action needed + state.decodingIndex++; + continue; + } + // Read the current position + // 1. Column offset from prev read jsColumn + state.currentEmittedColumn += base64VLQFormatDecode(); + // Incorrect emittedColumn dont support this map + if (createErrorIfCondition(state.currentEmittedColumn < 0, "Invalid emittedColumn found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted column")) { + return false; + } + // 2. Relative sourceIndex + state.currentSourceIndex += base64VLQFormatDecode(); + // Incorrect sourceIndex dont support this map + if (createErrorIfCondition(state.currentSourceIndex < 0, "Invalid sourceIndex found")) { + return false; + } + // Dont support reading mappings that dont have information about original source position + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after sourceIndex")) { + return false; + } + // 3. Relative sourceLine 0 based + state.currentSourceLine += base64VLQFormatDecode(); + // Incorrect sourceLine dont support this map + if (createErrorIfCondition(state.currentSourceLine < 0, "Invalid sourceLine found")) { + return false; + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: No entries after emitted Line")) { + return false; + } + // 4. Relative sourceColumn 0 based + state.currentSourceColumn += base64VLQFormatDecode(); + // Incorrect sourceColumn dont support this map + if (createErrorIfCondition(state.currentSourceColumn < 0, "Invalid sourceLine found")) { + return false; + } + // 5. Check if there is name: + if (!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex)) { + if (state.currentNameIndex === undefined) { + state.currentNameIndex = 0; + } + state.currentNameIndex += base64VLQFormatDecode(); + // Incorrect nameIndex dont support this map + // TODO: If we start using `name`s, issue errors when they aren't correct in the sourcemap + // if (createErrorIfCondition(state.currentNameIndex < 0 || state.currentNameIndex >= state.sourceMapNamesLength, "Invalid name index for the source map entry")) { + // return; + // } + } + // Dont support reading mappings that dont have information about original source and its line numbers + if (createErrorIfCondition(!isSourceMappingSegmentEnd(state.encodedText, state.decodingIndex), "Unsupported Error Format: There are more entries after " + (state.currentNameIndex === undefined ? "sourceColumn" : "nameIndex"))) { + return false; + } + // Entry should be complete + return true; + } + createErrorIfCondition(/*condition*/ true, "No encoded entry found"); + return false; + function createErrorIfCondition(condition, errormsg) { + if (state.error) { + // An error was already reported + return true; + } + if (condition) { + state.error = errormsg; + } + return condition; + } + function base64VLQFormatDecode() { + var moreDigits = true; + var shiftCount = 0; + var value = 0; + for (; moreDigits; state.decodingIndex++) { + if (createErrorIfCondition(state.decodingIndex >= state.encodedText.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) { + return undefined; // TODO: GH#18217 + } + // 6 digit number + var currentByte = base64FormatDecode(state.encodedText.charAt(state.decodingIndex)); + // If msb is set, we still have more bits to continue + moreDigits = (currentByte & 32) !== 0; + // least significant 5 bits are the next msbs in the final value. + value = value | ((currentByte & 31) << shiftCount); + shiftCount += 5; + } + // Least significant bit if 1 represents negative and rest of the msb is actual absolute value + if ((value & 1) === 0) { + // + number + value = value >> 1; + } + else { + // - number + value = value >> 1; + value = -value; + } + return value; + } + } + function base64FormatDecode(char) { + return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(char); + } + function isSourceMappingSegmentEnd(encodedText, pos) { + return (pos === encodedText.length || + encodedText.charCodeAt(pos) === 44 /* comma */ || + encodedText.charCodeAt(pos) === 59 /* semicolon */); + } + })(sourcemaps = ts.sourcemaps || (ts.sourcemaps = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { function getOriginalNodeId(node) { node = ts.getOriginalNode(node); return node ? ts.getNodeId(node) : 0; } ts.getOriginalNodeId = getOriginalNodeId; - function getNamedImportCount(node) { - if (!(node.importClause && node.importClause.namedBindings)) - return 0; - var names = node.importClause.namedBindings; - if (!names) - return 0; - if (!ts.isNamedImports(names)) - return 0; - return names.elements.length; - } function containsDefaultReference(node) { if (!node) return false; @@ -54953,14 +61193,42 @@ var ts; return ts.some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName && e.propertyName.escapedText === "default" /* Default */; + return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */; } + function chainBundle(transformSourceFile) { + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + return node.kind === 277 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node); + } + function transformBundle(node) { + return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); + } + } + ts.chainBundle = chainBundle; function getImportNeedsImportStarHelper(node) { - return !!ts.getNamespaceDeclarationNode(node) || (getNamedImportCount(node) > 1 && containsDefaultReference(node.importClause.namedBindings)); + if (!!ts.getNamespaceDeclarationNode(node)) { + return true; + } + var bindings = node.importClause && node.importClause.namedBindings; + if (!bindings) { + return false; + } + if (!ts.isNamedImports(bindings)) + return false; + var defaultRefCount = 0; + for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) { + var binding = _a[_i]; + if (isNamedDefaultReference(binding)) { + defaultRefCount++; + } + } + // Import star is required if there's default named refs mixed with non-default refs, or if theres non-default refs and it has a default import + return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper; function getImportNeedsImportDefaultHelper(node) { - return ts.isDefaultImport(node) || (getNamedImportCount(node) === 1 && containsDefaultReference(node.importClause.namedBindings)); + // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) + return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper; function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) { @@ -54976,21 +61244,21 @@ var ts; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var node = _a[_i]; switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import "mod" // import x from "mod" // import * as x from "mod" // import { x, y } from "mod" externalImports.push(node); - hasImportStarOrImportDefault = getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); + hasImportStarOrImportDefault = hasImportStarOrImportDefault || getImportNeedsImportStarHelper(node) || getImportNeedsImportDefaultHelper(node); break; - case 241 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 252 /* ExternalModuleReference */) { + case 246 /* ImportEqualsDeclaration */: + if (node.moduleReference.kind === 257 /* ExternalModuleReference */) { // import x = require("mod") externalImports.push(node); } break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (node.moduleSpecifier) { if (!node.exportClause) { // export * from "mod" @@ -55020,13 +61288,13 @@ var ts; } } break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: if (node.isExportEquals && !exportEquals) { // export = x exportEquals = node; } break; - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: if (ts.hasModifier(node, 1 /* Export */)) { for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) { var decl = _e[_d]; @@ -55034,7 +61302,7 @@ var ts; } } break; - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default function() { } @@ -55054,7 +61322,7 @@ var ts; } } break; - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (ts.hasModifier(node, 1 /* Export */)) { if (ts.hasModifier(node, 512 /* Default */)) { // export default class { } @@ -55128,9 +61396,27 @@ var ts; ts.isIdentifier(expression); } ts.isSimpleCopiableExpression = isSimpleCopiableExpression; + /** + * @param input Template string input strings + * @param args Names which need to be made file-level unique + */ + function helperString(input) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return function (uniqueName) { + var result = ""; + for (var i = 0; i < args.length; i++) { + result += input[i]; + result += uniqueName(args[i]); + } + result += input[input.length - 1]; + return result; + }; + } + ts.helperString = helperString; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -55161,7 +61447,7 @@ var ts; value = node.right; } else { - return value; + return ts.visitNode(value, visitor, ts.isExpression); } } } @@ -55169,7 +61455,7 @@ var ts; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: true, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -55230,7 +61516,7 @@ var ts; } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; function bindingOrAssignmentElementAssignsToName(element, escapedName) { - var target = ts.getTargetOfBindingOrAssignmentElement(element); + var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); } @@ -55261,13 +61547,14 @@ var ts; * @param level Indicates the extent to which flattening should occur. */ function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { + if (hoistTempVariables === void 0) { hoistTempVariables = false; } var pendingExpressions; var pendingDeclarations = []; var declarations = []; var flattenContext = { context: context, level: level, - downlevelIteration: context.getCompilerOptions().downlevelIteration, + downlevelIteration: !!context.getCompilerOptions().downlevelIteration, hoistTempVariables: hoistTempVariables, emitExpression: emitExpression, emitBindingOrAssignment: emitBindingOrAssignment, @@ -55295,7 +61582,7 @@ var ts; } else { context.hoistVariableDeclaration(temp); - var pendingDeclaration = ts.lastOrUndefined(pendingDeclarations); + var pendingDeclaration = ts.last(pendingDeclarations); pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value)); ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions); pendingDeclaration.value = temp; @@ -55349,7 +61636,7 @@ var ts; value = ts.createVoidZero(); } } - var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); + var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217 if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) { flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } @@ -55357,7 +61644,7 @@ var ts; flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); + flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217 } } /** @@ -55409,7 +61696,7 @@ var ts; flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); bindingElements = undefined; } - var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); + var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); } } @@ -55605,9 +61892,6 @@ var ts; ]); } })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -55654,13 +61938,14 @@ var ts; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; // Enable substitution for property/element access to emit const enum values. - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; - var currentScope; + var currentLexicalScope; + var currentNameScope; var currentScopeFirstDeclarationsOfName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -55682,7 +61967,21 @@ var ts; * at the next execution site, in document order */ var pendingExpressions; - return transformSourceFile; + return transformSourceFileOrBundle; + function transformSourceFileOrBundle(node) { + if (node.kind === 278 /* Bundle */) { + return transformBundle(node); + } + return transformSourceFile(node); + } + function transformBundle(node) { + return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.javascriptText, prepend.javascriptMapPath, prepend.javascriptMapText); + } + return prepend; + })); + } /** * Transform TypeScript-specific syntax in a SourceFile. * @@ -55705,16 +62004,18 @@ var ts; */ function saveStateAndInvoke(node, f) { // Save state - var savedCurrentScope = currentScope; + var savedCurrentScope = currentLexicalScope; + var savedCurrentNameScope = currentNameScope; var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state - if (currentScope !== savedCurrentScope) { + if (currentLexicalScope !== savedCurrentScope) { currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } - currentScope = savedCurrentScope; + currentLexicalScope = savedCurrentScope; + currentNameScope = savedCurrentNameScope; return visited; } /** @@ -55724,15 +62025,16 @@ var ts; */ function onBeforeVisitNode(node) { switch (node.kind) { - case 272 /* SourceFile */: - case 239 /* CaseBlock */: - case 238 /* ModuleBlock */: - case 211 /* Block */: - currentScope = node; + case 277 /* SourceFile */: + case 244 /* CaseBlock */: + case 243 /* ModuleBlock */: + case 216 /* Block */: + currentLexicalScope = node; + currentNameScope = undefined; currentScopeFirstDeclarationsOfName = undefined; break; - case 233 /* ClassDeclaration */: - case 232 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: if (ts.hasModifier(node, 2 /* Ambient */)) { break; } @@ -55744,7 +62046,11 @@ var ts; // 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 === 233 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + ts.Debug.assert(node.kind === 238 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */)); + } + if (ts.isClassDeclaration(node)) { + // XXX: should probably also cover interfaces and type aliases that can have type variables? + currentNameScope = node; } break; } @@ -55788,10 +62094,10 @@ var ts; */ function sourceElementVisitorWorker(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return visitEllidableStatement(node); default: return visitorWorker(node); @@ -55812,13 +62118,13 @@ var ts; return node; } switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); default: ts.Debug.fail("Unhandled ellided statement"); @@ -55838,11 +62144,11 @@ var ts; * @param node The node to visit. */ function namespaceElementVisitorWorker(node) { - if (node.kind === 248 /* ExportDeclaration */ || - node.kind === 242 /* ImportDeclaration */ || - node.kind === 243 /* ImportClause */ || - (node.kind === 241 /* ImportEqualsDeclaration */ && - node.moduleReference.kind === 252 /* ExternalModuleReference */)) { + if (node.kind === 253 /* ExportDeclaration */ || + node.kind === 247 /* ImportDeclaration */ || + node.kind === 248 /* ImportClause */ || + (node.kind === 246 /* ImportEqualsDeclaration */ && + node.moduleReference.kind === 257 /* ExternalModuleReference */)) { // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } @@ -55872,23 +62178,22 @@ var ts; */ function classElementVisitorWorker(node) { switch (node.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: // TypeScript constructors are transformed in `visitClassDeclaration`. // We elide them here as `visitorWorker` checks transform flags, which could // erronously include an ES6 constructor without TypeScript syntax. return undefined; - case 151 /* PropertyDeclaration */: - case 159 /* IndexSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 153 /* MethodDeclaration */: + case 152 /* PropertyDeclaration */: + case 160 /* IndexSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 154 /* MethodDeclaration */: // Fallback to the default visit behavior. return visitorWorker(node); - case 210 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: return node; default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function modifierVisitor(node) { @@ -55924,52 +62229,55 @@ var ts; case 124 /* DeclareKeyword */: case 132 /* ReadonlyKeyword */: // TypeScript accessibility and readonly modifiers are elided. - case 166 /* ArrayType */: - case 167 /* TupleType */: - case 165 /* TypeLiteral */: - case 160 /* TypePredicate */: - case 147 /* TypeParameter */: + case 167 /* ArrayType */: + case 168 /* TupleType */: + case 169 /* OptionalType */: + case 170 /* RestType */: + case 166 /* TypeLiteral */: + case 161 /* TypePredicate */: + case 148 /* TypeParameter */: case 119 /* AnyKeyword */: + case 142 /* UnknownKeyword */: case 122 /* BooleanKeyword */: case 137 /* StringKeyword */: case 134 /* NumberKeyword */: case 131 /* NeverKeyword */: case 105 /* VoidKeyword */: case 138 /* SymbolKeyword */: - case 163 /* ConstructorType */: - case 162 /* FunctionType */: - case 164 /* TypeQuery */: - case 161 /* TypeReference */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: - case 170 /* ConditionalType */: - case 172 /* ParenthesizedType */: - case 173 /* ThisType */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 177 /* LiteralType */: + case 164 /* ConstructorType */: + case 163 /* FunctionType */: + case 165 /* TypeQuery */: + case 162 /* TypeReference */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: + case 173 /* ConditionalType */: + case 175 /* ParenthesizedType */: + case 176 /* ThisType */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 180 /* LiteralType */: // TypeScript type nodes are elided. - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: // TypeScript index signatures are elided. - case 149 /* Decorator */: + case 150 /* Decorator */: // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration. - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // TypeScript type-only declarations are elided. return undefined; - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects return visitPropertyDeclaration(node); - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: // TypeScript namespace export declarations are elided. return undefined; - case 154 /* Constructor */: + case 155 /* Constructor */: return visitConstructor(node); - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: // TypeScript interfaces are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: // This is a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -55980,7 +62288,7 @@ var ts; // - index signatures // - method overload signatures return visitClassDeclaration(node); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: // This is a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: @@ -55991,35 +62299,35 @@ var ts; // - index signatures // - method overload signatures return visitClassExpression(node); - case 266 /* HeritageClause */: + case 271 /* HeritageClause */: // This is a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause return visitHeritageClause(node); - case 205 /* ExpressionWithTypeArguments */: + case 209 /* ExpressionWithTypeArguments */: // TypeScript supports type arguments on an expression in an `extends` heritage clause. return visitExpressionWithTypeArguments(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: // Get Accessors can have TypeScript modifiers, decorators, and type annotations. return visitGetAccessor(node); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); - case 148 /* Parameter */: + case 149 /* Parameter */: // This is a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: @@ -56029,43 +62337,45 @@ var ts; // - type annotations // - this parameters return visitParameter(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: // ParenthesizedExpressions are TypeScript if their expression is a // TypeAssertion or AsExpression return visitParenthesizedExpression(node); - case 188 /* TypeAssertionExpression */: - case 206 /* AsExpression */: + case 192 /* TypeAssertionExpression */: + case 210 /* AsExpression */: // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 207 /* NonNullExpression */: + case 191 /* TaggedTemplateExpression */: + return visitTaggedTemplateExpression(node); + case 211 /* NonNullExpression */: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } function visitSourceFile(node) { var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") && - !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015); + !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) && + !ts.isJsonSourceFile(node); return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict)); } /** @@ -56091,7 +62401,7 @@ var ts; var facts = 0 /* None */; if (ts.some(staticProperties)) facts |= 1 /* HasStaticInitializedProperties */; - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; if (shouldEmitDecorateCallForClass(node)) @@ -56134,7 +62444,7 @@ var ts; var statements = [classStatement]; // Write any pending expressions from elided or moved computed property names if (ts.some(pendingExpressions)) { - statements.push(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); } pendingExpressions = savedPendingExpressions; // Emit static property assignment. Because classDeclaration is lexically evaluated, @@ -56172,7 +62482,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, context.endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -56377,7 +62687,7 @@ var ts; // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); var alias = ts.getSynthesizedClone(temp); - alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */; classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent @@ -56495,7 +62805,7 @@ var ts; // // super(...arguments); // - statements.push(ts.createStatement(ts.createCall(ts.createSuper(), + statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))]))); } // Add the property initializers. Transforms this: @@ -56537,7 +62847,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { + if (statement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -56574,7 +62884,7 @@ var ts; ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */); var localName = ts.getMutableClone(name); ts.setEmitFlags(localName, 1536 /* NoComments */); - return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); + return ts.startOnNewLine(ts.setEmitFlags(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), ts.moveRangePos(node, -1)), 1536 /* NoComments */)); } /** * Gets all property declarations with initializers on either the static or instance side of a class. @@ -56608,7 +62918,7 @@ var ts; * @param isStatic A value indicating whether the member should be a static or instance member. */ function isInitializedProperty(member, isStatic) { - return member.kind === 151 /* PropertyDeclaration */ + return member.kind === 152 /* PropertyDeclaration */ && isStatic === ts.hasModifier(member, 32 /* Static */) && member.initializer !== undefined; } @@ -56621,7 +62931,7 @@ var ts; function addInitializedPropertyStatements(statements, properties, receiver) { for (var _i = 0, properties_10 = properties; _i < properties_10.length; _i++) { var property = properties_10[_i]; - var statement = ts.createStatement(transformInitializedProperty(property, receiver)); + var statement = ts.createExpressionStatement(transformInitializedProperty(property, receiver)); ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); ts.setCommentRange(statement, property); statements.push(statement); @@ -56654,7 +62964,7 @@ var ts; function transformInitializedProperty(property, receiver) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) var propertyName = ts.isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) - ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name, !ts.hasModifier(property, 32 /* Static */))) + ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name)) : property.name; var initializer = ts.visitNode(property.initializer, visitor, ts.isExpression); var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName); @@ -56746,12 +63056,12 @@ var ts; */ function getAllDecoratorsOfClassElement(node, member) { switch (member.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return getAllDecoratorsOfAccessors(node, member); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return getAllDecoratorsOfMethod(member); - case 151 /* PropertyDeclaration */: + case 152 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return undefined; @@ -56845,8 +63155,8 @@ var ts; function generateClassElementDecorationExpressions(node, isStatic) { var members = getDecoratedClassElements(node, isStatic); var expressions; - for (var _i = 0, members_4 = members; _i < members_4.length; _i++) { - var member = members_4[_i]; + for (var _i = 0, members_5 = members; _i < members_5.length; _i++) { + var member = members_5[_i]; var expression = generateClassElementDecorationExpression(node, member); if (expression) { if (!expressions) { @@ -56904,7 +63214,7 @@ var ts; var prefix = getClassMemberPrefix(node, member); var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); var descriptor = languageVersion > 0 /* ES3 */ - ? member.kind === 151 /* PropertyDeclaration */ + ? member.kind === 152 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it // should not invoke `Object.getOwnPropertyDescriptor`. ? ts.createVoidZero() @@ -56924,7 +63234,7 @@ var ts; function addConstructorDecorationStatement(statements, node) { var expression = generateConstructorDecorationExpression(node); if (expression) { - statements.push(ts.setOriginalNode(ts.createStatement(expression), node)); + statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node)); } } /** @@ -57027,10 +63337,10 @@ var ts; */ function shouldAddTypeMetadata(node) { var kind = node.kind; - return kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */ - || kind === 151 /* PropertyDeclaration */; + return kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */ + || kind === 152 /* PropertyDeclaration */; } /** * Determines whether to emit the "design:returntype" metadata based on the node's kind. @@ -57040,7 +63350,7 @@ var ts; * @param node The node to test. */ function shouldAddReturnTypeMetadata(node) { - return node.kind === 153 /* MethodDeclaration */; + return node.kind === 154 /* MethodDeclaration */; } /** * Determines whether to emit the "design:paramtypes" metadata based on the node's kind. @@ -57051,12 +63361,12 @@ var ts; */ function shouldAddParamTypesMetadata(node) { switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return ts.getFirstConstructorWithBody(node) !== undefined; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return true; } return false; @@ -57068,15 +63378,15 @@ var ts; */ function serializeTypeOfNode(node) { switch (node.kind) { - case 151 /* PropertyDeclaration */: - case 148 /* Parameter */: - case 155 /* GetAccessor */: + case 152 /* PropertyDeclaration */: + case 149 /* Parameter */: + case 156 /* GetAccessor */: return serializeTypeNode(node.type); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return serializeTypeNode(ts.getSetAccessorTypeAnnotationNode(node)); - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 153 /* MethodDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 154 /* MethodDeclaration */: return ts.createIdentifier("Function"); default: return ts.createVoidZero(); @@ -57113,7 +63423,7 @@ var ts; return ts.createArrayLiteral(expressions); } function getParametersOfDecoratedDeclaration(node, container) { - if (container && node.kind === 155 /* GetAccessor */) { + if (container && node.kind === 156 /* GetAccessor */) { var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor; if (setAccessor) { return setAccessor.parameters; @@ -57163,22 +63473,22 @@ var ts; case 95 /* NullKeyword */: case 131 /* NeverKeyword */: return ts.createVoidZero(); - case 172 /* ParenthesizedType */: + case 175 /* ParenthesizedType */: return serializeTypeNode(node.type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return ts.createIdentifier("Function"); - case 166 /* ArrayType */: - case 167 /* TupleType */: + case 167 /* ArrayType */: + case 168 /* TupleType */: return ts.createIdentifier("Array"); - case 160 /* TypePredicate */: + case 161 /* TypePredicate */: case 122 /* BooleanKeyword */: return ts.createIdentifier("Boolean"); case 137 /* StringKeyword */: return ts.createIdentifier("String"); case 135 /* ObjectKeyword */: return ts.createIdentifier("Object"); - case 177 /* LiteralType */: + case 180 /* LiteralType */: switch (node.literal.kind) { case 9 /* StringLiteral */: return ts.createIdentifier("String"); @@ -57188,32 +63498,31 @@ var ts; case 86 /* FalseKeyword */: return ts.createIdentifier("Boolean"); default: - ts.Debug.failBadSyntaxKind(node.literal); - break; + return ts.Debug.failBadSyntaxKind(node.literal); } - break; case 134 /* NumberKeyword */: return ts.createIdentifier("Number"); case 138 /* SymbolKeyword */: return languageVersion < 2 /* ES2015 */ ? getGlobalSymbolNameWithFallback() : ts.createIdentifier("Symbol"); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return serializeTypeReferenceNode(node); - case 169 /* IntersectionType */: - case 168 /* UnionType */: + case 172 /* IntersectionType */: + case 171 /* UnionType */: return serializeUnionOrIntersectionType(node); - case 164 /* TypeQuery */: - case 174 /* TypeOperator */: - case 175 /* IndexedAccessType */: - case 176 /* MappedType */: - case 165 /* TypeLiteral */: + case 165 /* TypeQuery */: + case 177 /* TypeOperator */: + case 178 /* IndexedAccessType */: + case 179 /* MappedType */: + case 166 /* TypeLiteral */: case 119 /* AnyKeyword */: - case 173 /* ThisType */: + case 142 /* UnknownKeyword */: + case 176 /* ThisType */: + case 181 /* ImportType */: break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } return ts.createIdentifier("Object"); } @@ -57223,7 +63532,7 @@ var ts; var serializedUnion; for (var _i = 0, _a = node.types; _i < _a.length; _i++) { var typeNode = _a[_i]; - while (typeNode.kind === 172 /* ParenthesizedType */) { + while (typeNode.kind === 175 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === 131 /* NeverKeyword */) { @@ -57262,13 +63571,14 @@ var ts; * @param node The type reference node. */ function serializeTypeReferenceNode(node) { - switch (resolver.getTypeReferenceSerializationKind(node.typeName, currentScope)) { + var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope); + switch (kind) { case ts.TypeReferenceSerializationKind.Unknown: - var serialized = serializeEntityNameAsExpression(node.typeName, /*useFallback*/ true); + var serialized = serializeEntityNameAsExpressionFallback(node.typeName); var temp = ts.createTempVariable(hoistVariableDeclaration); - return ts.createLogicalOr(ts.createLogicalAnd(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp), ts.createIdentifier("Object")); + return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object")); case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue: - return serializeEntityNameAsExpression(node.typeName, /*useFallback*/ false); + return serializeEntityNameAsExpression(node.typeName); case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType: return ts.createVoidZero(); case ts.TypeReferenceSerializationKind.BooleanType: @@ -57288,18 +63598,40 @@ var ts; case ts.TypeReferenceSerializationKind.Promise: return ts.createIdentifier("Promise"); case ts.TypeReferenceSerializationKind.ObjectType: - default: return ts.createIdentifier("Object"); + default: + return ts.Debug.assertNever(kind); } } + function createCheckedValue(left, right) { + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right); + } + /** + * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw + * + * @param node The entity name to serialize. + */ + function serializeEntityNameAsExpressionFallback(node) { + if (node.kind === 71 /* Identifier */) { + // A -> typeof A !== undefined && A + var copied = serializeEntityNameAsExpression(node); + return createCheckedValue(copied, copied); + } + if (node.left.kind === 71 /* Identifier */) { + // A.B -> typeof A !== undefined && A.B + return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node)); + } + // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C + var left = serializeEntityNameAsExpressionFallback(node.left); + var temp = ts.createTempVariable(hoistVariableDeclaration); + return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right)); + } /** * Serializes an entity name as an expression for decorator type metadata. * * @param node The entity name to serialize. - * @param useFallback A value indicating whether to use logical operators to test for the - * entity name at runtime. */ - function serializeEntityNameAsExpression(node, useFallback) { + function serializeEntityNameAsExpression(node) { switch (node.kind) { case 71 /* Identifier */: // Create a clone of the name with a new parent, and treat it as if it were @@ -57307,13 +63639,10 @@ var ts; var name = ts.getMutableClone(node); name.flags &= ~8 /* Synthesized */; name.original = undefined; - name.parent = ts.getParseTreeNode(currentScope); // ensure the parent is set to a parse tree node. - if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name), ts.createLiteral("undefined")), name); - } + name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node. return name; - case 145 /* QualifiedName */: - return serializeQualifiedNameAsExpression(node, useFallback); + case 146 /* QualifiedName */: + return serializeQualifiedNameAsExpression(node); } } /** @@ -57323,19 +63652,8 @@ var ts; * @param useFallback A value indicating whether to use logical operators to test for the * qualified name at runtime. */ - function serializeQualifiedNameAsExpression(node, useFallback) { - var left; - if (node.left.kind === 71 /* Identifier */) { - left = serializeEntityNameAsExpression(node.left, useFallback); - } - else if (useFallback) { - var temp = ts.createTempVariable(hoistVariableDeclaration); - left = ts.createLogicalAnd(ts.createAssignment(temp, serializeEntityNameAsExpression(node.left, /*useFallback*/ true)), temp); - } - else { - left = serializeEntityNameAsExpression(node.left, /*useFallback*/ false); - } - return ts.createPropertyAccess(left, node.right); + function serializeQualifiedNameAsExpression(node) { + return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right); } /** * Gets an expression that points to the global "Symbol" constructor at runtime if it is @@ -57641,7 +63959,7 @@ var ts; // elide statement if there are no initialized variables. return undefined; } - return ts.setTextRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } else { return ts.visitEachChild(node, visitor, context); @@ -57687,6 +64005,11 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. + // HOWEVER - if there are leading comments on the expression itself, to handle ASI + // correctly for return and throw, we must keep the parenthesis + if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { + return ts.updateParen(node, expression); + } return ts.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -57707,13 +64030,17 @@ var ts; return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); } + function visitTaggedTemplateExpression(node) { + return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), + /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression)); + } /** * Determines whether to emit an enum declaration. * * @param node The enum declaration node. */ function shouldEmitEnumDeclaration(node) { - return !ts.isConst(node) + return !ts.isEnumConst(node) || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } @@ -57737,7 +64064,7 @@ var ts; // enum body. if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -57762,7 +64089,7 @@ var ts; // x[x["y"] = 0] = "y"; // ... // })(x || (x = {})); - var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -57788,8 +64115,9 @@ var ts; currentNamespaceContainerName = localName; var statements = []; startLexicalEnvironment(); - ts.addRange(statements, ts.map(node.members, transformEnumMember)); - ts.addRange(statements, endLexicalEnvironment()); + var members = ts.map(node.members, transformEnumMember); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); @@ -57809,7 +64137,7 @@ var ts; var outerAssignment = valueExpression.kind === 9 /* StringLiteral */ ? innerAssignment : ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name); - return ts.setTextRange(ts.createStatement(ts.setTextRange(outerAssignment, member)), member); + return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member); } /** * Transforms the value of an enum member. @@ -57837,7 +64165,7 @@ var ts; * @param node The module declaration node. */ function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); + return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules); } /** * Determines whether an exported declaration will have a qualified export name (e.g. `f.x` @@ -57887,12 +64215,12 @@ var ts; // enums in any other scope are emitted as a `let` declaration. var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) - ], currentScope.kind === 272 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); + ], currentLexicalScope.kind === 277 /* SourceFile */ ? 0 /* None */ : 1 /* Let */)); ts.setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { // Adjust the source map emit to match the old emitter. - if (node.kind === 236 /* EnumDeclaration */) { + if (node.kind === 241 /* EnumDeclaration */) { ts.setSourceMapRange(statement.declarationList, node); } else { @@ -57954,7 +64282,7 @@ var ts; // module body. if (addVarForEnumOrModuleDeclaration(statements, node)) { // We should still emit the comments if we are emitting a system module. - if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { + if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) { emitFlags |= 512 /* NoLeadingComments */; } } @@ -57978,7 +64306,7 @@ var ts; // (function (x_1) { // x_1.y = ...; // })(x || (x = {})); - var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression( + var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, @@ -58011,7 +64339,7 @@ var ts; var statementsLocation; var blockLocation; var body = node.body; - if (body.kind === 238 /* ModuleBlock */) { + if (body.kind === 243 /* ModuleBlock */) { saveStateAndInvoke(body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); }); statementsLocation = body.statements; blockLocation = body; @@ -58029,7 +64357,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -58057,13 +64385,13 @@ var ts; // })(hi = hello.hi || (hello.hi = {})); // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. - if (body.kind !== 238 /* ModuleBlock */) { + if (body.kind !== 243 /* ModuleBlock */) { ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */); } return block; } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 237 /* ModuleDeclaration */) { + if (moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } @@ -58104,7 +64432,7 @@ var ts; * @param node The named import bindings node. */ function visitNamedImportBindings(node) { - if (node.kind === 244 /* NamespaceImport */) { + if (node.kind === 249 /* NamespaceImport */) { // Elide a namespace import if it is not referenced. return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } @@ -58259,17 +64587,17 @@ var ts; * Creates a statement for the provided expression. This is used in calls to `map`. */ function expressionToStatement(expression) { - return ts.createStatement(expression); + return ts.createExpressionStatement(expression); } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node)); ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end)); - var statement = ts.createStatement(expression); + var statement = ts.createExpressionStatement(expression); ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { - return ts.setTextRange(ts.createStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); + return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location); } function createNamespaceExportExpression(exportName, exportValue, location) { return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location); @@ -58336,16 +64664,16 @@ var ts; // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to // substitute the names of exported members of a namespace. context.enableSubstitution(71 /* Identifier */); - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // We need to be notified when entering and exiting namespaces. - context.enableEmitNotification(237 /* ModuleDeclaration */); + context.enableEmitNotification(242 /* ModuleDeclaration */); } } function isTransformedModuleDeclaration(node) { - return ts.getOriginalNode(node).kind === 237 /* ModuleDeclaration */; + return ts.getOriginalNode(node).kind === 242 /* ModuleDeclaration */; } function isTransformedEnumDeclaration(node) { - return ts.getOriginalNode(node).kind === 236 /* EnumDeclaration */; + return ts.getOriginalNode(node).kind === 241 /* EnumDeclaration */; } /** * Hook for node emit. @@ -58406,9 +64734,9 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); } return node; @@ -58428,7 +64756,7 @@ var ts; // constructor references in static property initializers. var declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { - var classAlias = classAliases[declaration.id]; + var classAlias = classAliases[declaration.id]; // TODO: GH#18217 if (classAlias) { var clone_1 = ts.getSynthesizedClone(classAlias); ts.setSourceMapRange(clone_1, node); @@ -58446,9 +64774,9 @@ var ts; // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); - if (container && container.kind !== 272 /* SourceFile */) { - var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 237 /* ModuleDeclaration */) || - (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 236 /* EnumDeclaration */); + if (container && container.kind !== 277 /* SourceFile */) { + var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 242 /* ModuleDeclaration */) || + (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 241 /* EnumDeclaration */); if (substitute) { return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), /*location*/ node); @@ -58536,8 +64864,6 @@ var ts; text: "\n var __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n };" }; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -58568,7 +64894,7 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -58585,15 +64911,15 @@ var ts; case 120 /* AsyncKeyword */: // ES2017 async modifier should be elided for targets < ES2017 return undefined; - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); default: return ts.visitEachChild(node, visitor, context); @@ -58602,27 +64928,27 @@ var ts; function asyncBodyVisitor(node) { if (ts.isNodeWithPossibleHoistedDeclaration(node)) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatementInAsyncBody(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatementInAsyncBody(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatementInAsyncBody(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatementInAsyncBody(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClauseInAsyncBody(node); - case 211 /* Block */: - case 225 /* SwitchStatement */: - case 239 /* CaseBlock */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: - case 228 /* TryStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 215 /* IfStatement */: - case 224 /* WithStatement */: - case 226 /* LabeledStatement */: + case 216 /* Block */: + case 230 /* SwitchStatement */: + case 244 /* CaseBlock */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 229 /* WithStatement */: + case 231 /* LabeledStatement */: return ts.visitEachChild(node, asyncBodyVisitor, context); default: return ts.Debug.assertNever(node, "Unhandled node."); @@ -58632,7 +64958,7 @@ var ts; } function visitCatchClauseInAsyncBody(node) { var catchClauseNames = ts.createUnderscoreEscapedMap(); - recordDeclarationName(node.variableDeclaration, catchClauseNames); + recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217 // names declared in a catch variable are block scoped var catchClauseUnshadowedNames; catchClauseNames.forEach(function (_, escapedName) { @@ -58657,7 +64983,7 @@ var ts; function visitVariableStatementInAsyncBody(node) { if (isVariableDeclarationListWithCollidingName(node.declarationList)) { var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); - return expression ? ts.createStatement(expression) : undefined; + return expression ? ts.createExpressionStatement(expression) : undefined; } return ts.visitEachChild(node, visitor, context); } @@ -58672,8 +64998,9 @@ var ts; : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } function visitForStatementInAsyncBody(node) { - return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + var initializer = node.initializer; // TODO: GH#18217 + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer) + ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); } /** @@ -58765,10 +65092,10 @@ var ts; } } function isVariableDeclarationListWithCollidingName(node) { - return node + return !!node && ts.isVariableDeclarationList(node) && !(node.flags & 3 /* BlockScoped */) - && ts.forEach(node.declarations, collidesWithParameterName); + && node.declarations.some(collidesWithParameterName); } function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { hoistVariableDeclarationList(node); @@ -58822,7 +65149,7 @@ var ts; var original = ts.getOriginalNode(node, ts.isFunctionLike); var nodeType = original.type; var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined; - var isArrowFunction = node.kind === 191 /* ArrowFunction */; + var isArrowFunction = node.kind === 195 /* ArrowFunction */; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -58840,7 +65167,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. @@ -58862,7 +65189,7 @@ var ts; var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements)); } else { result = expression; @@ -58895,15 +65222,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(185 /* CallExpression */); - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(233 /* ClassDeclaration */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(154 /* Constructor */); + context.enableEmitNotification(238 /* ClassDeclaration */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(155 /* Constructor */); } } /** @@ -58943,11 +65270,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -58979,19 +65306,19 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 233 /* ClassDeclaration */ - || kind === 154 /* Constructor */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */; + return kind === 238 /* ClassDeclaration */ + || kind === 155 /* Constructor */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { - return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_super"), /*typeArguments*/ undefined, [argumentExpression]), "value"), location); } else { - return ts.setTextRange(ts.createCall(ts.createIdentifier("_super"), + return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_super"), /*typeArguments*/ undefined, [argumentExpression]), location); } } @@ -59024,17 +65351,14 @@ var ts; ts.asyncSuperHelper = { name: "typescript:async-super", scoped: true, - text: "\n const _super = name => super[name];\n " + text: ts.helperString(__makeTemplateObject(["\n const ", " = name => super[name];"], ["\n const ", " = name => super[name];"]), "_super") }; ts.advancedAsyncSuperHelper = { name: "typescript:advanced-async-super", scoped: true, - text: "\n const _super = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);\n " + text: ts.helperString(__makeTemplateObject(["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"], ["\n const ", " = (function (geti, seti) {\n const cache = Object.create(null);\n return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n })(name => super[name], (name, value) => super[name] = value);"]), "_super") }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -59055,7 +65379,7 @@ var ts; var enabledSubstitutions; var enclosingFunctionFlags; var enclosingSuperContainerFlags = 0; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -59081,45 +65405,47 @@ var ts; return node; } switch (node.kind) { - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: return visitAwaitExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 226 /* LabeledStatement */: + case 228 /* ReturnStatement */: + return visitReturnStatement(node); + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, noDestructuringValue); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 194 /* VoidExpression */: + case 198 /* VoidExpression */: return visitVoidExpression(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return visitConstructorDeclaration(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return visitGetAccessorDeclaration(node); - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return visitSetAccessorDeclaration(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitParameter(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, noDestructuringValue); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); default: return ts.visitEachChild(node, visitor, context); @@ -59133,16 +65459,27 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (node.asteriskToken) { + var expression = ts.visitNode(node.expression, visitor, ts.isExpression); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); + } + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression + ? ts.visitNode(node.expression, visitor, ts.isExpression) + : ts.createVoidZero())), node), node); + } + return ts.visitEachChild(node, visitor, context); + } + function visitReturnStatement(node) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero())); } return ts.visitEachChild(node, visitor, context); } function visitLabeledStatement(node) { if (enclosingFunctionFlags & 2 /* Async */) { var statement = ts.unwrapInnermostStatementOfLabel(node); - if (statement.kind === 220 /* ForOfStatement */ && statement.awaitModifier) { + if (statement.kind === 225 /* ForOfStatement */ && statement.awaitModifier) { return visitForOfStatement(statement, node); } return ts.restoreEnclosingLabel(ts.visitEachChild(statement, visitor, context), node); @@ -59154,7 +65491,7 @@ var ts; var objects = []; for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { var e = elements_4[_i]; - if (e.kind === 270 /* SpreadAssignment */) { + if (e.kind === 275 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); chunkObject = undefined; @@ -59163,7 +65500,7 @@ var ts; objects.push(ts.visitNode(target, visitor, ts.isExpression)); } else { - chunkObject = ts.append(chunkObject, e.kind === 268 /* PropertyAssignment */ + chunkObject = ts.append(chunkObject, e.kind === 273 /* PropertyAssignment */ ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression)) : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike)); } @@ -59181,7 +65518,7 @@ var ts; // If the first element is a spread element, then the first argument to __assign is {}: // { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2) var objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== 182 /* ObjectLiteralExpression */) { + if (objects.length && objects[0].kind !== 186 /* ObjectLiteralExpression */) { objects.unshift(ts.createObjectLiteral()); } return createAssignHelper(context, objects); @@ -59260,6 +65597,11 @@ var ts; bodyLocation = node.statement; statementsLocation = node.statement.statements; } + else if (node.statement) { + ts.append(statements, node.statement); + bodyLocation = node.statement; + statementsLocation = node.statement; + } return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer) ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), @@ -59310,18 +65652,18 @@ var ts; ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), /*incrementor*/ undefined, - /*statement*/ convertForOfStatementHead(node, createDownlevelAwait(getValue))), + /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -59432,7 +65774,7 @@ var ts; /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset)))))); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. @@ -59457,11 +65799,11 @@ var ts; statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); } ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); - var trailingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || ts.some(statements) || ts.some(trailingStatements)) { + var leadingStatements = endLexicalEnvironment(); + if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); + ts.addStatementsAfterPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); - ts.addRange(statements, trailingStatements); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } return body; @@ -59489,15 +65831,15 @@ var ts; enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */; // We need to enable substitutions for call, property access, and element access // if we need to rewrite super calls. - context.enableSubstitution(185 /* CallExpression */); - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(184 /* ElementAccessExpression */); + context.enableSubstitution(189 /* CallExpression */); + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(188 /* ElementAccessExpression */); // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(233 /* ClassDeclaration */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(154 /* Constructor */); + context.enableEmitNotification(238 /* ClassDeclaration */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(155 /* Constructor */); } } /** @@ -59537,11 +65879,11 @@ var ts; } function substituteExpression(node) { switch (node.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return substitutePropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return substituteElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return substituteCallExpression(node); } return node; @@ -59573,11 +65915,11 @@ var ts; } function isSuperContainer(node) { var kind = node.kind; - return kind === 233 /* ClassDeclaration */ - || kind === 154 /* Constructor */ - || kind === 153 /* MethodDeclaration */ - || kind === 155 /* GetAccessor */ - || kind === 156 /* SetAccessor */; + return kind === 238 /* ClassDeclaration */ + || kind === 155 /* Constructor */ + || kind === 154 /* MethodDeclaration */ + || kind === 156 /* GetAccessor */ + || kind === 157 /* SetAccessor */; } function createSuperAccessInAsyncMethod(argumentExpression, location) { if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) { @@ -59595,7 +65937,7 @@ var ts; name: "typescript:assign", scoped: false, priority: 1, - text: "\n var __assign = (this && this.__assign) || Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };" + text: "\n var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };" }; function createAssignHelper(context, attributesSegments) { if (context.getCompilerOptions().target >= 2 /* ES2015 */) { @@ -59610,7 +65952,7 @@ var ts; var awaitHelper = { name: "typescript:await", scoped: false, - text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }" }; function createAwaitHelper(context, expression) { context.requestEmitHelper(awaitHelper); @@ -59619,7 +65961,7 @@ var ts; var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };" }; function createAsyncGeneratorHelper(context, generatorFunc) { context.requestEmitHelper(awaitHelper); @@ -59636,7 +65978,7 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n };" }; function createAsyncDelegatorHelper(context, expression, location) { context.requestEmitHelper(awaitHelper); @@ -59647,7 +65989,7 @@ var ts; var asyncValues = { name: "typescript:asyncValues", scoped: false, - text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator];\n return m ? m.call(o) : typeof __values === \"function\" ? __values(o) : o[Symbol.iterator]();\n };\n " + text: "\n var __asyncValues = (this && this.__asyncValues) || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n };" }; function createAsyncValuesHelper(context, expression, location) { context.requestEmitHelper(asyncValues); @@ -59655,16 +65997,13 @@ var ts; /*typeArguments*/ undefined, [expression]), location); } })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { function transformJsx(context) { var compilerOptions = context.getCompilerOptions(); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transform JSX-specific syntax in a SourceFile. * @@ -59689,13 +66028,13 @@ var ts; } function visitorWorker(node) { switch (node.kind) { - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ false); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ false); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ false); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -59705,17 +66044,16 @@ var ts; switch (node.kind) { case 10 /* JsxText */: return visitJsxText(node); - case 263 /* JsxExpression */: + case 268 /* JsxExpression */: return visitJsxExpression(node); - case 253 /* JsxElement */: + case 258 /* JsxElement */: return visitJsxElement(node, /*isChild*/ true); - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: return visitJsxSelfClosingElement(node, /*isChild*/ true); - case 257 /* JsxFragment */: + case 262 /* JsxFragment */: return visitJsxFragment(node, /*isChild*/ true); default: - ts.Debug.failBadSyntaxKind(node); - return undefined; + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxElement(node, isChild) { @@ -59753,14 +66091,16 @@ var ts; objectProperties = ts.createAssignHelper(context, segments); } } - var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } return element; } function visitJsxOpeningFragment(node, children, isChild, location) { - var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, ts.mapDefined(children, transformJsxChildToExpression), node, location); + var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217 + ts.mapDefined(children, transformJsxChildToExpression), node, location); if (isChild) { ts.startOnNewLine(element); } @@ -59785,14 +66125,14 @@ var ts; literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile); return ts.setTextRange(literal, node); } - else if (node.kind === 263 /* JsxExpression */) { + else if (node.kind === 268 /* JsxExpression */) { if (node.expression === undefined) { return ts.createTrue(); } return visitJsxExpression(node); } else { - ts.Debug.failBadSyntaxKind(node); + return ts.Debug.failBadSyntaxKind(node); } } function visitJsxText(node) { @@ -59879,7 +66219,7 @@ var ts; return decoded === text ? undefined : decoded; } function getTagName(node) { - if (node.kind === 253 /* JsxElement */) { + if (node.kind === 258 /* JsxElement */) { return getTagName(node.openingElement); } else { @@ -60168,14 +66508,12 @@ var ts; diams: 0x2666 }); })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { function transformES2016(context) { var hoistVariableDeclaration = context.hoistVariableDeclaration; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60187,7 +66525,7 @@ var ts; return node; } switch (node.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -60237,9 +66575,6 @@ var ts; } ts.transformES2016 = transformES2016; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -60386,7 +66721,7 @@ var ts; * be reset. */ var enabledSubstitutions; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -60422,14 +66757,14 @@ var ts; hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { - return hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ - && node.kind === 223 /* ReturnStatement */ + return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 + && node.kind === 228 /* ReturnStatement */ && !node.expression; } function shouldVisitNode(node) { return (node.transformFlags & 128 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined - || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 211 /* Block */))) + || (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 216 /* Block */))) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)) || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0; } @@ -60457,63 +66792,63 @@ var ts; switch (node.kind) { case 115 /* StaticKeyword */: return undefined; // elide static keyword - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return visitClassExpression(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return visitParameter(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return visitArrowFunction(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: return visitVariableDeclaration(node); case 71 /* Identifier */: return visitIdentifier(node); - case 231 /* VariableDeclarationList */: + case 236 /* VariableDeclarationList */: return visitVariableDeclarationList(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 211 /* Block */: + case 216 /* Block */: return visitBlock(node, /*isFunctionBody*/ false); - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: return visitBreakOrContinueStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, /*outermostLabeledStatement*/ undefined); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return visitExpressionStatement(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return visitShorthandPropertyAssignment(node); - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return visitComputedPropertyName(node); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node, /*needsDestructuringValue*/ true); case 13 /* NoSubstitutionTemplateLiteral */: case 14 /* TemplateHead */: @@ -60524,28 +66859,28 @@ var ts; return visitStringLiteral(node); case 8 /* NumericLiteral */: return visitNumericLiteral(node); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return visitTaggedTemplateExpression(node); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: return visitTemplateExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 202 /* SpreadElement */: + case 206 /* SpreadElement */: return visitSpreadElement(node); case 97 /* SuperKeyword */: return visitSuperKeyword(/*isExpressionOfCall*/ false); case 99 /* ThisKeyword */: return visitThisKeyword(node); - case 208 /* MetaProperty */: + case 212 /* MetaProperty */: return visitMetaProperty(node); - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return visitMethodDeclaration(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: return ts.visitEachChild(node, visitor, context); @@ -60562,7 +66897,7 @@ var ts; if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -60584,7 +66919,7 @@ var ts; return updated; } function returnCapturedThis(node) { - return ts.setOriginalNode(ts.createReturn(ts.createIdentifier("_this")), node); + return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node); } function visitReturnStatement(node) { if (convertedLoopState) { @@ -60632,13 +66967,14 @@ var ts; // it is possible if either // - break/continue is labeled and label is located inside the converted loop // - break/continue is non-labeled and located in non-converted loop/switch statement - var jump = node.kind === 222 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; + var jump = node.kind === 227 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */; var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) || (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump)); if (!canUseBreakOrContinue) { var labelMarker = void 0; - if (!node.label) { - if (node.kind === 222 /* BreakStatement */) { + var label = node.label; + if (!label) { + if (node.kind === 227 /* BreakStatement */) { convertedLoopState.nonLocalJumps |= 2 /* Break */; labelMarker = "break"; } @@ -60649,13 +66985,13 @@ var ts; } } else { - if (node.kind === 222 /* BreakStatement */) { - labelMarker = "break-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(node.label), labelMarker); + if (node.kind === 227 /* BreakStatement */) { + labelMarker = "break-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker); } else { - labelMarker = "continue-" + node.label.escapedText; - setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(node.label), labelMarker); + labelMarker = "continue-" + label.escapedText; + setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker); } } var returnExpression = ts.createLiteral(labelMarker); @@ -60766,12 +67102,12 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); + var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, - /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "_super")] : [], + /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], /*type*/ undefined, transformClassBody(node, extendsClauseElement)); // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier @@ -60816,7 +67152,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -60830,7 +67166,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), + statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -60874,7 +67210,7 @@ var ts; // `super` call. // If this is the case, we do not include the synthetic `...args` parameter and // will instead use the `arguments` object in ES5/3. - return ts.visitParameterList(constructor && !hasSynthesizedSuper && constructor.parameters, visitor, context) + return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } /** @@ -60910,7 +67246,7 @@ var ts; } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). - var isDerivedClass = extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; + var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 95 /* NullKeyword */; var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); // The last statement expression was replaced. Skip it. if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { @@ -60927,9 +67263,9 @@ var ts; if (isDerivedClass && superCaptureStatus !== 2 /* ReplaceWithReturn */ && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createIdentifier("_this"))); + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); } - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); if (constructor) { prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); } @@ -60949,11 +67285,11 @@ var ts; */ function isSufficientlyCoveredByReturnStatements(statement) { // A return statement is considered covered. - if (statement.kind === 223 /* ReturnStatement */) { + if (statement.kind === 228 /* ReturnStatement */) { return true; } // An if-statement with two covered branches is covered. - else if (statement.kind === 215 /* IfStatement */) { + else if (statement.kind === 220 /* IfStatement */) { var ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && @@ -60961,7 +67297,7 @@ var ts; } } // A block is covered if it has a last statement which is covered. - else if (statement.kind === 211 /* Block */) { + else if (statement.kind === 216 /* Block */) { var lastStatement = ts.lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; @@ -61019,7 +67355,7 @@ var ts; var ctorStatements = ctor.body.statements; if (statementOffset < ctorStatements.length) { firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 214 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + if (firstStatement.kind === 219 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } } @@ -61029,8 +67365,8 @@ var ts; && statementOffset === ctorStatements.length - 1 && !(ctor.transformFlags & (16384 /* ContainsLexicalThis */ | 32768 /* ContainsCapturedLexicalThis */))) { var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 198 /* BinaryExpression */ - || superCallExpression.left.kind !== 185 /* CallExpression */) { + if (superCallExpression.kind !== 202 /* BinaryExpression */ + || superCallExpression.left.kind !== 189 /* CallExpression */) { ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); } // Shift comments from the original super call to the return statement. @@ -61050,7 +67386,7 @@ var ts; return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } function createDefaultSuperCallOrThis() { - return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createIdentifier("_super"), ts.createNull()), ts.createFunctionApply(ts.createIdentifier("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); + return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis()); } /** * Visits a parameter declaration. @@ -61145,7 +67481,7 @@ var ts; /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } /** @@ -61159,7 +67495,7 @@ var ts; function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ - ts.createStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) + ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)); ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); @@ -61211,7 +67547,7 @@ var ts; var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ - ts.startOnNewLine(ts.setTextRange(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 + ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0 ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), /*location*/ parameter)) @@ -61227,7 +67563,7 @@ var ts; * @param node A node. */ function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 191 /* ArrowFunction */) { + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */ && node.kind !== 195 /* ArrowFunction */) { captureThisForNode(statements, node, ts.createThis()); } } @@ -61235,7 +67571,7 @@ var ts; enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), /*type*/ undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); @@ -61247,33 +67583,32 @@ var ts; if (hierarchyFacts & 16384 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return statements; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // Methods and accessors cannot be constructors, so 'new.target' will // always return 'undefined'. newTarget = ts.createVoidZero(); break; - case 154 /* Constructor */: + case 155 /* Constructor */: // Class constructors can only be called with `new`, so `this.constructor` // should be relatively safe to use. newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"); break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: // Functions can be called or constructed, and may have a `this` due to // being a member or when calling an imported function via `other_1.f()`. newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 93 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero()); break; default: - ts.Debug.failBadSyntaxKind(node); - break; + return ts.Debug.failBadSyntaxKind(node); } var captureNewTargetStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_newTarget", + ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); if (copyOnWrite) { @@ -61294,20 +67629,20 @@ var ts; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; switch (member.kind) { - case 210 /* SemicolonClassElement */: + case 215 /* SemicolonClassElement */: statements.push(transformSemicolonClassElementToStatement(member)); break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node)); } break; - case 154 /* Constructor */: + case 155 /* Constructor */: // Constructors are handled in visitClassExpression/visitClassDeclaration break; default: @@ -61338,7 +67673,7 @@ var ts; var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container); ts.setEmitFlags(memberFunction, 1536 /* NoComments */); ts.setSourceMapRange(memberFunction, sourceMapRange); - var statement = ts.setTextRange(ts.createStatement(ts.createAssignment(memberName, memberFunction)), + var statement = ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(memberName, memberFunction)), /*location*/ member); ts.setOriginalNode(statement, member); ts.setCommentRange(statement, commentRange); @@ -61356,7 +67691,7 @@ var ts; * @param accessors The set of related get/set accessors. */ function transformAccessorsToStatement(receiver, accessors, container) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); + var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. @@ -61377,7 +67712,7 @@ var ts; // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */); - ts.setSourceMapRange(target, firstAccessor.name); + ts.setSourceMapRange(target, firstAccessor.name); // TODO: GH#18217 var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */); ts.setSourceMapRange(propertyName, firstAccessor.name); @@ -61499,7 +67834,7 @@ var ts; : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 232 /* FunctionDeclaration */ || node.kind === 190 /* FunctionExpression */)) { + if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 237 /* FunctionDeclaration */ || node.kind === 194 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); @@ -61520,6 +67855,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; + var leadingStatements = []; var statements = []; var body = node.body; var statementOffset; @@ -61527,18 +67863,14 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false); - } - addCaptureThisForNodeIfNeeded(statements, node); - addDefaultValueAssignmentsIfNeeded(statements, node); - addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false); - // If we added any generated statements, this must be a multi-line block. - if (!multiLine && statements.length > 0) { - multiLine = true; + statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); } + addCaptureThisForNodeIfNeeded(leadingStatements, node); + addDefaultValueAssignmentsIfNeeded(leadingStatements, node); + addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -61547,7 +67879,7 @@ var ts; } } else { - ts.Debug.assert(node.kind === 191 /* ArrowFunction */); + ts.Debug.assert(node.kind === 195 /* ArrowFunction */); // To align with the old emitter, we use a synthetic end position on the location // for the statement list we synthesize when we down-level an arrow function with // an expression function body. This prevents both comments and source maps from @@ -61565,6 +67897,7 @@ var ts; var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression); ts.setTextRange(returnStatement, body); + ts.moveSyntheticComments(returnStatement, body); ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom @@ -61572,13 +67905,13 @@ var ts; closeBraceLocation = body; } var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addRange(statements, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements, lexicalEnvironment); prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); // If we added any final generated statements, this must be a multi-line block - if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) { + if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -61614,10 +67947,10 @@ var ts; function visitExpressionStatement(node) { // If we are here it is most likely because our expression is a destructuring assignment. switch (node.expression.kind) { - case 189 /* ParenthesizedExpression */: - return ts.updateStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 198 /* BinaryExpression */: - return ts.updateStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); + case 193 /* ParenthesizedExpression */: + return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); + case 202 /* BinaryExpression */: + return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } return ts.visitEachChild(node, visitor, context); } @@ -61635,9 +67968,9 @@ var ts; // expression. If we are in a state where we do not need the destructuring value, // we pass that information along to the children that care about it. switch (node.expression.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false)); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false)); } } @@ -61679,7 +68012,7 @@ var ts; } } if (assignments) { - updated = ts.setTextRange(ts.createStatement(ts.inlineExpressions(assignments)), node); + updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node); } else { // none of declarations has initializer - the entire variable statement can be deleted @@ -61710,13 +68043,12 @@ 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.last(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); if (firstDeclaration) { - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, ts.last(declarations).end)); } } return declarationList; @@ -61839,14 +68171,14 @@ var ts; } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return visitDoOrWhileStatement(node, outermostLabeledStatement); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node, outermostLabeledStatement); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node, outermostLabeledStatement); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node, outermostLabeledStatement); } } @@ -61870,11 +68202,12 @@ var ts; } function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) { var statements = []; - if (ts.isVariableDeclarationList(node.initializer)) { + var initializer = node.initializer; + if (ts.isVariableDeclarationList(initializer)) { if (node.initializer.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } - var firstOriginalDeclaration = ts.firstOrUndefined(node.initializer.declarations); + var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations); if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -61883,9 +68216,7 @@ var ts; ts.setOriginalNode(declarationList, node.initializer); // Adjust the source map range for the first declaration to align with the old // emitter. - var firstDeclaration = declarations[0]; - var lastDeclaration = ts.lastOrUndefined(declarations); - ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -61896,42 +68227,39 @@ var ts; /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), /*type*/ undefined, boundValue) - ]), ts.moveRangePos(node.initializer, -1)), node.initializer)), ts.moveRangeEnd(node.initializer, -1))); + ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1))); } } else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - var assignment = ts.createAssignment(node.initializer, boundValue); + var assignment = ts.createAssignment(initializer, boundValue); if (ts.isDestructuringAssignment(assignment)) { ts.aggregateTransformFlags(assignment); - statements.push(ts.createStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); + statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false))); } else { - assignment.end = node.initializer.end; - statements.push(ts.setTextRange(ts.createStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(node.initializer, -1))); + assignment.end = initializer.end; + statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1))); } } - var bodyLocation; - var statementsLocation; if (convertedLoopBodyStatements) { - ts.addRange(statements, convertedLoopBodyStatements); + return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements)); } else { var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock); if (ts.isBlock(statement)) { - ts.addRange(statements, statement.statements); - bodyLocation = statement; - statementsLocation = statement.statements; + return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements)); } else { statements.push(statement); + return createSyntheticBlockForConvertedStatements(statements); } } - // The old emitter does not emit source maps for the block. - // We add the location to preserve comments. - return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), - /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); + } + function createSyntheticBlockForConvertedStatements(statements) { + return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), + /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) { // The following ES6 code: @@ -62001,13 +68329,13 @@ var ts; return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ + ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([ ts.createPropertyAssignment("error", catchVariable) ]))) ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */), ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -62034,7 +68362,7 @@ var ts; && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } - if (property.name.kind === 146 /* ComputedPropertyName */) { + if (property.name.kind === 147 /* ComputedPropertyName */) { numInitialProperties = i; break; } @@ -62106,11 +68434,11 @@ var ts; var functionName = ts.createUniqueName("_loop"); var loopInitializer; switch (node.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: var initializer = node.initializer; - if (initializer && initializer.kind === 231 /* VariableDeclarationList */) { + if (initializer && initializer.kind === 236 /* VariableDeclarationList */) { loopInitializer = initializer; } break; @@ -62156,7 +68484,7 @@ var ts; if (loopOutParameters.length) { copyOutParameters(loopOutParameters, 1 /* ToOutParameter */, statements_4); } - ts.addRange(statements_4, lexicalEnvironment); + ts.addStatementsAfterPrologue(statements_4, lexicalEnvironment); loopBody = ts.createBlock(statements_4, /*multiline*/ true); } if (ts.isBlock(loopBody)) { @@ -62274,7 +68602,7 @@ var ts; function copyOutParameters(outParams, copyDirection, statements) { for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) { var outParam = outParams_1[_i]; - statements.push(ts.createStatement(copyOutParameter(outParam, copyDirection))); + statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection))); } } function generateCallToConvertedLoop(loopFunctionExpressionName, parameters, state, isAsyncBlockContainingAwait) { @@ -62291,7 +68619,7 @@ var ts; ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { - statements.push(ts.createStatement(callResult)); + statements.push(ts.createExpressionStatement(callResult)); copyOutParameters(state.loopOutParameters, 0 /* ToOriginal */, statements); } else { @@ -62390,20 +68718,20 @@ var ts; for (var i = start; i < numProperties; i++) { var property = properties[i]; switch (property.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property === accessors.firstAccessor) { - expressions.push(transformAccessorsToExpression(receiver, accessors, node, node.multiLine)); + expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine)); } break; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine)); break; - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine)); break; default: @@ -62510,18 +68838,15 @@ var ts; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; - if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { - var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = transformFunctionBody(node); - if (node.kind === 155 /* GetAccessor */) { - updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); - } - else { - updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); - } + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = node.transformFlags & (32768 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) + ? transformFunctionBody(node) + : visitFunctionBodyDownLevel(node); + if (node.kind === 156 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { - updated = ts.visitEachChild(node, visitor, context); + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; @@ -62559,7 +68884,7 @@ var ts; function visitArrayLiteralExpression(node) { if (node.transformFlags & 64 /* ES2015 */) { // We are here because we contain a SpreadElementExpression. - return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, node.multiLine, /*hasTrailingComma*/ node.elements.hasTrailingComma); + return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); } @@ -62612,11 +68937,13 @@ var ts; // We skip any outer expressions in a number of places to get to the innermost // expression, but we will restore them later to preserve comments and source maps. var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock); - // The class statements are the statements generated by visiting the first statement of the + // The class statements are the statements generated by visiting the first statement with initializer of the // body (1), while all other statements are added to remainingStatements (2) - var classStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 0, 1); - var remainingStatements = ts.visitNodes(body.statements, visitor, ts.isStatement, 1, body.statements.length - 1); - var varStatement = ts.cast(ts.firstOrUndefined(classStatements), ts.isVariableStatement); + var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; }; + var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement); + var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer); + var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); }); + var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement); // We know there is only one variable declaration here as we verified this in an // earlier call to isTypeScriptClassWrapper var variable = varStatement.declarationList.declarations[0]; @@ -62625,6 +68952,7 @@ var ts; // we see as an assignment, for example: // // (function () { + // var C_1; // var C = C_1 = (function () { // function C() { // } @@ -62633,7 +68961,6 @@ var ts; // }()); // C = C_1 = __decorate([dec], C); // return C; - // var C_1; // }()) // var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression); @@ -62656,7 +68983,7 @@ var ts; statements.push(funcStatements[classBodyStart]); classBodyStart++; // Add the class alias following the declaration. - statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { @@ -62733,7 +69060,7 @@ var ts; ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); var initializer = ts.createLogicalOr(resultingCall, actualThis); resultingCall = assignToCapturedThis - ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; } return ts.setOriginalNode(resultingCall, node); @@ -62793,7 +69120,7 @@ var ts; else { if (segments.length === 1) { var firstElement = elements[0]; - return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 181 /* ArrayLiteralExpression */ + return needsUniqueCopy && ts.isSpreadElement(firstElement) && firstElement.expression.kind !== 185 /* ArrayLiteralExpression */ ? ts.createArraySlice(segments[0]) : segments[0]; } @@ -62987,14 +69314,14 @@ var ts; */ function addTemplateSpans(expressions, node) { for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) { - var span_6 = _a[_i]; - expressions.push(ts.visitNode(span_6.expression, visitor, ts.isExpression)); + var span = _a[_i]; + expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression)); // Only emit if the literal is non-empty. // The binary '+' operator is left-associative, so the first string concatenation // with the head will force the result up to this point to be a string. // Emitting a '+ ""' has no semantic effect for middles and tails. - if (span_6.literal.text.length !== 0) { - expressions.push(ts.createLiteral(span_6.literal.text)); + if (span.literal.text.length !== 0) { + expressions.push(ts.createLiteral(span.literal.text)); } } } @@ -63004,8 +69331,8 @@ var ts; function visitSuperKeyword(isExpressionOfCall) { return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall - ? ts.createPropertyAccess(ts.createIdentifier("_super"), "prototype") - : ts.createIdentifier("_super"); + ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") + : ts.createFileLevelUniqueName("_super"); } function visitMetaProperty(node) { if (node.keywordToken === 94 /* NewKeyword */ && node.name.escapedText === "target") { @@ -63015,7 +69342,7 @@ var ts; else { hierarchyFacts |= 16384 /* NewTarget */; } - return ts.createIdentifier("_newTarget"); + return ts.createFileLevelUniqueName("_newTarget"); } return node; } @@ -63056,13 +69383,13 @@ var ts; if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) { enabledSubstitutions |= 1 /* CapturedThis */; context.enableSubstitution(99 /* ThisKeyword */); - context.enableEmitNotification(154 /* Constructor */); - context.enableEmitNotification(153 /* MethodDeclaration */); - context.enableEmitNotification(155 /* GetAccessor */); - context.enableEmitNotification(156 /* SetAccessor */); - context.enableEmitNotification(191 /* ArrowFunction */); - context.enableEmitNotification(190 /* FunctionExpression */); - context.enableEmitNotification(232 /* FunctionDeclaration */); + context.enableEmitNotification(155 /* Constructor */); + context.enableEmitNotification(154 /* MethodDeclaration */); + context.enableEmitNotification(156 /* GetAccessor */); + context.enableEmitNotification(157 /* SetAccessor */); + context.enableEmitNotification(195 /* ArrowFunction */); + context.enableEmitNotification(194 /* FunctionExpression */); + context.enableEmitNotification(237 /* FunctionDeclaration */); } } /** @@ -63102,14 +69429,13 @@ var ts; * @param node An original source tree node. */ function isNameOfDeclarationWithCollidingName(node) { - var parent = node.parent; - switch (parent.kind) { - case 180 /* BindingElement */: - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 230 /* VariableDeclaration */: - return parent.name === node - && resolver.isDeclarationWithCollidingName(parent); + switch (node.parent.kind) { + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 235 /* VariableDeclaration */: + return node.parent.name === node + && resolver.isDeclarationWithCollidingName(node.parent); } return false; } @@ -63172,7 +69498,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && hierarchyFacts & 16 /* CapturesThis */) { - return ts.setTextRange(ts.createIdentifier("_this"), node); + return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node); } return node; } @@ -63189,11 +69515,11 @@ var ts; return false; } var statement = ts.firstOrUndefined(constructor.body.statements); - if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 214 /* ExpressionStatement */) { + if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 219 /* ExpressionStatement */) { return false; } var statementExpression = statement.expression; - if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 185 /* CallExpression */) { + if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 189 /* CallExpression */) { return false; } var callTarget = statementExpression.expression; @@ -63201,7 +69527,7 @@ var ts; return false; } var callArgument = ts.singleOrUndefined(statementExpression.arguments); - if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 202 /* SpreadElement */) { + if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 206 /* SpreadElement */) { return false; } var expression = callArgument.expression; @@ -63214,7 +69540,7 @@ var ts; return ts.createCall(ts.getHelperName("__extends"), /*typeArguments*/ undefined, [ name, - ts.createIdentifier("_super") + ts.createFileLevelUniqueName("_super") ]); } function createTemplateObjectHelper(context, cooked, raw) { @@ -63229,7 +69555,7 @@ var ts; name: "typescript:extends", scoped: false, priority: 0, - text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" + text: "\n var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n }\n\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n })();" }; var templateObjectHelper = { name: "typescript:makeTemplateObject", @@ -63238,8 +69564,6 @@ var ts; text: "\n var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n };" }; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -63256,16 +69580,16 @@ var ts; if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) { previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; - context.enableEmitNotification(255 /* JsxOpeningElement */); - context.enableEmitNotification(256 /* JsxClosingElement */); - context.enableEmitNotification(254 /* JsxSelfClosingElement */); + context.enableEmitNotification(260 /* JsxOpeningElement */); + context.enableEmitNotification(261 /* JsxClosingElement */); + context.enableEmitNotification(259 /* JsxSelfClosingElement */); noSubstitution = []; } var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; - context.enableSubstitution(183 /* PropertyAccessExpression */); - context.enableSubstitution(268 /* PropertyAssignment */); - return transformSourceFile; + context.enableSubstitution(187 /* PropertyAccessExpression */); + context.enableSubstitution(273 /* PropertyAssignment */); + return ts.chainBundle(transformSourceFile); /** * Transforms an ES5 source file to ES3. * @@ -63283,9 +69607,9 @@ var ts; */ function onEmitNode(hint, node, emitCallback) { switch (node.kind) { - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: var tagName = node.tagName; noSubstitution[ts.getOriginalNodeId(tagName)] = true; break; @@ -63342,7 +69666,7 @@ var ts; */ function trySubstituteReservedName(name) { var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined); - if (token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { + if (token !== undefined && token >= 72 /* FirstReservedWord */ && token <= 107 /* LastReservedWord */) { return ts.setTextRange(ts.createLiteral(name), name); } return undefined; @@ -63350,8 +69674,6 @@ var ts; } ts.transformES5 = transformES5; })(ts || (ts = {})); -/// -/// // Transforms generator functions into a compatible ES5 representation with similar runtime // semantics. This is accomplished by first transforming the body of each generator // function into an intermediate representation that is the compiled into a JavaScript @@ -63529,6 +69851,7 @@ var ts; case 4 /* Yield */: return "yield"; case 5 /* YieldStar */: return "yield*"; case 7 /* Endfinally */: return "endfinally"; + default: return undefined; // TODO: GH#18217 } } function transformGenerators(context) { @@ -63579,7 +69902,7 @@ var ts; var exceptionBlockStack; // A stack of containing exception blocks. var currentExceptionBlock; // The current exception block. var withBlockStack; // A stack containing `with` blocks. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { return node; @@ -63618,13 +69941,13 @@ var ts; */ function visitJavaScriptInStatementContainingYield(node) { switch (node.kind) { - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); @@ -63637,24 +69960,24 @@ var ts; */ function visitJavaScriptInGeneratorFunctionBody(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return visitAccessorDeclaration(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return visitBreakStatement(node); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return visitContinueStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return visitReturnStatement(node); default: if (node.transformFlags & 16777216 /* ContainsYield */) { @@ -63675,21 +69998,21 @@ var ts; */ function visitJavaScriptContainingYield(node) { switch (node.kind) { - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return visitBinaryExpression(node); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return visitConditionalExpression(node); - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: return visitYieldExpression(node); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return visitArrayLiteralExpression(node); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return visitObjectLiteralExpression(node); - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return visitElementAccessExpression(node); - case 185 /* CallExpression */: + case 189 /* CallExpression */: return visitCallExpression(node); - case 186 /* NewExpression */: + case 190 /* NewExpression */: return visitNewExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -63702,13 +70025,12 @@ var ts; */ function visitGenerator(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return visitFunctionExpression(node); default: - ts.Debug.failBadSyntaxKind(node); - return ts.visitEachChild(node, visitor, context); + return ts.Debug.failBadSyntaxKind(node); } } /** @@ -63837,7 +70159,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -63881,7 +70203,7 @@ var ts; if (variables.length === 0) { return undefined; } - return ts.setSourceMapRange(ts.createStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); + return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node); } } /** @@ -63893,13 +70215,14 @@ var ts; * @param node The node to visit. */ function visitBinaryExpression(node) { - switch (ts.getExpressionAssociativity(node)) { + var assoc = ts.getExpressionAssociativity(node); + switch (assoc) { case 0 /* Left */: return visitLeftAssociativeBinaryExpression(node); case 1 /* Right */: return visitRightAssociativeBinaryExpression(node); default: - ts.Debug.fail("Unknown associativity."); + return ts.Debug.assertNever(assoc); } } function isCompoundAssignment(kind) { @@ -63932,7 +70255,7 @@ var ts; if (containsYield(right)) { var target = void 0; switch (left.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: // [source] // a.b = yield; // @@ -63944,7 +70267,7 @@ var ts; // _a.b = %sent%; target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: // [source] // a[b] = yield; // @@ -64068,7 +70391,7 @@ var ts; } else { if (containsYield(node) && pendingExpressions.length > 0) { - emitWorker(1 /* Statement */, [ts.createStatement(ts.inlineExpressions(pendingExpressions))]); + emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]); pendingExpressions = []; } pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression)); @@ -64221,7 +70544,7 @@ var ts; return ts.inlineExpressions(expressions); function reduceProperty(expressions, property) { if (containsYield(property) && expressions.length > 0) { - emitStatement(ts.createStatement(ts.inlineExpressions(expressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions))); expressions = []; } var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp); @@ -64320,35 +70643,35 @@ var ts; } function transformAndEmitStatementWorker(node) { switch (node.kind) { - case 211 /* Block */: + case 216 /* Block */: return transformAndEmitBlock(node); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return transformAndEmitExpressionStatement(node); - case 215 /* IfStatement */: + case 220 /* IfStatement */: return transformAndEmitIfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return transformAndEmitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return transformAndEmitWhileStatement(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return transformAndEmitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return transformAndEmitForInStatement(node); - case 221 /* ContinueStatement */: + case 226 /* ContinueStatement */: return transformAndEmitContinueStatement(node); - case 222 /* BreakStatement */: + case 227 /* BreakStatement */: return transformAndEmitBreakStatement(node); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: return transformAndEmitReturnStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return transformAndEmitWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return transformAndEmitSwitchStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return transformAndEmitLabeledStatement(node); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: return transformAndEmitThrowStatement(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return transformAndEmitTryStatement(node); default: return emitStatement(ts.visitNode(node, visitor, ts.isStatement)); @@ -64385,7 +70708,7 @@ var ts; pendingExpressions.push(transformInitializedVariable(variable)); } if (pendingExpressions.length) { - emitStatement(ts.createStatement(ts.inlineExpressions(pendingExpressions))); + emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))); variablesWritten += pendingExpressions.length; pendingExpressions = []; } @@ -64536,7 +70859,7 @@ var ts; transformAndEmitVariableDeclarationList(initializer); } else { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer)); } } markLabel(conditionLabel); @@ -64546,7 +70869,7 @@ var ts; transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); if (node.incrementor) { - emitStatement(ts.setTextRange(ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); + emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor)); } emitBreak(conditionLabel); endLoopBlock(); @@ -64607,7 +70930,7 @@ var ts; var initializer = node.initializer; hoistVariableDeclaration(keysIndex); emitAssignment(keysArray, ts.createArrayLiteral()); - emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), + emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), /*typeArguments*/ undefined, [key])))); emitAssignment(keysIndex, ts.createLiteral(0)); var conditionLabel = defineLabel(); @@ -64630,7 +70953,7 @@ var ts; emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex)); transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); - emitStatement(ts.createStatement(ts.createPostfixIncrement(keysIndex))); + emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex))); emitBreak(conditionLabel); endLoopBlock(); } @@ -64778,7 +71101,7 @@ var ts; for (var i = 0; i < numClauses; i++) { var clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === 265 /* DefaultClause */ && defaultClauseIndex === -1) { + if (clause.kind === 270 /* DefaultClause */ && defaultClauseIndex === -1) { defaultClauseIndex = i; } } @@ -64791,7 +71114,7 @@ var ts; var defaultClausesSkipped = 0; for (var i = clausesWritten; i < numClauses; i++) { var clause = caseBlock.clauses[i]; - if (clause.kind === 264 /* CaseClause */) { + if (clause.kind === 269 /* CaseClause */) { if (containsYield(clause.expression) && pendingClauses.length > 0) { break; } @@ -64907,7 +71230,7 @@ var ts; beginExceptionBlock(); transformAndEmitEmbeddedStatement(node.tryBlock); if (node.catchClause) { - beginCatchBlock(node.catchClause.variableDeclaration); + beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217 transformAndEmitEmbeddedStatement(node.catchClause.block); } if (node.finallyBlock) { @@ -64921,7 +71244,7 @@ var ts; } } function containsYield(node) { - return node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 16777216 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -65022,7 +71345,8 @@ var ts; */ function endBlock() { var block = peekBlock(); - ts.Debug.assert(block !== undefined, "beginBlock was never called."); + if (block === undefined) + return ts.Debug.fail("beginBlock was never called."); var index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -65355,7 +71679,7 @@ var ts; * @param label A label. */ function createLabel(label) { - if (label > 0) { + if (label !== undefined && label > 0) { if (labelExpressions === undefined) { labelExpressions = []; } @@ -65653,7 +71977,7 @@ var ts; // indicate entry into a protected region by pushing the label numbers // for each block in the protected region. var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel; - statements.unshift(ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), + statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), /*typeArguments*/ undefined, [ ts.createArrayLiteral([ createLabel(startLabel), @@ -65667,7 +71991,7 @@ var ts; if (markLabelEnd) { // The case clause for the last label falls through to this label, so we // add an assignment statement to reflect the change in labels. - statements.push(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); + statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1)))); } } clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || [])); @@ -65825,7 +72149,7 @@ var ts; * @param operationLocation The source map location for the operation. */ function writeAssign(left, right, operationLocation) { - writeStatement(ts.setTextRange(ts.createStatement(ts.createAssignment(left, right)), operationLocation)); + writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation)); } /** * Writes a Throw operation to the current label's statement list. @@ -65994,12 +72318,9 @@ var ts; name: "typescript:generator", scoped: false, priority: 6, - text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" + text: "\n var __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n };" }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -66022,18 +72343,18 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols. - context.enableSubstitution(198 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(196 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(197 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. - context.enableEmitNotification(272 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var currentSourceFile; // The current file. var currentModuleInfo; // The ExternalModuleInfo for the current file. var noSubstitution; // Set of nodes for which substitution rules should be ignored. var needUMDDynamicImportHelper; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -66076,7 +72397,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -66119,7 +72440,7 @@ var ts; // // define(moduleName?, ["module1", "module2"], function ... var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(define, + ts.createExpressionStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: // @@ -66170,9 +72491,9 @@ var ts; ts.createIdentifier("exports") ])) ]), - ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */) ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("define"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -66196,7 +72517,7 @@ var ts; // } // })(function ...) var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(umdHeader, + ts.createExpressionStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: // @@ -66270,12 +72591,12 @@ var ts; if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { return undefined; } - var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217 var expr = getHelperExpressionForImport(node, name); if (expr === name) { return undefined; } - return ts.createStatement(ts.createAssignment(name, expr)); + return ts.createExpressionStatement(ts.createAssignment(name, expr)); } /** * Transforms a SourceFile into an AMD or UMD module body. @@ -66299,7 +72620,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addRange(statements, endLexicalEnvironment()); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -66321,7 +72642,7 @@ var ts; */ function addExportEqualsIfNeeded(statements, emitAsReturn) { if (currentModuleInfo.exportEquals) { - var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, importCallExpressionVisitor); + var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor); if (expressionResult) { if (emitAsReturn) { var statement = ts.createReturn(expressionResult); @@ -66330,7 +72651,7 @@ var ts; statements.push(statement); } else { - var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); + var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult)); ts.setTextRange(statement, currentModuleInfo.exportEquals); ts.setEmitFlags(statement, 1536 /* NoComments */); statements.push(statement); @@ -66348,43 +72669,98 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: return visitExportDeclaration(node); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 297 /* MergeDeclarationMarker */: + case 307 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 308 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } - function importCallExpressionVisitor(node) { - // This visitor does not need to descend into the tree if there is no dynamic import, + function moduleExpressionElementVisitor(node) { + // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */)) { + if (!(node.transformFlags & 67108864 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } + else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + return visitDestructuringAssignment(node); + } else { - return ts.visitEachChild(node, importCallExpressionVisitor, context); + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); } } + function destructuringNeedsFlattening(node) { + if (ts.isObjectLiteralExpression(node)) { + for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { + var elem = _a[_i]; + switch (elem.kind) { + case 273 /* PropertyAssignment */: + if (destructuringNeedsFlattening(elem.initializer)) { + return true; + } + break; + case 274 /* ShorthandPropertyAssignment */: + if (destructuringNeedsFlattening(elem.name)) { + return true; + } + break; + case 275 /* SpreadAssignment */: + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + break; + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return false; + default: ts.Debug.assertNever(elem, "Unhandled object member kind"); + } + } + } + else if (ts.isArrayLiteralExpression(node)) { + for (var _b = 0, _c = node.elements; _b < _c.length; _b++) { + var elem = _c[_b]; + if (ts.isSpreadElement(elem)) { + if (destructuringNeedsFlattening(elem.expression)) { + return true; + } + } + else if (destructuringNeedsFlattening(elem)) { + return true; + } + } + } + else if (ts.isIdentifier(node)) { + return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0); + } + return false; + } + function visitDestructuringAssignment(node) { + if (destructuringNeedsFlattening(node.left)) { + return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions); + } + return ts.visitEachChild(node, moduleExpressionElementVisitor, context); + } function visitImportCallExpression(node) { - var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), importCallExpressionVisitor); + var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); var containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: @@ -66440,7 +72816,7 @@ var ts; ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject) ]; var body = ts.createBlock([ - ts.createStatement(ts.createCall(ts.createIdentifier("require"), + ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject])) ]); var func; @@ -66535,7 +72911,7 @@ var ts; if (moduleKind !== ts.ModuleKind.AMD) { if (!node.importClause) { // import "mod"; - return ts.setTextRange(ts.createStatement(createRequireCall(node)), node); + return ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node); } else { var variables = []; @@ -66603,7 +72979,7 @@ var ts; var statements; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(node.name, createRequireCall(node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node)); } else { statements = ts.append(statements, ts.setTextRange(ts.createVariableStatement( @@ -66616,7 +72992,7 @@ var ts; } else { if (ts.hasModifier(node, 1 /* Export */)) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node)); } } if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -66655,13 +73031,13 @@ var ts; for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { var specifier = _a[_i]; var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name); - statements.push(ts.setTextRange(ts.createStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); + statements.push(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue)), specifier)); } return ts.singleOrMany(statements); } else { // export * from "mod"; - return ts.setTextRange(ts.createStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); + return ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node); } } /** @@ -66678,10 +73054,10 @@ var ts; if (original && hasAssociatedEndOfDeclarationMarker(original)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); - deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } else { - statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, importCallExpressionVisitor), /*location*/ node, /*allowComments*/ true); + statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true); } return ts.singleOrMany(statements); } @@ -66695,13 +73071,13 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.parameters, importCallExpressionVisitor), - /*type*/ undefined, ts.visitEachChild(node.body, importCallExpressionVisitor, context)), + /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), + /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), /*location*/ node), /*original*/ node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66723,10 +73099,10 @@ var ts; if (ts.hasModifier(node, 1 /* Export */)) { statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration( /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), - /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, importCallExpressionVisitor), ts.visitNodes(node.members, importCallExpressionVisitor)), node), node)); + /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node)); } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66767,11 +73143,11 @@ var ts; statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables))); } if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); } } else { - statements = ts.append(statements, ts.visitEachChild(node, importCallExpressionVisitor, context)); + statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context)); } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -66783,6 +73159,21 @@ var ts; } return ts.singleOrMany(statements); } + function createAllExportExpressions(name, value, location) { + var exportedNames = getExports(name); + if (exportedNames) { + // For each additional export of the declaration, apply an export assignment. + var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value); + for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { + var exportName = exportedNames_1[_i]; + // Mark the node to prevent triggering substitution. + ts.setEmitFlags(expression, 4 /* NoSubstitution */); + expression = createExportExpression(exportName, expression, /*location*/ location); + } + return expression; + } + return ts.createAssignment(name, value); + } /** * Transforms an exported variable with an initializer into an expression. * @@ -66790,13 +73181,13 @@ var ts; */ function transformInitializedVariable(node) { if (ts.isBindingPattern(node.name)) { - return ts.flattenDestructuringAssignment(ts.visitNode(node, importCallExpressionVisitor), + return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), /*visitor*/ undefined, context, 0 /* All */, - /*needsValue*/ false, createExportExpression); + /*needsValue*/ false, createAllExportExpressions); } else { return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), - /*location*/ node.name), ts.visitNode(node.initializer, importCallExpressionVisitor)); + /*location*/ node.name), ts.visitNode(node.initializer, moduleExpressionElementVisitor)); } } /** @@ -66813,7 +73204,7 @@ var ts; // // To balance the declaration, add the exports of the elided variable // statement. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 212 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); } @@ -66868,10 +73259,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 245 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -67001,10 +73392,10 @@ var ts; function createUnderscoreUnderscoreESModule() { var statement; if (languageVersion === 0 /* ES3 */) { - statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); + statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true))); } else { - statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), /*typeArguments*/ undefined, [ ts.createIdentifier("exports"), ts.createLiteral("__esModule"), @@ -67025,7 +73416,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, location, allowComments) { - var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); + var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -67070,7 +73461,7 @@ var ts; * @param emit A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { currentSourceFile = node; currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)]; noSubstitution = []; @@ -67134,10 +73525,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 197 /* PostfixUnaryExpression */: - case 196 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -67158,7 +73549,7 @@ var ts; } if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) { var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node)); - if (exportContainer && exportContainer.kind === 272 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), /*location*/ node); } @@ -67200,8 +73591,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) { - var exportName = exportedNames_1[_i]; + for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { + var exportName = exportedNames_2[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression, /*location*/ node); @@ -67233,12 +73624,12 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 197 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 43 /* PlusPlusToken */ ? 59 /* PlusEqualsToken */ : 60 /* MinusEqualsToken */), ts.createLiteral(1)), /*location*/ node) : node; - for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) { - var exportName = exportedNames_2[_i]; + for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { + var exportName = exportedNames_3[_i]; // Mark the node to prevent triggering this rule again. noSubstitution[ts.getNodeId(expression)] = true; expression = createExportExpression(exportName, expression); @@ -67269,7 +73660,7 @@ var ts; var exportStarHelper = { name: "typescript:export-star", scoped: true, - text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }\n " + text: "\n function __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n }" }; function createExportStarHelper(context, module) { var compilerOptions = context.getCompilerOptions(); @@ -67296,9 +73687,6 @@ var ts; text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};" }; })(ts || (ts = {})); -/// -/// -/// /*@internal*/ var ts; (function (ts) { @@ -67312,11 +73700,11 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. - context.enableSubstitution(269 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols - context.enableSubstitution(198 /* BinaryExpression */); // Substitutes assignments to exported symbols. - context.enableSubstitution(196 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableSubstitution(197 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. - context.enableEmitNotification(272 /* SourceFile */); // Restore state when substituting nodes in a file. + context.enableSubstitution(274 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols + context.enableSubstitution(202 /* BinaryExpression */); // Substitutes assignments to exported symbols. + context.enableSubstitution(200 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableSubstitution(201 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. + context.enableEmitNotification(277 /* SourceFile */); // Restore state when substituting nodes in a file. var moduleInfoMap = []; // The ExternalModuleInfo for each file. var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found. var exportFunctionsMap = []; // The export function associated with a source file. @@ -67328,7 +73716,7 @@ var ts; var hoistedStatements; var enclosingBlockScopedContainer; var noSubstitution; // Set of nodes for which substitution rules should be ignored. - return transformSourceFile; + return ts.chainBundle(transformSourceFile); /** * Transforms the module aspects of a SourceFile. * @@ -67378,7 +73766,7 @@ var ts; var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; })); var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ - ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), + ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, moduleBodyFunction] : [dependencies, moduleBodyFunction])) @@ -67501,8 +73889,8 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addRange(statements, endLexicalEnvironment()); - var exportStarFunction = addExportStarIfNeeded(statements); + ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), ts.createPropertyAssignment("execute", ts.createFunctionExpression( @@ -67537,7 +73925,7 @@ var ts; var hasExportDeclarationWithExportClause = false; for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) { var externalImport = _a[_i]; - if (externalImport.kind === 248 /* ExportDeclaration */ && externalImport.exportClause) { + if (externalImport.kind === 253 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; } @@ -67562,7 +73950,7 @@ var ts; } for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) { var externalImport = _e[_d]; - if (externalImport.kind !== 248 /* ExportDeclaration */) { + if (externalImport.kind !== 253 /* ExportDeclaration */) { continue; } if (!externalImport.exportClause) { @@ -67616,9 +74004,9 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */) ])), - ts.createStatement(ts.createCall(exportFunction, + ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exports])) ], /*multiline*/ true)); } @@ -67631,28 +74019,28 @@ var ts; function createSettersArray(exportStarFunction, dependencyGroups) { var setters = []; for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) { - var group_2 = dependencyGroups_1[_i]; + var group_1 = dependencyGroups_1[_i]; // derive a unique name for parameter from the first named entry in the group - var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); + var localName = ts.forEach(group_1.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); }); var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName(""); var statements = []; - for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) { + for (var _a = 0, _b = group_1.externalImports; _a < _b.length; _a++) { var entry = _b[_a]; - var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); + var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217 switch (entry.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: if (!entry.importClause) { // 'import "..."' case // module is imported only for side-effects, no emit required break; } // falls through - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: ts.Debug.assert(importVariableName !== undefined); // save import into the local - statements.push(ts.createStatement(ts.createAssignment(importVariableName, parameterName))); + statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName))); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: ts.Debug.assert(importVariableName !== undefined); if (entry.exportClause) { // export {a, b as c} from 'foo' @@ -67668,7 +74056,7 @@ var ts; var e = _d[_c]; properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name))))); } - statements.push(ts.createStatement(ts.createCall(exportFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)]))); } else { @@ -67677,7 +74065,7 @@ var ts; // emit as: // // exportStar(foo_1_1); - statements.push(ts.createStatement(ts.createCall(exportStarFunction, + statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, /*typeArguments*/ undefined, [parameterName]))); } break; @@ -67702,15 +74090,15 @@ var ts; */ function sourceElementVisitor(node) { switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: return visitImportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return visitImportEqualsDeclaration(node); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // ExportDeclarations are elided as they are handled via // `appendExportsOfDeclaration`. return undefined; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); default: return nestedElementVisitor(node); @@ -67724,7 +74112,7 @@ var ts; function visitImportDeclaration(node) { var statements; if (node.importClause) { - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 } if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -67744,7 +74132,7 @@ var ts; function visitImportEqualsDeclaration(node) { ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); var statements; - hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); + hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217 if (hasAssociatedEndOfDeclarationMarker(node)) { // Defer exports until we encounter an EndOfDeclarationMarker node var id = ts.getOriginalNodeId(node); @@ -67811,7 +74199,7 @@ var ts; var name = ts.getLocalName(node); hoistVariableDeclaration(name); // Rewrite the class declaration into an assignment of a class expression. - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression( /*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node)); if (hasAssociatedEndOfDeclarationMarker(node)) { @@ -67848,7 +74236,7 @@ var ts; } var statements; if (expressions) { - statements = ts.append(statements, ts.setTextRange(ts.createStatement(ts.inlineExpressions(expressions)), node)); + statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node)); } if (isMarkedDeclaration) { // Defer exports until we encounter an EndOfDeclarationMarker node @@ -67886,7 +74274,7 @@ var ts; function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 - && (enclosingBlockScopedContainer.kind === 272 /* SourceFile */ + && (enclosingBlockScopedContainer.kind === 277 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } /** @@ -67950,7 +74338,7 @@ var ts; // // To balance the declaration, we defer the exports of the elided variable // statement until we visit this declaration's `EndOfDeclarationMarker`. - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 212 /* VariableStatement */) { + if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 217 /* VariableStatement */) { var id = ts.getOriginalNodeId(node); var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */); deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); @@ -67981,6 +74369,12 @@ var ts; delete deferredExports[id]; return ts.append(statements, node); } + else { + var original = ts.getOriginalNode(node); + if (ts.isModuleOrEnumDeclaration(original)) { + return ts.append(appendExportsOfDeclaration(statements, original), node); + } + } return node; } /** @@ -68006,10 +74400,10 @@ var ts; var namedBindings = importClause.namedBindings; if (namedBindings) { switch (namedBindings.kind) { - case 244 /* NamespaceImport */: + case 249 /* NamespaceImport */: statements = appendExportsOfDeclaration(statements, namedBindings); break; - case 245 /* NamedImports */: + case 250 /* NamedImports */: for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { var importBinding = _a[_i]; statements = appendExportsOfDeclaration(statements, importBinding); @@ -68161,7 +74555,7 @@ var ts; * @param allowComments An optional value indicating whether to emit comments for the statement. */ function createExportStatement(name, value, allowComments) { - var statement = ts.createStatement(createExportExpression(name, value)); + var statement = ts.createExpressionStatement(createExportExpression(name, value)); ts.startOnNewLine(statement); if (!allowComments) { ts.setEmitFlags(statement, 1536 /* NoComments */); @@ -68189,43 +74583,43 @@ var ts; */ function nestedElementVisitor(node) { switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: return visitVariableStatement(node); - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: return visitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: return visitClassDeclaration(node); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return visitForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: return visitForInStatement(node); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: return visitForOfStatement(node); - case 216 /* DoStatement */: + case 221 /* DoStatement */: return visitDoStatement(node); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: return visitWhileStatement(node); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: return visitLabeledStatement(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: return visitWithStatement(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return visitSwitchStatement(node); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return visitCaseBlock(node); - case 264 /* CaseClause */: + case 269 /* CaseClause */: return visitCaseClause(node); - case 265 /* DefaultClause */: + case 270 /* DefaultClause */: return visitDefaultClause(node); - case 228 /* TryStatement */: + case 233 /* TryStatement */: return visitTryStatement(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return visitCatchClause(node); - case 211 /* Block */: + case 216 /* Block */: return visitBlock(node); - case 297 /* MergeDeclarationMarker */: + case 307 /* MergeDeclarationMarker */: return visitMergeDeclarationMarker(node); - case 298 /* EndOfDeclarationMarker */: + case 308 /* EndOfDeclarationMarker */: return visitEndOfDeclarationMarker(node); default: return destructuringAndImportCallVisitor(node); @@ -68239,7 +74633,7 @@ var ts; function visitForStatement(node) { var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer; enclosingBlockScopedContainer = node; - node = ts.updateFor(node, visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); + node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement)); enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer; return node; } @@ -68283,9 +74677,6 @@ var ts; * @param node The node to visit. */ function visitForInitializer(node) { - if (!node) { - return node; - } if (shouldHoistForInitializer(node)) { var expressions = void 0; for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) { @@ -68411,7 +74802,7 @@ var ts; */ function destructuringAndImportCallVisitor(node) { if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 198 /* BinaryExpression */) { + && node.kind === 202 /* BinaryExpression */) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { @@ -68476,7 +74867,7 @@ var ts; } else if (ts.isIdentifier(node)) { var container = resolver.getReferencedExportContainer(node); - return container !== undefined && container.kind === 272 /* SourceFile */; + return container !== undefined && container.kind === 277 /* SourceFile */; } else { return false; @@ -68509,7 +74900,7 @@ var ts; * @param emitCallback A callback used to emit the node in the printer. */ function onEmitNode(hint, node, emitCallback) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { var id = ts.getOriginalNodeId(node); currentSourceFile = node; moduleInfo = moduleInfoMap[id]; @@ -68557,7 +74948,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 269 /* ShorthandPropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -68593,10 +74984,10 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return substituteExpressionIdentifier(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return substituteBinaryExpression(node); - case 196 /* PrefixUnaryExpression */: - case 197 /* PostfixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: return substituteUnaryExpression(node); } return node; @@ -68658,8 +75049,8 @@ var ts; if (exportedNames) { // For each additional export of the declaration, apply an export assignment. var expression = node; - for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) { - var exportName = exportedNames_3[_i]; + for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { + var exportName = exportedNames_4[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } return expression; @@ -68689,14 +75080,14 @@ var ts; && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) { var exportedNames = getExports(node.operand); if (exportedNames) { - var expression = node.kind === 197 /* PostfixUnaryExpression */ + var expression = node.kind === 201 /* PostfixUnaryExpression */ ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node) : node; - for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) { - var exportName = exportedNames_4[_i]; + for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) { + var exportName = exportedNames_5[_i]; expression = createExportExpression(exportName, preventSubstitution(expression)); } - if (node.kind === 197 /* PostfixUnaryExpression */) { + if (node.kind === 201 /* PostfixUnaryExpression */) { expression = node.operator === 43 /* PlusPlusToken */ ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1)) : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1)); @@ -68718,7 +75109,7 @@ var ts; || resolver.getReferencedValueDeclaration(name); if (valueDeclaration) { var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false); - if (exportContainer && exportContainer.kind === 272 /* SourceFile */) { + if (exportContainer && exportContainer.kind === 277 /* SourceFile */) { exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration)); } exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]); @@ -68748,8 +75139,6 @@ var ts; } ts.transformSystemModule = transformSystemModule; })(ts || (ts = {})); -/// -/// /*@internal*/ var ts; (function (ts) { @@ -68759,10 +75148,10 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; - context.enableEmitNotification(272 /* SourceFile */); + context.enableEmitNotification(277 /* SourceFile */); context.enableSubstitution(71 /* Identifier */); var currentSourceFile; - return transformSourceFile; + return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { return node; @@ -68788,10 +75177,10 @@ var ts; } function visitor(node) { switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // Elide `import=` as it is not legal with --module ES6 return undefined; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: return visitExportAssignment(node); } return node; @@ -68848,19 +75237,1496 @@ var ts; } ts.transformES2015Module = transformES2015Module; })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + function canProduceDiagnostics(node) { + return ts.isVariableDeclaration(node) || + ts.isPropertyDeclaration(node) || + ts.isPropertySignature(node) || + ts.isBindingElement(node) || + ts.isSetAccessor(node) || + ts.isGetAccessor(node) || + ts.isConstructSignatureDeclaration(node) || + ts.isCallSignatureDeclaration(node) || + ts.isMethodDeclaration(node) || + ts.isMethodSignature(node) || + ts.isFunctionDeclaration(node) || + ts.isParameter(node) || + ts.isTypeParameterDeclaration(node) || + ts.isExpressionWithTypeArguments(node) || + ts.isImportEqualsDeclaration(node) || + ts.isTypeAliasDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isIndexSignatureDeclaration(node); + } + ts.canProduceDiagnostics = canProduceDiagnostics; + function createGetSymbolAccessibilityDiagnosticForNodeName(node) { + if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + function getMethodNameVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName; + function createGetSymbolAccessibilityDiagnosticForNode(node) { + if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (ts.isParameter(node)) { + if (ts.isParameterPropertyDeclaration(node) && ts.hasModifier(node.parent, 8 /* Private */)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (ts.isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (ts.isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (ts.isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (ts.isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]); + } + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === 152 /* PropertyDeclaration */ || node.kind === 151 /* PropertySignature */ || + (node.kind === 149 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (ts.hasModifier(node, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 238 /* ClassDeclaration */ || node.kind === 149 /* Parameter */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + if (node.kind === 157 /* SetAccessor */) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name, + typeName: node.name + }; + } + function getReturnTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 159 /* ConstructSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 158 /* CallSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 160 /* IndexSignature */: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node, 32 /* Static */)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 238 /* ClassDeclaration */) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 237 /* FunctionDeclaration */: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + return ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { + var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { + switch (node.parent.kind) { + case 155 /* Constructor */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + case 159 /* ConstructSignature */: + case 164 /* ConstructorType */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + case 158 /* CallSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + case 160 /* IndexSignature */: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + case 237 /* FunctionDeclaration */: + case 163 /* FunctionType */: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + default: + return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]); + } + } + function getTypeParameterConstraintVisibilityError() { + // Type parameter constraints are named by user so we should always be able to name it + var diagnosticMessage; + switch (node.parent.kind) { + case 238 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 239 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 159 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 158 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + if (ts.hasModifier(node.parent, 32 /* Static */)) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 237 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + case 240 /* TypeAliasDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + default: + return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + function getHeritageClauseVisibilityError() { + var diagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === 238 /* ClassDeclaration */) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = node.parent.token === 108 /* ImplementsKeyword */ ? + ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: ts.getNameOfDeclaration(node.parent.parent) + }; + } + function getImportEntityNameVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + function getTypeAliasDeclarationVisibilityError() { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode; +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getDeclarationDiagnostics(host, resolver, file) { + if (file && ts.isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + var compilerOptions = host.getCompilerOptions(); + var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + 4096 /* UseTypeOfFunction */ | + 8 /* UseStructuralFallback */ | + 524288 /* AllowEmptyTuple */ | + 4 /* GenerateNamesForShadowedTypeParams */ | + 1 /* NoTruncation */; + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + function transformDeclarations(context) { + var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); }; + var getSymbolAccessibilityDiagnostic = throwDiagnostic; + var needsDeclare = true; + var isBundledEmit = false; + var resultHasExternalModuleIndicator = false; + var needsScopeFixMarker = false; + var resultHasScopeMarker = false; + var enclosingDeclaration; + var necessaryTypeRefernces; + var lateMarkedStatements; + var lateStatementReplacementMap; + var suppressNewDiagnosticContexts; + var host = context.getEmitHost(); + var symbolTracker = { + trackSymbol: trackSymbol, + reportInaccessibleThisError: reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression, + moduleResolverHost: host, + trackReferencedAmbientModule: trackReferencedAmbientModule, + }; + var errorNameNode; + var currentSourceFile; + var refs; + var resolver = context.getEmitResolver(); + var options = context.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(options); + var noResolve = options.noResolve, stripInternal = options.stripInternal; + return transformRoot; + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || ts.createMap(); + for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { + var ref = typeReferenceDirectives_2[_i]; + necessaryTypeRefernces.set(ref, true); + } + } + function trackReferencedAmbientModule(node, symbol) { + // If it is visible via `// `, then we should just use that + var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */); + if (ts.length(directives)) { + return recordTypeReferenceDirectivesIfNecessary(directives); + } + // Otherwise we should emit a path-based reference + var container = ts.getSourceFileOfNode(node); + refs.set("" + ts.getOriginalNodeId(container), container); + } + function handleSymbolAccessibilityError(symbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!lateMarkedStatements) { + lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) { + var ref = _a[_i]; + ts.pushIfUnique(lateMarkedStatements, ref); + } + } + } + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + if (symbol.flags & 262144 /* TypeParameter */) + return; + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + function reportPrivateInBaseOfClassExpression(propertyName) { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); + } + } + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); + } + } + function transformRoot(node) { + if (node.kind === 277 /* SourceFile */ && (node.isDeclarationFile || ts.isSourceFileJavaScript(node))) { + return node; + } + if (node.kind === 278 /* Bundle */) { + isBundledEmit = true; + var refs_1 = ts.createMap(); + var hasNoDefaultLib_1 = false; + var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) { + if (sourceFile.isDeclarationFile || ts.isSourceFileJavaScript(sourceFile)) + return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217 + hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib; + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + lateMarkedStatements = undefined; + suppressNewDiagnosticContexts = false; + lateStatementReplacementMap = ts.createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + collectReferences(sourceFile, refs_1); + if (ts.isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + var statements_5 = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(124 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements_5)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + return newFile; + } + needsDeclare = true; + var updated = ts.visitNodes(sourceFile.statements, visitDeclarationStatements); + return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []); + }), ts.mapDefined(node.prepends, function (prepend) { + if (prepend.kind === 280 /* InputFiles */) { + return ts.createUnparsedSourceFile(prepend.declarationText, prepend.declarationMapPath, prepend.declarationMapText); + } + })); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + bundle.hasNoDefaultLib = hasNoDefaultLib_1; + var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1); + refs_1.forEach(referenceVisitor_1); + return bundle; + } + // Single source file + needsDeclare = true; + needsScopeFixMarker = false; + resultHasScopeMarker = false; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + lateMarkedStatements = undefined; + lateStatementReplacementMap = ts.createMap(); + necessaryTypeRefernces = undefined; + refs = collectReferences(currentSourceFile, ts.createMap()); + var references = []; + var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + var referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + var statements = ts.visitNodes(node.statements, visitDeclarationStatements); + var combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements); + refs.forEach(referenceVisitor); + var emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); + if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) { + combinedStatements = ts.setTextRange(ts.createNodeArray(combinedStatements.concat([ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createNamedExports([]), /*moduleSpecifier*/ undefined)])), combinedStatements); + } + var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib); + return updated; + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? ts.mapDefined(ts.arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + function getFileReferenceForTypeName(typeName) { + // Elide type references for which we have imports + if (emittedImports) { + for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) { + var importStatement = emittedImports_1[_i]; + if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) { + var expr = importStatement.moduleReference.expression; + if (ts.isStringLiteralLike(expr) && expr.text === typeName) { + return undefined; + } + } + else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) { + return undefined; + } + } + } + return { fileName: typeName, pos: -1, end: -1 }; + } + function mapReferencesIntoArray(references, outputFilePath) { + return function (file) { + var declFileName; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && ts.contains(node.sourceFiles, file)) + return; // Omit references to files which are being merged + var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + if (declFileName) { + var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false); + if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName: fileName }); + } + }; + } + } + function collectReferences(sourceFile, ret) { + if (noResolve || ts.isSourceFileJavaScript(sourceFile)) + return ret; + ts.forEach(sourceFile.referencedFiles, function (f) { + var elem = ts.tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + ts.getOriginalNodeId(elem), elem); + } + }); + return ret; + } + function filterBindingPatternInitializers(name) { + if (name.kind === 71 /* Identifier */) { + return name; + } + else { + if (name.kind === 183 /* ArrayBindingPattern */) { + return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + else { + return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement)); + } + } + function visitBindingElement(elem) { + if (elem.kind === 208 /* OmittedExpression */) { + return elem; + } + return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + function ensureParameter(p, modifierMask) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p); + } + var newParam = ts.updateParameter(p, + /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.createToken(55 /* QuestionToken */)) : undefined, ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p)); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + function shouldPrintWithInitializer(node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe + } + function ensureNoInitializer(node) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(ts.getParseTreeNode(node)); // TODO: Make safe + } + return undefined; + } + function ensureType(node, type, ignorePrivate) { + if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + var shouldUseResolverType = node.kind === 149 /* Parameter */ && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return ts.visitNode(type, visitDeclarationSubtree); + } + if (!ts.getParseTreeNode(node)) { + return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + if (node.kind === 157 /* SetAccessor */) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + errorNameNode = node.name; + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === 235 /* VariableDeclaration */ || node.kind === 184 /* BindingElement */) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === 149 /* Parameter */ + || node.kind === 152 /* PropertyDeclaration */ + || node.kind === 151 /* PropertySignature */) { + if (!node.initializer) + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + function cleanup(returnValue) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || ts.createKeywordTypeNode(119 /* AnyKeyword */); + } + } + function isDeclarationAndNotVisible(node) { + node = ts.getParseTreeNode(node); + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case 235 /* VariableDeclaration */: + return !getBindingNameVisible(node); + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + return false; + } + return false; + } + function getBindingNameVisible(elem) { + if (ts.isOmittedExpression(elem)) { + return false; + } + if (ts.isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return ts.some(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + function updateParamsList(node, params, modifierMask) { + if (ts.hasModifier(node, 8 /* Private */)) { + return undefined; // TODO: GH#18217 + } + var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); }); + if (!newParams) { + return undefined; // TODO: GH#18217 + } + return ts.createNodeArray(newParams, params.hasTrailingComma); + } + function ensureTypeParams(node, params) { + return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree); + } + function isEnclosingDeclaration(node) { + return ts.isSourceFile(node) + || ts.isTypeAliasDeclaration(node) + || ts.isModuleDeclaration(node) + || ts.isClassDeclaration(node) + || ts.isInterfaceDeclaration(node) + || ts.isFunctionLike(node) + || ts.isIndexSignatureDeclaration(node) + || ts.isMappedTypeNode(node); + } + function checkEntityNameVisibility(entityName, enclosingDeclaration) { + var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + function preserveJsDoc(updated, original) { + if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return ts.setCommentRange(updated, ts.getCommentRange(original)); + } + function rewriteModuleSpecifier(parent, input) { + if (!input) + return undefined; // TODO: GH#18217 + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 242 /* ModuleDeclaration */ && parent.kind !== 181 /* ImportType */); + if (input.kind === 9 /* StringLiteral */ && isBundledEmit) { + var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return ts.createLiteral(newName); + } + } + return input; + } + function transformImportEqualsDeclaration(decl) { + if (!resolver.isDeclarationVisible(decl)) + return; + if (decl.moduleReference.kind === 257 /* ExternalModuleReference */) { + // Rewrite external module names if necessary + var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl); + return ts.updateImportEqualsDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier))); + } + else { + var oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + function transformImportDeclaration(decl) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // The `importClause` visibility corresponds to the default's visibility. + var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, + /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === 249 /* NamespaceImport */) { + // Namespace import (optionally with visible default) + var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; }); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return ts.updateImportDeclaration(decl, + /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + // Nothing visible + } + function transformAndReplaceLatePaintedStatements(statements) { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + while (ts.length(lateMarkedStatements)) { + var i = lateMarkedStatements.shift(); + if (!ts.isLateVisibilityPaintedStatement(i)) { + return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); + } + var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); + } + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); + function visitLateVisibilityMarkedStatements(statement) { + if (ts.isLateVisibilityPaintedStatement(statement)) { + var key = "" + ts.getOriginalNodeId(statement); + if (lateStatementReplacementMap.has(key)) { + var result = lateStatementReplacementMap.get(key); + lateStatementReplacementMap.delete(key); + if (result && ts.isSourceFile(statement.parent)) { + if (ts.isArray(result) ? ts.some(result, needsScopeMarker) : needsScopeMarker(result)) { + // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier + needsScopeFixMarker = true; + } + if (ts.isArray(result) ? ts.some(result, isExternalModuleIndicator) : isExternalModuleIndicator(result)) { + resultHasExternalModuleIndicator = true; + } + } + return result; + } + } + return statement; + } + } + function isExternalModuleIndicator(result) { + // Exported top-level member indicates moduleness + return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */); + } + function needsScopeMarker(result) { + return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result); + } + function visitDeclarationSubtree(input) { + if (shouldStripInternal(input)) + return; + if (ts.isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) + return; + if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) { + return; + } + } + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + // Elide semicolon class statements + if (ts.isSemicolonClassElement(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var oldDiag = getSymbolAccessibilityDiagnostic; + // Emit methods which are private as properties with no type information + if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) { + if (ts.hasModifier(input, 8 /* Private */)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) + return; // Elide all but the first overload + return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + if (ts.isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + var oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 166 /* TypeLiteral */ || input.kind === 179 /* MappedType */) && input.parent.kind !== 240 /* TypeAliasDeclaration */); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + if (isProcessedComponent(input)) { + switch (input.kind) { + case 209 /* ExpressionWithTypeArguments */: { + if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case 162 /* TypeReference */: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + var node = ts.visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments))); + } + case 159 /* ConstructSignature */: + return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + case 155 /* Constructor */: { + var isPrivate = ts.hasModifier(input, 8 /* Private */); + // A constructor declaration may not have a type annotation + var ctor = ts.createSignatureDeclaration(155 /* Constructor */, isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + // TODO: GH#18217 + isPrivate ? undefined : updateParamsList(input, input.parameters, 0 /* None */), + /*type*/ undefined); + ctor.modifiers = ts.createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case 154 /* MethodDeclaration */: { + var sig = ts.createSignatureDeclaration(153 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)); + sig.name = input.name; + sig.modifiers = ts.createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case 156 /* GetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 157 /* SetAccessor */: { + var newNode = ensureAccessor(input); + return cleanup(newNode); + } + case 152 /* PropertyDeclaration */: + return cleanup(ts.updateProperty(input, + /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 151 /* PropertySignature */: + return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, !ts.hasModifier(input, 8 /* Private */) ? ensureType(input, input.type) : undefined, ensureNoInitializer(input))); + case 153 /* MethodSignature */: { + return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken)); + } + case 158 /* CallSignature */: { + return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type))); + } + case 160 /* IndexSignature */: { + return cleanup(ts.updateIndexSignature(input, + /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(119 /* AnyKeyword */))); + } + case 235 /* VariableDeclaration */: { + if (ts.isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(ts.updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case 148 /* TypeParameter */: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + } + case 173 /* ConditionalType */: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree); + var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree); + var oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case 163 /* FunctionType */: { + return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 164 /* ConstructorType */: { + return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree))); + } + case 181 /* ImportType */: { + if (!ts.isLiteralImportTypeNode(input)) + return cleanup(input); + return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf)); + } + default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]); + } + } + return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context)); + function cleanup(returnValue) { + if (returnValue && canProdiceDiagnostic && ts.hasDynamicName(input)) { + checkName(input); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 154 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); + } + function visitDeclarationStatements(input) { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 253 /* ExportDeclaration */: { + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return ts.updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case 252 /* ExportAssignment */: { + // Always visible if the parent node isn't dropped for being not visible + if (ts.isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + resultHasScopeMarker = true; + } + if (input.expression.kind === 71 /* Identifier */) { + return input; + } + else { + var newId = ts.createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); }; + var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + } + var result = transformTopLevelDeclaration(input); + // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass + lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result); + return input; + } + function transformTopLevelDeclaration(input, isPrivate) { + if (shouldStripInternal(input)) + return; + switch (input.kind) { + case 246 /* ImportEqualsDeclaration */: { + return transformImportEqualsDeclaration(input); + } + case 247 /* ImportDeclaration */: { + return transformImportDeclaration(input); + } + } + if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input)) + return; + // Elide implementation signatures from overload sets + if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input)) + return; + var previousEnclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input; + } + var canProdiceDiagnostic = ts.canProduceDiagnostics(input); + var oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input); + } + var previousNeedsDeclare = needsDeclare; + switch (input.kind) { + case 240 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(ts.updateTypeAliasDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode))); + case 239 /* InterfaceDeclaration */: { + return cleanup(ts.updateInterfaceDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree))); + } + case 237 /* FunctionDeclaration */: { + // Generators lose their generator-ness, excepting their return type + return cleanup(ts.updateFunctionDeclaration(input, + /*decorators*/ undefined, ensureModifiers(input, isPrivate), + /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), + /*body*/ undefined)); + } + case 242 /* ModuleDeclaration */: { + needsDeclare = false; + var inner = input.body; + if (inner && inner.kind === 243 /* ModuleBlock */) { + var statements = ts.visitNodes(inner.statements, visitDeclarationStatements); + var body = ts.updateModuleBlock(inner, transformAndReplaceLatePaintedStatements(statements)); + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body)); + } + else { + needsDeclare = previousNeedsDeclare; + var mods = ensureModifiers(input, isPrivate); + needsDeclare = false; + ts.visitNode(inner, visitDeclarationStatements); + // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done) + var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217 + var body = lateStatementReplacementMap.get(id); + lateStatementReplacementMap.delete(id); + return cleanup(ts.updateModuleDeclaration(input, + /*decorators*/ undefined, mods, input.name, body)); + } + } + case 238 /* ClassDeclaration */: { + var modifiers = ts.createNodeArray(ensureModifiers(input, isPrivate)); + var typeParameters = ensureTypeParams(input, input.typeParameters); + var ctor = ts.getFirstConstructorWithBody(input); + var parameterProperties = void 0; + if (ctor) { + var oldDiag_1 = getSymbolAccessibilityDiagnostic; + parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) { + if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) + return; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === 71 /* Identifier */) { + return preserveJsDoc(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + function walkBindingPattern(pattern) { + var elems; + for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { + var elem = _a[_i]; + if (ts.isOmittedExpression(elem)) + continue; + if (ts.isBindingPattern(elem.name)) { + elems = ts.concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(ts.createProperty( + /*decorators*/ undefined, ensureModifiers(param), elem.name, + /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined)); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag_1; + } + var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); + var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); + if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 95 /* NullKeyword */) { + // We must add a temporary declaration for the extends clause expression + var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + getSymbolAccessibilityDiagnostic = function () { return ({ + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause_1, + typeName: input.name + }); }; + var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(124 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */)); + var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) { + if (clause.token === 85 /* ExtendsKeyword */) { + var oldDiag_2 = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); })); + getSymbolAccessibilityDiagnostic = oldDiag_2; + return newClause; + } + return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 95 /* NullKeyword */; })), visitDeclarationSubtree)); + })); + return [statement, cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217 + } + else { + var heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(ts.updateClassDeclaration(input, + /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members)); + } + } + case 217 /* VariableStatement */: { + return cleanup(transformVariableStatement(input, isPrivate)); + } + case 241 /* EnumDeclaration */: { + return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input, isPrivate)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) { + if (shouldStripInternal(m)) + return; + // Rewrite enum values to their constants, if available + var constValue = resolver.getConstantValue(m); + return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m); + })))); + } + } + // Anything left unhandled is an error, so this should be unreachable + return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]); + function cleanup(node) { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (input.kind === 242 /* ModuleDeclaration */) { + needsDeclare = previousNeedsDeclare; + } + if (node === input) { + return node; + } + return node && ts.setOriginalNode(preserveJsDoc(node, input), input); + } + } + function transformVariableStatement(input, privateDeclaration) { + if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible)) + return; + var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!ts.length(nodes)) + return; + return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input, privateDeclaration)), ts.updateVariableDeclarationList(input.declarationList, nodes)); + } + function recreateBindingPattern(d) { + return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); })); + } + function recreateBindingElement(e) { + if (e.kind === 208 /* OmittedExpression */) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) + return; + if (ts.isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + function checkName(node) { + var oldDiag; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = node.name; + ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names + var decl = node; + var entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + function hasInternalAnnotation(range) { + var comment = currentSourceFile.text.substring(range.pos, range.end); + return ts.stringContains(comment, "@internal"); + } + function shouldStripInternal(node) { + if (stripInternal && node) { + var leadingCommentRanges = ts.getLeadingCommentRangesOfNode(ts.getParseTreeNode(node), currentSourceFile); + if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + function ensureModifiers(node, privateDeclaration) { + var currentFlags = ts.getModifierFlags(node); + var newFlags = ensureModifierFlags(node, privateDeclaration); + if (currentFlags === newFlags) { + return node.modifiers; + } + return ts.createModifiersFromModifierFlags(newFlags); + } + function ensureModifierFlags(node, privateDeclaration) { + var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files + var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */; + var parentIsFile = node.parent.kind === 277 /* SourceFile */; + if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) { + mask ^= ((privateDeclaration || (isBundledEmit && parentIsFile) ? 0 : 1 /* Export */) | 512 /* Default */ | 2 /* Ambient */); + additions = 0 /* None */; + } + return maskModifierFlags(node, mask, additions); + } + function ensureAccessor(node) { + var accessors = resolver.getAllAccessorDeclarations(node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + var accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + var _loop_10 = function (range) { + if (range.kind === 3 /* MultiLineCommentTrivia */) { + var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + var lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + var lastLines = lines.slice(1); + var indentation_1 = ts.guessIndentation(lastLines); + text = [lines[0]].concat(ts.map(lastLines, function (l) { return l.slice(indentation_1); })).join(newLine); + } + ts.addSyntheticLeadingComment(prop, range.kind, text, range.hasTrailingNewLine); + } + }; + for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { + var range = leadingsSyntheticCommentRanges_1[_i]; + _loop_10(range); + } + } + return prop; + } + function transformHeritageClauses(nodes) { + return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { + return ts.isEntityNameExpression(t.expression) || (clause.token === 85 /* ExtendsKeyword */ && t.expression.kind === 95 /* NullKeyword */); + })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; })); + } + } + ts.transformDeclarations = transformDeclarations; + function isAlwaysType(node) { + if (node.kind === 239 /* InterfaceDeclaration */) { + return true; + } + return false; + } + // Elide "public" modifier, as it is the default + function maskModifiers(node, modifierMask, modifierAdditions) { + return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + function maskModifierFlags(node, modifierMask, modifierAdditions) { + if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; } + if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; } + var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & 512 /* Default */ && flags & 2 /* Ambient */) { + flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 156 /* GetAccessor */ + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + function canHaveLiteralInitializer(node) { + switch (node.kind) { + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 149 /* Parameter */: + return true; + } + return false; + } + function isPreservedDeclarationStatement(node) { + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 239 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 217 /* VariableStatement */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 252 /* ExportAssignment */: + return true; + } + return false; + } + function isProcessedComponent(node) { + switch (node.kind) { + case 159 /* ConstructSignature */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 160 /* IndexSignature */: + case 235 /* VariableDeclaration */: + case 148 /* TypeParameter */: + case 209 /* ExpressionWithTypeArguments */: + case 162 /* TypeReference */: + case 173 /* ConditionalType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 181 /* ImportType */: + return true; + } + return false; + } +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -68931,7 +76797,7 @@ var ts; * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files. */ function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) { - var enabledSyntaxKindFeatures = new Array(299 /* Count */); + var enabledSyntaxKindFeatures = new Array(309 /* Count */); var lexicalEnvironmentVariableDeclarations; var lexicalEnvironmentFunctionDeclarations; var lexicalEnvironmentVariableDeclarationsStack = []; @@ -68942,6 +76808,7 @@ var ts; var onSubstituteNode = function (_, node) { return node; }; var onEmitNode = function (hint, node, callback) { return callback(hint, node); }; var state = 0 /* Uninitialized */; + var diagnostics = []; // The transformation context is provided to each transformer as part of transformer // initialization. var context = { @@ -68971,6 +76838,9 @@ var ts; ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed."); ts.Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; + }, + addDiagnostic: function (diag) { + diagnostics.push(diag); } }; // Ensure the parse tree is clean before applying transformations @@ -68993,7 +76863,8 @@ var ts; transformed: transformed, substituteNode: substituteNode, emitNodeWithNotification: emitNodeWithNotification, - dispose: dispose + dispose: dispose, + diagnostics: diagnostics }; function transformRoot(node) { return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; @@ -69184,20 +77055,19 @@ var ts; } ts.transformNodes = transformNodes; })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, + emittedLine: 0, + emittedColumn: 0, + sourceLine: 0, + sourceColumn: 0, sourceIndex: 0 }; - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); + function createSourceMapWriter(host, writer, compilerOptions) { + if (compilerOptions === void 0) { compilerOptions = host.getCompilerOptions(); } var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSource; var currentSourceText; @@ -69210,11 +77080,11 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; + var sourceMapDataList; var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, - getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, emitNodeWithSourceMap: emitNodeWithSourceMap, @@ -69235,13 +77105,14 @@ var ts; * @param sourceMapFilePath The path to the output source map file. * @param sourceFileOrBundle The input source file or bundle for the program. */ - function initialize(filePath, sourceMapFilePath, sourceFileOrBundle) { - if (disabled) { + function initialize(filePath, sourceMapFilePath, sourceFileOrBundle, outputSourceMapDataList) { + if (disabled || ts.fileExtensionIs(filePath, ".json" /* Json */)) { return; } if (sourceMapData) { reset(); } + sourceMapDataList = outputSourceMapDataList; currentSource = undefined; currentSourceText = undefined; // Current source map file and its index in the sources list @@ -69261,7 +77132,6 @@ var ts; sourceMapNames: [], sourceMapMappings: "", sourceMapSourcesContent: compilerOptions.inlineSources ? [] : undefined, - sourceMapDecodedMappings: [] }; // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the // relative paths of the sources list in the sourcemap @@ -69271,10 +77141,10 @@ var ts; } if (compilerOptions.mapRoot) { sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (sourceFileOrBundle.kind === 272 /* SourceFile */) { // emitting single module file + if (sourceFileOrBundle.kind === 277 /* SourceFile */) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle, host, sourceMapDir)); + sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFileOrBundle.fileName, host, sourceMapDir)); } if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { // The relative paths are relative to the common directory @@ -69299,6 +77169,10 @@ var ts; if (disabled) { return; } + // Record source map data for the test harness. + if (sourceMapDataList) { + sourceMapDataList.push(sourceMapData); + } currentSource = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -69306,12 +77180,28 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; + sourceMapDataList = undefined; + } + function captureSection() { + return { + version: 3, + file: sourceMapData.sourceMapFile, + sourceRoot: sourceMapData.sourceMapSourceRoot, + sources: sourceMapData.sourceMapSources, + names: sourceMapData.sourceMapNames, + mappings: sourceMapData.sourceMapMappings, + sourcesContent: sourceMapData.sourceMapSourcesContent, + }; } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { return; } + ts.Debug.assert(lastRecordedSourceMapSpan.emittedColumn >= 0, "lastEncodedSourceMapSpan.emittedColumn was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceIndex >= 0, "lastEncodedSourceMapSpan.sourceIndex was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceLine >= 0, "lastEncodedSourceMapSpan.sourceLine was negative"); + ts.Debug.assert(lastRecordedSourceMapSpan.sourceColumn >= 0, "lastEncodedSourceMapSpan.sourceColumn was negative"); var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; // Line/Comma delimiters if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) { @@ -69325,7 +77215,7 @@ var ts; for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { sourceMapData.sourceMapMappings += ";"; } - prevEncodedEmittedColumn = 1; + prevEncodedEmittedColumn = 0; } // 1. Relative Column 0 based sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); @@ -69342,7 +77232,6 @@ var ts; lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; } lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } /** * Emits a mapping. @@ -69353,16 +77242,13 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (disabled || ts.positionIsSynthesized(pos)) { + if (disabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(currentSource)) { return; } if (extendedDiagnostics) { ts.performance.mark("beforeSourcemap"); } var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSource, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; var emittedLine = writer.getLine(); var emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span @@ -69394,6 +77280,9 @@ var ts; ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } + function isPossiblySourceMap(x) { + return typeof x === "object" && !!x.mappings && typeof x.mappings === "string" && !!x.sources; + } /** * Emits a node with possible leading and trailing source maps. * @@ -69402,21 +77291,66 @@ var ts; * @param emitCallback The callback used to emit the node. */ function emitNodeWithSourceMap(hint, node, emitCallback) { - if (disabled) { + var _a; + if (disabled || ts.isInJsonFile(node)) { return emitCallback(hint, node); } if (node) { + if (ts.isUnparsedSource(node) && node.sourceMapText !== undefined) { + var text = node.sourceMapText; + var parsed = void 0; + try { + parsed = JSON.parse(text); + } + catch (_b) { + // empty + } + if (!parsed || !isPossiblySourceMap(parsed)) { + return emitCallback(hint, node); + } + var offsetLine = writer.getLine(); + var firstLineColumnOffset = writer.getColumn(); + // First, decode the old component sourcemap + var originalMap = parsed; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + var resolvedPathCache = ts.createMap(); + var absolutePathCache = ts.createMap(); + var sourcemapIterator = ts.sourcemaps.decodeMappings(originalMap); + for (var _c = sourcemapIterator.next(), raw = _c.value, done = _c.done; !done; _a = sourcemapIterator.next(), raw = _a.value, done = _a.done, _a) { + var pathCacheKey = "" + raw.sourceIndex; + // Apply offsets to each position and fixup source entries + if (!resolvedPathCache.has(pathCacheKey)) { + var rawPath = originalMap.sources[raw.sourceIndex]; + var relativePath = originalMap.sourceRoot ? ts.combinePaths(originalMap.sourceRoot, rawPath) : rawPath; + var combinedPath = ts.combinePaths(ts.getDirectoryPath(node.sourceMapPath), relativePath); + var resolvedPath_1 = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, combinedPath, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + resolvedPathCache.set(pathCacheKey, resolvedPath_1); + absolutePathCache.set(pathCacheKey, ts.getNormalizedAbsolutePath(resolvedPath_1, sourcesDirectoryPath)); + } + var resolvedPath = resolvedPathCache.get(pathCacheKey); + var absolutePath = absolutePathCache.get(pathCacheKey); + // tslint:disable-next-line:no-null-keyword + setupSourceEntry(absolutePath, originalMap.sourcesContent ? originalMap.sourcesContent[raw.sourceIndex] : null, resolvedPath); // TODO: Lookup content for inlining? + var newIndex = sourceMapData.sourceMapSources.indexOf(resolvedPath); + // Then reencode all the updated spans into the overall map + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = __assign({}, raw, { emittedLine: raw.emittedLine + offsetLine, emittedColumn: raw.emittedLine === 0 ? (raw.emittedColumn + firstLineColumnOffset) : raw.emittedColumn, sourceIndex: newIndex }); + } + // And actually emit the text these sourcemaps are for + return emitCallback(hint, node); + } var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.sourceMapRange; - var _a = range || node, pos = _a.pos, end = _a.end; + var _d = range || node, pos = _d.pos, end = _d.end; var source = range && range.source; var oldSource = currentSource; if (source === oldSource) source = undefined; if (source) setSourceFile(source); - if (node.kind !== 294 /* NotEmittedStatement */ + if (node.kind !== 304 /* NotEmittedStatement */ && (emitFlags & 16 /* NoLeadingSourceMap */) === 0 && pos >= 0) { emitPos(skipSourceTrivia(pos)); @@ -69433,7 +77367,7 @@ var ts; } if (source) setSourceFile(source); - if (node.kind !== 294 /* NotEmittedStatement */ + if (node.kind !== 304 /* NotEmittedStatement */ && (emitFlags & 32 /* NoTrailingSourceMap */) === 0 && end >= 0) { emitPos(end); @@ -69451,11 +77385,11 @@ var ts; * @param emitCallback The callback used to emit the token. */ function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { - if (disabled) { + if (disabled || ts.isInJsonFile(node)) { return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0 /* None */; var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; tokenPos = skipSourceTrivia(range ? range.pos : tokenPos); if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { @@ -69469,6 +77403,9 @@ var ts; } return tokenPos; } + function isJsonSourceMapSource(sourceFile) { + return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */); + } /** * Set the current source file. * @@ -69480,20 +77417,28 @@ var ts; } currentSource = sourceFile; currentSourceText = currentSource.text; - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); + if (isJsonSourceMapSource(sourceFile)) { + return; + } + setupSourceEntry(sourceFile.fileName, sourceFile.text); + } + function setupSourceEntry(fileName, content, source) { + if (!source) { + // Add the file to tsFilePaths + // If sourceroot option: Use the relative path corresponding to the common directory path + // otherwise source locations relative to map file location + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ true); + } sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(currentSource.fileName); + sourceMapData.inputSourceFileNames.push(fileName); if (compilerOptions.inlineSources) { - sourceMapData.sourceMapSourcesContent.push(currentSource.text); + sourceMapData.sourceMapSourcesContent.push(content); } } } @@ -69501,30 +77446,22 @@ var ts; * Gets the text for the source map. */ function getText() { - if (disabled) { - return; + if (disabled || isJsonSourceMapSource(currentSource)) { + return undefined; // TODO: GH#18217 } encodeLastRecordedSourceMapSpan(); - return JSON.stringify({ - version: 3, - file: sourceMapData.sourceMapFile, - sourceRoot: sourceMapData.sourceMapSourceRoot, - sources: sourceMapData.sourceMapSources, - names: sourceMapData.sourceMapNames, - mappings: sourceMapData.sourceMapMappings, - sourcesContent: sourceMapData.sourceMapSourcesContent, - }); + return JSON.stringify(captureSection()); } /** * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { - if (disabled) { - return; + if (disabled || isJsonSourceMapSource(currentSource)) { + return undefined; // TODO: GH#18217 } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - var base64SourceMapText = ts.convertToBase64(getText()); + var base64SourceMapText = ts.base64encode(ts.sys, getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; } else { @@ -69566,7 +77503,6 @@ var ts; return encodedStr; } })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -69582,7 +77518,7 @@ var ts; var currentLineMap; var detachedCommentsInfo; var hasWrittenComment = false; - var disabled = printerOptions.removeComments; + var disabled = !!printerOptions.removeComments; return { reset: reset, setWriter: setWriter, @@ -69600,7 +77536,7 @@ var ts; if (node) { hasWrittenComment = false; var emitNode = node.emitNode; - var emitFlags = emitNode && emitNode.flags; + var emitFlags = emitNode && emitNode.flags || 0; var _a = emitNode && emitNode.commentRange || node, pos = _a.pos, end = _a.end; if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. @@ -69610,7 +77546,7 @@ var ts; if (extendedDiagnostics) { ts.performance.mark("preEmitNodeWithComment"); } - var isEmittedNode = node.kind !== 294 /* NotEmittedStatement */; + var isEmittedNode = node.kind !== 304 /* NotEmittedStatement */; // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation. // It is expensive to walk entire tree just to set one kind of node to have no comments. var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 10 /* JsxText */; @@ -69631,7 +77567,7 @@ var ts; containerEnd = end; // To avoid invalid comment emit in a down-level binding pattern, we // keep track of the last declaration list container's end - if (node.kind === 231 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { declarationListContainerEnd = end; } } @@ -69778,7 +77714,15 @@ var ts; emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos); } } + function shouldWriteComment(text, pos) { + if (printerOptions.onlyPrintJsDocStyle) { + return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos)); + } + return true; + } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (!hasWrittenComment) { ts.emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -69806,6 +77750,8 @@ var ts; forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -69878,11 +77824,11 @@ var ts; detachedCommentsInfo = undefined; } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; + return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { // get the leading comments from detachedPos - var pos = ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos; + var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -69903,6 +77849,8 @@ var ts; } } function writeComment(text, lineMap, writer, commentPos, commentEnd, newLine) { + if (!shouldWriteComment(currentText, commentPos)) + return; if (emitPos) emitPos(commentPos); ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); @@ -69920,1840 +77868,9 @@ var ts; } ts.createCommentWriter = createCommentWriter; })(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getDeclarationDiagnostics(host, resolver, targetSourceFile) { - var declarationDiagnostics = ts.createDiagnosticCollection(); - ts.forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - function getDeclarationDiagnosticsFromFile(_a, sourceFileOrBundle) { - var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - var newLine = host.getNewLine(); - var compilerOptions = host.getCompilerOptions(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer; - createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var resultHasExternalModuleIndicator; - var currentText; - var currentLineMap; - var currentIdentifiers; - var isCurrentFileExternalModule; - var reportedDeclarationError = false; - var errorNameNode; - var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; - var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var needsDeclare = true; - var moduleElementDeclarationEmitInfo = []; - var asynchronousSubModuleDeclarationEmitInfo; - // Contains the reference paths that needs to go in the declaration file. - // Collecting this separately because reference paths need to be first thing in the declaration file - // and we could be collecting these paths from multiple files into single one with --out option - var referencesOutput = ""; - var usedTypeDirectiveReferences; - // Emit references corresponding to each file - var emittedReferencedFiles = []; - var addedGlobalFileReference = false; - var allSourcesModuleElementDeclarationEmitInfo = []; - ts.forEach(sourceFiles, function (sourceFile) { - // Dont emit for javascript file - if (ts.isSourceFileJavaScript(sourceFile)) { - return; - } - // Check what references need to be added - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); - // Emit reference in dts, if the file reference was not already emitted - if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - // Add a reference to generated dts file, - // global file reference is added only - // - if it is not bundled emit (because otherwise it would be self reference) - // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { - addedGlobalFileReference = true; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (ts.isExternalModule(sourceFile)) { - needsDeclare = false; - write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - } - // create asynchronous output for the importDeclarations - if (moduleElementDeclarationEmitInfo.length) { - var oldWriter = writer; - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - ts.Debug.assert(aliasEmitInfo.node.kind === 242 /* ImportDeclaration */); - createAndSetNewTextWriterWithSymbolWriter(); - ts.Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (var i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { - // if file was external module this fact should be preserved in .d.ts as well. - // in case if we didn't write any external module specifiers in .d.ts we need to emit something - // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. - write("export {};"); - writeLine(); - } - }); - if (usedTypeDirectiveReferences) { - ts.forEachKey(usedTypeDirectiveReferences, function (directive) { - referencesOutput += "/// " + newLine; - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput: referencesOutput, - }; - function hasInternalAnnotation(range) { - var comment = currentText.substring(range.pos, range.end); - return ts.stringContains(comment, "@internal"); - } - function stripInternal(node) { - if (node) { - var leadingCommentRanges = ts.getLeadingCommentRanges(currentText, node.pos); - if (ts.forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - emitNode(node); - } - } - function createAndSetNewTextWriterWithSymbolWriter() { - var writer = ts.createTextWriter(newLine); - writer.trackSymbol = trackSymbol; - writer.reportInaccessibleThisError = reportInaccessibleThisError; - writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; - writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; - writer.writeKeyword = writer.write; - writer.writeOperator = writer.write; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsynchronousModuleElements(nodes) { - var oldWriter = writer; - ts.forEach(nodes, function (declaration) { - var nodeToCheck; - if (declaration.kind === 230 /* VariableDeclaration */) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === 245 /* NamedImports */ || declaration.kind === 246 /* ImportSpecifier */ || declaration.kind === 243 /* ImportClause */) { - ts.Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - var moduleElementEmitInfo = ts.forEach(moduleElementDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { - moduleElementEmitInfo = ts.forEach(asynchronousSubModuleDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined; }); - } - // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration - // then we don't need to write it at this point. We will write it when we actually see its declaration - // Eg. - // export function bar(a: foo.Foo) { } - // import foo = require("foo"); - // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, - // we would write alias foo declaration when we visit it since it would now be marked as visible - if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === 242 /* ImportDeclaration */) { - // we have to create asynchronous output only after we have collected complete information - // because it is possible to enable multiple bindings as asynchronously visible - moduleElementEmitInfo.isVisible = true; - } - else { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - ts.Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === 237 /* ModuleDeclaration */) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) { - if (!typeReferenceDirectives) { - return; - } - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = ts.createMap(); - } - for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) { - var directive = typeReferenceDirectives_2[_i]; - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - function handleSymbolAccessibilityError(symbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) { - // write the aliases - if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); - } - } - else { - // Report error - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNodeFromSourceText(currentText, errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - function reportPrivateInBaseOfClassExpression(propertyName) { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); - } - } - function reportInaccessibleUniqueSymbolError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol")); - } - } - function reportInaccessibleThisError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this")); - } - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - // use the checker's type, not the declared type, - // for optional parameter properties - // and also for non-optional initialized parameters that aren't a parameter property - // these types may need to add `undefined`. - var shouldUseResolverType = declaration.kind === 148 /* Parameter */ && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | - 2048 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - errorNameNode = undefined; - } - } - function emitLines(nodes) { - for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { - var node = nodes_6[_i]; - emit(node); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { - var node = nodes_7[_i]; - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - function emitCommaList(nodes, eachNodeEmitFn, canEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJSDocCommentRanges(declaration, currentText); - ts.emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, ts.writeCommentRange); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 119 /* AnyKeyword */: - case 137 /* StringKeyword */: - case 134 /* NumberKeyword */: - case 122 /* BooleanKeyword */: - case 135 /* ObjectKeyword */: - case 138 /* SymbolKeyword */: - case 105 /* VoidKeyword */: - case 140 /* UndefinedKeyword */: - case 95 /* NullKeyword */: - case 131 /* NeverKeyword */: - case 173 /* ThisType */: - case 177 /* LiteralType */: - return writeTextOfNode(currentText, type); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(type); - case 161 /* TypeReference */: - return emitTypeReference(type); - case 164 /* TypeQuery */: - return emitTypeQuery(type); - case 166 /* ArrayType */: - return emitArrayType(type); - case 167 /* TupleType */: - return emitTupleType(type); - case 168 /* UnionType */: - return emitUnionType(type); - case 169 /* IntersectionType */: - return emitIntersectionType(type); - case 170 /* ConditionalType */: - return emitConditionalType(type); - case 171 /* InferType */: - return emitInferType(type); - case 172 /* ParenthesizedType */: - return emitParenType(type); - case 174 /* TypeOperator */: - return emitTypeOperator(type); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(type); - case 176 /* MappedType */: - return emitMappedType(type); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 165 /* TypeLiteral */: - return emitTypeLiteral(type); - case 71 /* Identifier */: - return emitEntityName(type); - case 145 /* QualifiedName */: - return emitEntityName(type); - case 160 /* TypePredicate */: - return emitTypePredicate(type); - } - function writeEntityName(entityName) { - if (entityName.kind === 71 /* Identifier */) { - writeTextOfNode(currentText, entityName); - } - else { - var left = entityName.kind === 145 /* QualifiedName */ ? entityName.left : entityName.expression; - var right = entityName.kind === 145 /* QualifiedName */ ? entityName.right : entityName.name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === 241 /* ImportEqualsDeclaration */ ? entityName.parent : enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeEntityName(entityName); - } - function emitExpressionWithTypeArguments(node) { - if (ts.isEntityNameExpression(node.expression)) { - ts.Debug.assert(node.expression.kind === 71 /* Identifier */ || node.expression.kind === 183 /* PropertyAccessExpression */); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypePredicate(type) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitIntersectionType(type) { - emitSeparatedList(type.types, " & ", emitType); - } - function emitConditionalType(node) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - function emitInferType(node) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeOperator(type) { - write(ts.tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - function emitIndexedAccessType(node) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - function emitMappedType(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === 37 /* PlusToken */ ? "+readonly " : - node.readonlyToken.kind === 38 /* MinusToken */ ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === 37 /* PlusToken */ ? "+?" : - node.questionToken.kind === 38 /* MinusToken */ ? "-?" : - "?"); - } - write(": "); - if (node.type) { - emitType(node.type); - } - else { - write("any"); - } - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentText = node.text; - currentLineMap = ts.getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = ts.isExternalModule(node); - enclosingDeclaration = node; - ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComments*/ true); - emitLines(node.statements); - } - // Return a temp variable name to be used in `export default`/`export class ... extends` statements. - // The temp name will be of the form _default_counter. - // Note that export default is only allowed at most once in a module, so we - // do not need to keep track of created temp names. - function getExportTempVariableName(baseName) { - if (!currentIdentifiers.has(baseName)) { - return baseName; - } - var count = 0; - while (true) { - count++; - var name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { - var tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */, writer); - write(";"); - writeLine(); - return tempVarName; - } - function emitExportAssignment(node) { - if (ts.isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === 71 /* Identifier */) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - // Make all the declarations visible for the export name - if (node.expression.kind === 71 /* Identifier */) { - var nodes = resolver.collectLinkedAliases(node.expression); - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - } - function isModuleElementVisible(node) { - return resolver.isDeclarationVisible(node); - } - function emitModuleElement(node, isModuleElementVisible) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective - else if (node.kind === 241 /* ImportEqualsDeclaration */ || - (node.parent.kind === 272 /* SourceFile */ && isCurrentFileExternalModule)) { - var isVisible = void 0; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== 272 /* SourceFile */) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - else { - if (node.kind === 242 /* ImportDeclaration */) { - var importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible: isVisible - }); - } - } - } - function writeModuleElement(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - return writeFunctionDeclaration(node); - case 212 /* VariableStatement */: - return writeVariableStatement(node); - case 234 /* InterfaceDeclaration */: - return writeInterfaceDeclaration(node); - case 233 /* ClassDeclaration */: - return writeClassDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return writeTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return writeEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return writeModuleDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return writeImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return writeImportDeclaration(node); - default: - ts.Debug.fail("Unknown symbol kind"); - } - } - function emitModuleElementDeclarationFlags(node) { - // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === 272 /* SourceFile */) { - var modifiers = ts.getModifierFlags(node); - // If the node is exported - if (modifiers & 1 /* Export */) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - if (modifiers & 512 /* Default */) { - write("default "); - } - else if (node.kind !== 234 /* InterfaceDeclaration */ && needsDeclare) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(flags) { - if (flags & 8 /* Private */) { - write("private "); - } - else if (flags & 16 /* Protected */) { - write("protected "); - } - if (flags & 32 /* Static */) { - write("static "); - } - if (flags & 64 /* Readonly */) { - write("readonly "); - } - if (flags & 128 /* Abstract */) { - write("abstract "); - } - } - function writeImportEqualsDeclaration(node) { - // note usage of writer. methods instead of aliases created, just to make sure we are using - // correct writer especially to handle asynchronous alias writing - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (ts.isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function isVisibleNamedBinding(namedBindings) { - if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(function (namedImport) { return resolver.isDeclarationVisible(namedImport); }); - } - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (ts.hasModifier(node, 1 /* Export */)) { - write("export "); - } - write("import "); - if (node.importClause) { - var currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { - if (currentWriterPos !== writer.getTextPos()) { - // If the default binding was emitted, write the separated - write(", "); - } - if (node.importClause.namedBindings.kind === 244 /* NamespaceImport */) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - function emitExternalModuleSpecifier(parent) { - // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). - // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered - // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' - // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 237 /* ModuleDeclaration */; - var moduleSpecifier = parent.kind === 241 /* ImportEqualsDeclaration */ ? ts.getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === 237 /* ModuleDeclaration */ ? parent.name : parent.moduleSpecifier; - if (moduleSpecifier.kind === 9 /* StringLiteral */ && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - var moduleName = ts.getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - writeTextOfNode(currentText, moduleSpecifier); - } - function emitImportOrExportSpecifier(node) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - function emitExportSpecifier(node) { - emitImportOrExportSpecifier(node); - // Make all the declarations visible for the export name - var nodes = resolver.collectLinkedAliases(node.propertyName || node.name); - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - function emitExportDeclaration(node) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - function writeModuleDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & 16 /* Namespace */) { - write("namespace "); - } - else { - write("module "); - } - if (ts.isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== 238 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - function writeTypeAliasDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - function getTypeAliasDeclarationVisibilityError() { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function writeEnumDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - var enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(ts.getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 153 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentText, node.name); - // If there is constraint present and this is not a type parameter of the private method emit the constraint - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - (node.parent.parent && node.parent.parent.kind === 165 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 153 /* MethodDeclaration */ || - node.parent.kind === 152 /* MethodSignature */ || - node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.kind === 157 /* CallSignature */ || - node.parent.kind === 158 /* ConstructSignature */); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError() { - // Type parameter constraints are named by user so we should always be able to name it - var diagnosticMessage; - switch (node.parent.kind) { - case 233 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 234 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 158 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 157 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 232 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - case 235 /* TypeAliasDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - if (ts.isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { - write("null"); - } - function getHeritageClauseVisibilityError() { - var diagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - // Class or Interface implemented/extended is inaccessible - diagnosticMessage = isImplementsList ? - ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : - ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; - } - else { - // interface is inaccessible - diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: ts.getNameOfDeclaration(node.parent.parent) - }; - } - } - } - function writeClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (ts.hasModifier(param, 92 /* ParameterPropertyModifier */)) { - emitPropertyDeclaration(param); - } - }); - } - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - var tempVarName; - if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? - "null" : - emitTempVariableDeclaration(baseTypeNode.expression, node.name.escapedText + "_base", { - diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, - errorNode: baseTypeNode, - typeName: node.name - }, !ts.findAncestor(node, function (n) { return n.kind === 237 /* ModuleDeclaration */; })); - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.hasModifier(node, 128 /* Abstract */)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!ts.isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(ts.getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function writeInterfaceDeclaration(node) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - function emitPropertyDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - emitJsDocComments(node); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - emitVariableDeclaration(node); - write(";"); - writeLine(); - } - function bindingNameContainsVisibleBindingElement(node) { - return !!node && ts.isBindingPattern(node) && ts.some(node.elements, function (elem) { return !ts.isOmittedExpression(elem) && isVariableDeclarationVisible(elem); }); - } - function isVariableDeclarationVisible(node) { - return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); - } - function emitVariableDeclaration(node) { - // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted - // so there is no check needed to see if declaration is visible - if (node.kind !== 230 /* VariableDeclaration */ || isVariableDeclarationVisible(node)) { - if (ts.isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); - // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor - // we don't want to emit property declaration with "?" - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && !ts.isParameterPropertyDeclaration(node))) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */) && node.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!ts.hasModifier(node, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (node.kind === 230 /* VariableDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } - // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === 151 /* PropertyDeclaration */ || node.kind === 150 /* PropertySignature */ || - (node.kind === 148 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) { - // TODO(jfreeman): Deal with computed properties in error reporting. - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */ || node.kind === 148 /* Parameter */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function emitBindingPattern(bindingPattern) { - // Only select visible, non-omitted expression from the bindingPattern's elements. - // We have to do this to avoid emitting trailing commas. - // For example: - // original: var [, c,,] = [ 2,3,4] - // emitted: declare var c: number; // instead of declare var c:number, ; - var elements = []; - for (var _i = 0, _a = bindingPattern.elements; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 204 /* OmittedExpression */ && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - function emitBindingElement(bindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); - } - } - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - // if this is property of type literal, - // or is parameter of method/call/construct/index signature of type literal - // emit only if type is specified - if (ts.hasType(node)) { - write(": "); - emitType(node.type); - } - } - function isVariableStatementVisible(node) { - return ts.forEach(node.declarationList.declarations, function (varDeclaration) { return isVariableDeclarationVisible(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)) { - write("let "); - } - else if (ts.isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - function emitAccessorDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - var accessors = ts.getAllAccessorDeclarations(node.parent.members, node); - var accessorWithTypeAnnotation; - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(ts.getModifierFlags(node) | (accessors.setAccessor ? 0 : 64 /* Readonly */)); - writeNameOfDeclaration(node, getAccessorNameVisibilityError); - if (!ts.hasModifier(node, 8 /* Private */)) { - accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - // couldn't get type for the first accessor, try the another one - var anotherAccessor = node.kind === 155 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 155 /* GetAccessor */ - ? accessor.type // Getter - return type - : accessor.parameters.length > 0 - ? accessor.parameters[0].type // Setter parameter type - : undefined; - } - } - function getAccessorNameVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 156 /* SetAccessor */) { - // Getters can infer the return type from the returned expression, but setters cannot, so the - // "_from_external_module_1_but_cannot_be_named" case cannot occur. - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - else { - if (ts.hasModifier(accessorWithTypeAnnotation, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: accessorWithTypeAnnotation.name - }; - } - } - function writeFunctionDeclaration(node) { - if (ts.hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting - // so no need to verify if the declaration is visible - if (!resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 232 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 153 /* MethodDeclaration */ || node.kind === 154 /* Constructor */) { - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - } - if (node.kind === 232 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === 154 /* Constructor */) { - write("constructor"); - } - else { - writeNameOfDeclaration(node, getMethodNameVisibilityError); - if (ts.hasQuestionToken(node)) { - write("?"); - } - } - emitSignatureDeclaration(node); - } - function getMethodNameVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) { - if (ts.hasModifier(node, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - function writeNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { - if (ts.hasDynamicName(node)) { - // If this node has a dynamic name, it can only be an identifier or property access because - // we've already skipped it otherwise. - ts.Debug.assert(resolver.isLateBound(node)); - writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic); - } - else { - // If this node is a computed name, it can only be a symbol, because we've already skipped - // it if it's not a well known symbol. In that case, the text of the name will be exactly - // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentText, node.name); - } - } - function writeLateBoundNameOfDeclaration(node, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - var entityName = node.name.expression; - var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeTextOfNode(currentText, node.name); - } - function emitSignatureDeclarationWithJsDocComments(node) { - emitJsDocComments(node); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - var closeParenthesizedFunctionType = false; - if (node.kind === 159 /* IndexSignature */) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(ts.getModifierFlags(node)); - write("["); - } - else { - if (node.kind === 154 /* Constructor */ && ts.hasModifier(node, 8 /* Private */)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === 158 /* ConstructSignature */ || node.kind === 163 /* ConstructorType */) { - write("new "); - } - else if (node.kind === 162 /* FunctionType */) { - var currentOutput = writer.getText(); - // Do not generate incorrect type when function type with type parameters is type argument - // This could happen if user used space between two '<' making it error free - // e.g var x: A< (a: Tany)=>Tany>; - if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { - closeParenthesizedFunctionType = true; - write("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 159 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - // If this is not a constructor and is not private, emit the return type - var isFunctionTypeOrConstructorType = node.kind === 162 /* FunctionType */ || node.kind === 163 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 165 /* TypeLiteral */) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 154 /* Constructor */ && !ts.hasModifier(node, 8 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - function getReturnTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 158 /* ConstructSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 157 /* CallSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 159 /* IndexSignature */: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node, 32 /* Static */)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - } - else if (node.parent.kind === 233 /* ClassDeclaration */) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; - } - else { - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; - } - break; - case 232 /* FunctionDeclaration */: - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : - ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - // For bindingPattern, we can't simply writeTextOfNode from the source file - // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. - // Therefore, we will have to recursively emit each element in the bindingPattern. - emitBindingPattern(node.name); - } - else { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 162 /* FunctionType */ || - node.parent.kind === 163 /* ConstructorType */ || - node.parent.parent.kind === 165 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!ts.hasModifier(node.parent, 8 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) { - var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) { - switch (node.parent.kind) { - case 154 /* Constructor */: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - case 158 /* ConstructSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - case 157 /* CallSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - case 159 /* IndexSignature */: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.hasModifier(node.parent, 32 /* Static */)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 233 /* ClassDeclaration */) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - case 232 /* FunctionDeclaration */: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ? - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : - ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - function emitBindingPattern(bindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === 178 /* ObjectBindingPattern */) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === 179 /* ArrayBindingPattern */) { - write("["); - var elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - function emitBindingElement(bindingElement) { - if (bindingElement.kind === 204 /* OmittedExpression */) { - // If bindingElement is an omittedExpression (i.e. containing elision), - // we will emit blank space (although this may differ from users' original code, - // it allows emitSeparatedList to write separator appropriately) - // Example: - // original: function foo([, x, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === 180 /* BindingElement */) { - if (bindingElement.propertyName) { - // bindingElement has propertyName property in the following case: - // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" - // We have to explicitly emit the propertyName before descending into its binding elements. - // Example: - // original: function foo({y: [a,b,c]}) {} - // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentText, bindingElement.propertyName); - write(": "); - } - if (bindingElement.name) { - if (ts.isBindingPattern(bindingElement.name)) { - // If it is a nested binding pattern, we will recursively descend into each element and emit each one separately. - // In the case of rest element, we will omit rest element. - // Example: - // original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {} - // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; - // original with rest: function foo([a, ...c]) {} - // emit : declare function foo([a, ...c]): void; - emitBindingPattern(bindingElement.name); - } - else { - ts.Debug.assert(bindingElement.name.kind === 71 /* Identifier */); - // If the node is just an identifier, we will simply emit the text associated with the node's name - // Example: - // original: function foo({y = 10, x}) {} - // emit : declare function foo({y, x}: {number, any}): void; - if (bindingElement.dotDotDotToken) { - write("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - function emitNode(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 234 /* InterfaceDeclaration */: - case 233 /* ClassDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - return emitModuleElement(node, isModuleElementVisible(node)); - case 212 /* VariableStatement */: - return emitModuleElement(node, isVariableStatementVisible(node)); - case 242 /* ImportDeclaration */: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/ !node.importClause); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return writeFunctionDeclaration(node); - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 159 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 271 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 272 /* SourceFile */: - return emitSourceFile(node); - } - } - /** - * Adds the reference to referenced file, returns true if global file reference was emitted - * @param referencedFile - * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not - */ - function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { - var declFileName; - var addedBundledEmitReference = false; - if (referencedFile.isDeclarationFile) { - // Declaration file, use declaration file name - declFileName = referencedFile.fileName; - } - else { - // Get the declaration file path - ts.forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); - } - if (declFileName) { - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - referencesOutput += "/// " + newLine; - } - return addedBundledEmitReference; - function getDeclFileName(emitFileNames, sourceFileOrBundle) { - // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path - var isBundledEmit = sourceFileOrBundle.kind === 273 /* Bundle */; - if (isBundledEmit && !addBundledFileReference) { - return; - } - ts.Debug.assert(!!emitFileNames.declarationFilePath || ts.isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); - var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped || emitOnlyDtsFiles) { - var sourceFiles = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - var declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - ts.writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - function getDeclarationOutput(synchronousDeclarationOutput, moduleElementDeclarationEmitInfo) { - var appliedSyncOutputPos = 0; - var declarationOutput = ""; - // apply asynchronous additions to the synchronous output - ts.forEach(moduleElementDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } - ts.writeDeclarationFile = writeDeclarationFile; -})(ts || (ts = {})); -/// -/// -/// -/// -/// var ts; (function (ts) { + var infoExtension = ".tsbundleinfo"; var brackets = createBracketsMap(); /*@internal*/ /** @@ -71766,14 +77883,13 @@ var ts; * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); var options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - var jsFilePath = options.outFile || options.out; - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var bundle = ts.createBundle(sourceFiles, host.getPrependNodes()); + var result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -71782,10 +77898,7 @@ var ts; else { for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) { var sourceFile = sourceFiles_1[_a]; - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -71793,13 +77906,45 @@ var ts; } } ts.forEachEmittedFile = forEachEmittedFile; + /*@internal*/ + function getOutputPathsFor(sourceFile, host, forceDtsPaths) { + var options = host.getCompilerOptions(); + if (sourceFile.kind === 278 /* Bundle */) { + var jsFilePath = options.outFile || options.out; + var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + var bundleInfoPath = options.references && jsFilePath ? (ts.removeFileExtension(jsFilePath) + infoExtension) : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: bundleInfoPath }; + } + else { + var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); + var sourceMapFilePath = ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + var isJs = ts.isSourceFileJavaScript(sourceFile); + var declarationFilePath = ((forceDtsPaths || ts.getEmitDeclarations(options)) && !isJs) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; + var declarationMapPath = ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; + return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, bundleInfoPath: undefined }; + } + } + ts.getOutputPathsFor = getOutputPathsFor; function getSourceMapFilePath(jsFilePath, options) { - return options.sourceMap ? jsFilePath + ".map" : undefined; + return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined; + } + function createDefaultBundleInfo() { + return { + originalOffset: -1, + totalLength: -1 + }; } // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also. // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve. // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve + /* @internal */ function getOutputExtension(sourceFile, options) { + if (ts.isJsonSourceFile(sourceFile)) { + return ".json" /* Json */; + } if (options.jsx === 1 /* Preserve */) { if (ts.isSourceFileJavaScript(sourceFile)) { if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) { @@ -71813,71 +77958,39 @@ var ts; } return ".js" /* Js */; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle) { - if (sourceFileOrBundle.kind === 273 /* Bundle */) { - return ts.updateBundle(sourceFileOrBundle, ts.sameMap(sourceFileOrBundle.sourceFiles, ts.getOriginalSourceFile)); - } - return ts.getOriginalSourceFile(sourceFileOrBundle); - } + ts.getOutputExtension = getOutputExtension; /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles, transformers, declarationTransformers) { var compilerOptions = host.getCompilerOptions(); - var moduleKind = ts.getEmitModuleKind(compilerOptions); - var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); var writer = ts.createTextWriter(newLine); var sourceMap = ts.createSourceMapWriter(host, writer); - var currentSourceFile; - var bundledHelpers; - var isOwnFileEmit; - var emitSkipped = false; - var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); - // Transform the source files - var transform = ts.transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); - // Create a printer to print the nodes - var printer = createPrinter(compilerOptions, { - // resolver hooks - hasGlobalName: resolver.hasGlobalName, - // transform hooks - onEmitNode: transform.emitNodeWithNotification, - substituteNode: transform.substituteNode, - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - // emitter hooks - onEmitHelpers: emitHelpers, - onSetSourceFile: setSourceFile, + var declarationSourceMap = ts.createSourceMapWriter(host, writer, { + sourceMap: compilerOptions.declarationMap, + sourceRoot: compilerOptions.sourceRoot, + mapRoot: compilerOptions.mapRoot, + extendedDiagnostics: compilerOptions.extendedDiagnostics, }); + var bundleInfo = createDefaultBundleInfo(); + var emitSkipped = false; // Emit each output file ts.performance.mark("beforePrint"); - forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), emittedFiles: emittedFilesList, - sourceMaps: sourceMapDataList + sourceMaps: sourceMapDataList, }; function emitSourceFileOrBundle(_a, sourceFileOrBundle) { - var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath; - // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, bundleInfoPath = _a.bundleInfoPath; + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { emittedFilesList.push(jsFilePath); @@ -71888,96 +78001,145 @@ var ts; if (declarationFilePath) { emittedFilesList.push(declarationFilePath); } + if (bundleInfoPath) { + emittedFilesList.push(bundleInfoPath); + } } } - function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle) { - var bundle = sourceFileOrBundle.kind === 273 /* Bundle */ ? sourceFileOrBundle : undefined; - var sourceFile = sourceFileOrBundle.kind === 272 /* SourceFile */ ? sourceFileOrBundle : undefined; + function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, bundleInfoPath) { + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // Transform the source files + var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], transformers, /*allowDtsFiles*/ false); + // Create a printer to print the nodes + var printer = createPrinter(__assign({}, compilerOptions, { noEmitHelpers: compilerOptions.noEmitHelpers }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + // sourcemap hooks + onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: sourceMap.emitPos, + // emitter hooks + onSetSourceFile: setSourceFile, + }); + ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform"); + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], bundleInfoPath, printer, sourceMap); + // Clean up emit nodes on parse tree + transform.dispose(); + } + function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { + if (!(declarationFilePath && !ts.isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + var nonJsFiles = ts.filter(sourceFiles, ts.isSourceFileNotJavaScript); + var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(nonJsFiles, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; + if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) { + // Checker wont collect the linked aliases since thats only done when declaration is enabled. + // Do that here when emitting only dts files + nonJsFiles.forEach(collectLinkedAliases); + } + var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, ts.concatenate([ts.transformDeclarations], declarationTransformers), /*allowDtsFiles*/ false); + if (ts.length(declarationTransform.diagnostics)) { + for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) { + var diagnostic = _b[_a]; + emitterDiagnostics.add(diagnostic); + } + } + var declarationPrinter = createPrinter(__assign({}, compilerOptions, { onlyPrintJsDocStyle: true, noEmitHelpers: true }), { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + // sourcemap hooks + onEmitSourceMapOfNode: declarationSourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: declarationSourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: declarationSourceMap.emitPos, + onSetSourceFile: setSourceFileForDeclarationSourceMaps, + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform"); + printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], /* bundleInfopath*/ undefined, declarationPrinter, declarationSourceMap); + } + declarationTransform.dispose(); + } + function collectLinkedAliases(node) { + if (ts.isExportAssignment(node)) { + if (node.expression.kind === 71 /* Identifier */) { + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); + } + return; + } + else if (ts.isExportSpecifier(node)) { + resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true); + return; + } + ts.forEachChild(node, collectLinkedAliases); + } + function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, bundleInfoPath, printer, mapRecorder) { + var bundle = sourceFileOrBundle.kind === 278 /* Bundle */ ? sourceFileOrBundle : undefined; + var sourceFile = sourceFileOrBundle.kind === 277 /* SourceFile */ ? sourceFileOrBundle : undefined; var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; - sourceMap.initialize(jsFilePath, sourceMapFilePath, sourceFileOrBundle); + mapRecorder.initialize(jsFilePath, sourceMapFilePath || "", sourceFileOrBundle, sourceMapDataList); if (bundle) { - bundledHelpers = ts.createMap(); - isOwnFileEmit = false; - printer.writeBundle(bundle, writer); + printer.writeBundle(bundle, writer, bundleInfo); } else { - isOwnFileEmit = true; printer.writeFile(sourceFile, writer); } writer.writeLine(); - var sourceMappingURL = sourceMap.getSourceMappingURL(); + var sourceMappingURL = mapRecorder.getSourceMappingURL(); if (sourceMappingURL) { writer.write("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Sometimes tools can sometimes see this line as a source mapping url comment } // Write the source map - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { - ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); - } - // Record source map data for the test harness. - if (sourceMapDataList) { - sourceMapDataList.push(sourceMap.getSourceMapData()); + if (sourceMapFilePath) { + ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, mapRecorder.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Write the output file - ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); + ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles); + // Write bundled offset information if applicable + if (bundleInfoPath) { + bundleInfo.totalLength = writer.getTextPos(); + ts.writeFile(host, emitterDiagnostics, bundleInfoPath, JSON.stringify(bundleInfo, undefined, 2), /*writeByteOrderMark*/ false); + } // Reset state - sourceMap.reset(); + mapRecorder.reset(); writer.clear(); - currentSourceFile = undefined; - bundledHelpers = undefined; - isOwnFileEmit = false; + bundleInfo = createDefaultBundleInfo(); } function setSourceFile(node) { - currentSourceFile = node; sourceMap.setSourceFile(node); } - function emitHelpers(node, writeLines) { - var helpersEmitted = false; - var bundle = node.kind === 273 /* Bundle */ ? node : undefined; - if (bundle && moduleKind === ts.ModuleKind.None) { - return; - } - var numNodes = bundle ? bundle.sourceFiles.length : 1; - for (var i = 0; i < numNodes; i++) { - var currentNode = bundle ? bundle.sourceFiles[i] : node; - var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; - var shouldSkip = compilerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; - var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; - var helpers = ts.getEmitHelpers(currentNode); - if (helpers) { - for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { - var helper = _b[_a]; - if (!helper.scoped) { - // Skip the helper if it can be skipped and the noEmitHelpers compiler - // option is set, or if it can be imported and the importHelpers compiler - // option is set. - if (shouldSkip) - continue; - // Skip the helper if it can be bundled but hasn't already been emitted and we - // are emitting a bundled module. - if (shouldBundle) { - if (bundledHelpers.get(helper.name)) { - continue; - } - bundledHelpers.set(helper.name, true); - } - } - else if (bundle) { - // Skip the helper if it is scoped and we are emitting bundled helpers - continue; - } - writeLines(helper.text); - helpersEmitted = true; - } - } - } - return helpersEmitted; + function setSourceFileForDeclarationSourceMaps(node) { + declarationSourceMap.setSourceFile(node); } } ts.emitFiles = emitFiles; + var PipelinePhase; + (function (PipelinePhase) { + PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification"; + PipelinePhase[PipelinePhase["Comments"] = 1] = "Comments"; + PipelinePhase[PipelinePhase["SourceMaps"] = 2] = "SourceMaps"; + PipelinePhase[PipelinePhase["Emit"] = 3] = "Emit"; + })(PipelinePhase || (PipelinePhase = {})); function createPrinter(printerOptions, handlers) { if (printerOptions === void 0) { printerOptions = {}; } if (handlers === void 0) { handlers = {}; } - var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onEmitHelpers = handlers.onEmitHelpers, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; + var hasGlobalName = handlers.hasGlobalName, onEmitSourceMapOfNode = handlers.onEmitSourceMapOfNode, onEmitSourceMapOfToken = handlers.onEmitSourceMapOfToken, onEmitSourceMapOfPosition = handlers.onEmitSourceMapOfPosition, onEmitNode = handlers.onEmitNode, onSetSourceFile = handlers.onSetSourceFile, substituteNode = handlers.substituteNode, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken; var newLine = ts.getNewLineCharacter(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; @@ -72000,6 +78162,9 @@ var ts; writeSemicolon = deferWriteSemicolon; } var syntheticParent = { pos: -1, end: -1 }; + var moduleKind = ts.getEmitModuleKind(printerOptions); + var bundledHelpers = ts.createMap(); + var isOwnFileEmit; reset(); return { // public API @@ -72026,8 +78191,9 @@ var ts; break; } switch (node.kind) { - case 272 /* SourceFile */: return printFile(node); - case 273 /* Bundle */: return printBundle(node); + case 277 /* SourceFile */: return printFile(node); + case 278 /* Bundle */: return printBundle(node); + case 279 /* UnparsedSource */: return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -72044,6 +78210,10 @@ var ts; writeFile(sourceFile, beginPrint()); return endPrint(); } + function printUnparsedSource(unparsed) { + writeUnparsedSource(unparsed, beginPrint()); + return endPrint(); + } function writeNode(hint, node, sourceFile, output) { var previousWriter = writer; setWriter(output); @@ -72061,20 +78231,38 @@ var ts; reset(); writer = previousWriter; } - function writeBundle(bundle, output) { + function writeBundle(bundle, output, bundleInfo) { + isOwnFileEmit = false; var previousWriter = writer; setWriter(output); emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); - emitHelpersIndirect(bundle); - for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) { - var sourceFile = _b[_a]; + emitHelpers(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); + for (var _a = 0, _b = bundle.prepends; _a < _b.length; _a++) { + var prepend = _b[_a]; + print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined); + writeLine(); + } + if (bundleInfo) { + bundleInfo.originalOffset = writer.getTextPos(); + } + for (var _c = 0, _d = bundle.sourceFiles; _c < _d.length; _c++) { + var sourceFile = _d[_c]; print(0 /* SourceFile */, sourceFile, sourceFile); } reset(); writer = previousWriter; } + function writeUnparsedSource(unparsed, output) { + var previousWriter = writer; + setWriter(output); + print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined); + reset(); + writer = previousWriter; + } function writeFile(sourceFile, output) { + isOwnFileEmit = true; var previousWriter = writer; setWriter(output); emitShebangIfNeeded(sourceFile); @@ -72095,7 +78283,8 @@ var ts; if (sourceFile) { setSourceFile(sourceFile); } - pipelineEmitWithNotification(hint, node); + var pipelinePhase = getPipelinePhase(0 /* Notification */, hint); + pipelinePhase(hint, node); } function setSourceFile(sourceFile) { currentSourceFile = sourceFile; @@ -72105,7 +78294,7 @@ var ts; } } function setWriter(output) { - writer = output; + writer = output; // TODO: GH#18217 comments.setWriter(output); } function reset() { @@ -72118,63 +78307,416 @@ var ts; comments.reset(); setWriter(/*output*/ undefined); } - // TODO: Should this just be `emit`? - // See https://github.com/Microsoft/TypeScript/pull/18284#discussion_r137611034 - function emitIfPresent(node) { - if (node) { - emit(node); - } - } function emit(node) { - pipelineEmitWithNotification(4 /* Unspecified */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 4 /* Unspecified */); + pipelinePhase(4 /* Unspecified */, node); } function emitIdentifierName(node) { - pipelineEmitWithNotification(2 /* IdentifierName */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 2 /* IdentifierName */); + pipelinePhase(2 /* IdentifierName */, node); } function emitExpression(node) { - pipelineEmitWithNotification(1 /* Expression */, node); + if (!node) + return; + var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */); + pipelinePhase(1 /* Expression */, node); + } + function getPipelinePhase(phase, hint) { + switch (phase) { + case 0 /* Notification */: + if (onEmitNode) { + return pipelineEmitWithNotification; + } + // falls through + case 1 /* Comments */: + if (emitNodeWithComments && hint !== 0 /* SourceFile */) { + return pipelineEmitWithComments; + } + return pipelineEmitWithoutComments; + case 2 /* SourceMaps */: + if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */) { + return pipelineEmitWithSourceMap; + } + // falls through + case 3 /* Emit */: + return pipelineEmitWithHint; + default: + return ts.Debug.assertNever(phase, "Unexpected value for PipelinePhase: " + phase); + } + } + function getNextPipelinePhase(currentPhase, hint) { + return getPipelinePhase(currentPhase + 1, hint); } function pipelineEmitWithNotification(hint, node) { - if (onEmitNode) { - onEmitNode(hint, node, pipelineEmitWithComments); - } - else { - pipelineEmitWithComments(hint, node); - } + ts.Debug.assertDefined(onEmitNode)(hint, node, getNextPipelinePhase(0 /* Notification */, hint)); } function pipelineEmitWithComments(hint, node) { - node = trySubstituteNode(hint, node); - if (emitNodeWithComments && hint !== 0 /* SourceFile */) { - emitNodeWithComments(hint, node, pipelineEmitWithSourceMap); - } - else { - pipelineEmitWithSourceMap(hint, node); - } + ts.Debug.assertDefined(emitNodeWithComments); + ts.Debug.assert(hint !== 0 /* SourceFile */); + emitNodeWithComments(hint, trySubstituteNode(hint, node), getNextPipelinePhase(1 /* Comments */, hint)); + } + function pipelineEmitWithoutComments(hint, node) { + var pipelinePhase = getNextPipelinePhase(1 /* Comments */, hint); + pipelinePhase(hint, trySubstituteNode(hint, node)); } function pipelineEmitWithSourceMap(hint, node) { - if (onEmitSourceMapOfNode && hint !== 0 /* SourceFile */ && hint !== 2 /* IdentifierName */) { - onEmitSourceMapOfNode(hint, node, pipelineEmitWithHint); - } - else { - pipelineEmitWithHint(hint, node); - } + ts.Debug.assert(hint !== 0 /* SourceFile */); + ts.Debug.assertDefined(onEmitSourceMapOfNode)(hint, node, pipelineEmitWithHint); } function pipelineEmitWithHint(hint, node) { - switch (hint) { - case 0 /* SourceFile */: return pipelineEmitSourceFile(node); - case 2 /* IdentifierName */: return pipelineEmitIdentifierName(node); - case 1 /* Expression */: return pipelineEmitExpression(node); - case 3 /* MappedTypeParameter */: return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); - case 4 /* Unspecified */: return pipelineEmitUnspecified(node); + if (hint === 0 /* SourceFile */) + return emitSourceFile(ts.cast(node, ts.isSourceFile)); + if (hint === 2 /* IdentifierName */) + return emitIdentifier(ts.cast(node, ts.isIdentifier)); + if (hint === 3 /* MappedTypeParameter */) + return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration)); + if (hint === 4 /* Unspecified */) { + if (ts.isKeyword(node.kind)) + return writeTokenNode(node, writeKeyword); + switch (node.kind) { + // Pseudo-literals + case 14 /* TemplateHead */: + case 15 /* TemplateMiddle */: + case 16 /* TemplateTail */: + return emitLiteral(node); + case 279 /* UnparsedSource */: + return emitUnparsedSource(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Parse tree nodes + // Names + case 146 /* QualifiedName */: + return emitQualifiedName(node); + case 147 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + // Signature elements + case 148 /* TypeParameter */: + return emitTypeParameter(node); + case 149 /* Parameter */: + return emitParameter(node); + case 150 /* Decorator */: + return emitDecorator(node); + // Type members + case 151 /* PropertySignature */: + return emitPropertySignature(node); + case 152 /* PropertyDeclaration */: + return emitPropertyDeclaration(node); + case 153 /* MethodSignature */: + return emitMethodSignature(node); + case 154 /* MethodDeclaration */: + return emitMethodDeclaration(node); + case 155 /* Constructor */: + return emitConstructor(node); + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 158 /* CallSignature */: + return emitCallSignature(node); + case 159 /* ConstructSignature */: + return emitConstructSignature(node); + case 160 /* IndexSignature */: + return emitIndexSignature(node); + // Types + case 161 /* TypePredicate */: + return emitTypePredicate(node); + case 162 /* TypeReference */: + return emitTypeReference(node); + case 163 /* FunctionType */: + return emitFunctionType(node); + case 287 /* JSDocFunctionType */: + return emitJSDocFunctionType(node); + case 164 /* ConstructorType */: + return emitConstructorType(node); + case 165 /* TypeQuery */: + return emitTypeQuery(node); + case 166 /* TypeLiteral */: + return emitTypeLiteral(node); + case 167 /* ArrayType */: + return emitArrayType(node); + case 168 /* TupleType */: + return emitTupleType(node); + case 169 /* OptionalType */: + return emitOptionalType(node); + case 171 /* UnionType */: + return emitUnionType(node); + case 172 /* IntersectionType */: + return emitIntersectionType(node); + case 173 /* ConditionalType */: + return emitConditionalType(node); + case 174 /* InferType */: + return emitInferType(node); + case 175 /* ParenthesizedType */: + return emitParenthesizedType(node); + case 209 /* ExpressionWithTypeArguments */: + return emitExpressionWithTypeArguments(node); + case 176 /* ThisType */: + return emitThisType(); + case 177 /* TypeOperator */: + return emitTypeOperator(node); + case 178 /* IndexedAccessType */: + return emitIndexedAccessType(node); + case 179 /* MappedType */: + return emitMappedType(node); + case 180 /* LiteralType */: + return emitLiteralType(node); + case 181 /* ImportType */: + return emitImportTypeNode(node); + case 282 /* JSDocAllType */: + write("*"); + return; + case 283 /* JSDocUnknownType */: + write("?"); + return; + case 284 /* JSDocNullableType */: + return emitJSDocNullableType(node); + case 285 /* JSDocNonNullableType */: + return emitJSDocNonNullableType(node); + case 286 /* JSDocOptionalType */: + return emitJSDocOptionalType(node); + case 170 /* RestType */: + case 288 /* JSDocVariadicType */: + return emitRestOrJSDocVariadicType(node); + // Binding patterns + case 182 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 183 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 184 /* BindingElement */: + return emitBindingElement(node); + // Misc + case 214 /* TemplateSpan */: + return emitTemplateSpan(node); + case 215 /* SemicolonClassElement */: + return emitSemicolonClassElement(); + // Statements + case 216 /* Block */: + return emitBlock(node); + case 217 /* VariableStatement */: + return emitVariableStatement(node); + case 218 /* EmptyStatement */: + return emitEmptyStatement(); + case 219 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 220 /* IfStatement */: + return emitIfStatement(node); + case 221 /* DoStatement */: + return emitDoStatement(node); + case 222 /* WhileStatement */: + return emitWhileStatement(node); + case 223 /* ForStatement */: + return emitForStatement(node); + case 224 /* ForInStatement */: + return emitForInStatement(node); + case 225 /* ForOfStatement */: + return emitForOfStatement(node); + case 226 /* ContinueStatement */: + return emitContinueStatement(node); + case 227 /* BreakStatement */: + return emitBreakStatement(node); + case 228 /* ReturnStatement */: + return emitReturnStatement(node); + case 229 /* WithStatement */: + return emitWithStatement(node); + case 230 /* SwitchStatement */: + return emitSwitchStatement(node); + case 231 /* LabeledStatement */: + return emitLabeledStatement(node); + case 232 /* ThrowStatement */: + return emitThrowStatement(node); + case 233 /* TryStatement */: + return emitTryStatement(node); + case 234 /* DebuggerStatement */: + return emitDebuggerStatement(node); + // Declarations + case 235 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 236 /* VariableDeclarationList */: + return emitVariableDeclarationList(node); + case 237 /* FunctionDeclaration */: + return emitFunctionDeclaration(node); + case 238 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 239 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 240 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 241 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 242 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 243 /* ModuleBlock */: + return emitModuleBlock(node); + case 244 /* CaseBlock */: + return emitCaseBlock(node); + case 245 /* NamespaceExportDeclaration */: + return emitNamespaceExportDeclaration(node); + case 246 /* ImportEqualsDeclaration */: + return emitImportEqualsDeclaration(node); + case 247 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 248 /* ImportClause */: + return emitImportClause(node); + case 249 /* NamespaceImport */: + return emitNamespaceImport(node); + case 250 /* NamedImports */: + return emitNamedImports(node); + case 251 /* ImportSpecifier */: + return emitImportSpecifier(node); + case 252 /* ExportAssignment */: + return emitExportAssignment(node); + case 253 /* ExportDeclaration */: + return emitExportDeclaration(node); + case 254 /* NamedExports */: + return emitNamedExports(node); + case 255 /* ExportSpecifier */: + return emitExportSpecifier(node); + case 256 /* MissingDeclaration */: + return; + // Module references + case 257 /* ExternalModuleReference */: + return emitExternalModuleReference(node); + // JSX (non-expression) + case 10 /* JsxText */: + return emitJsxText(node); + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: + return emitJsxOpeningElementOrFragment(node); + case 261 /* JsxClosingElement */: + case 264 /* JsxClosingFragment */: + return emitJsxClosingElementOrFragment(node); + case 265 /* JsxAttribute */: + return emitJsxAttribute(node); + case 266 /* JsxAttributes */: + return emitJsxAttributes(node); + case 267 /* JsxSpreadAttribute */: + return emitJsxSpreadAttribute(node); + case 268 /* JsxExpression */: + return emitJsxExpression(node); + // Clauses + case 269 /* CaseClause */: + return emitCaseClause(node); + case 270 /* DefaultClause */: + return emitDefaultClause(node); + case 271 /* HeritageClause */: + return emitHeritageClause(node); + case 272 /* CatchClause */: + return emitCatchClause(node); + // Property assignments + case 273 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 274 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 275 /* SpreadAssignment */: + return emitSpreadAssignment(node); + // Enum + case 276 /* EnumMember */: + return emitEnumMember(node); + // JSDoc nodes (ignored) + // Transformation nodes (ignored) + } + if (ts.isExpression(node)) { + hint = 1 /* Expression */; + node = trySubstituteNode(1 /* Expression */, node); + } + else if (ts.isToken(node)) { + return writeTokenNode(node, writePunctuation); + } + } + if (hint === 1 /* Expression */) { + switch (node.kind) { + // Literals + case 8 /* NumericLiteral */: + return emitNumericLiteral(node); + case 9 /* StringLiteral */: + case 12 /* RegularExpressionLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + return emitLiteral(node); + // Identifiers + case 71 /* Identifier */: + return emitIdentifier(node); + // Reserved words + case 86 /* FalseKeyword */: + case 95 /* NullKeyword */: + case 97 /* SuperKeyword */: + case 101 /* TrueKeyword */: + case 99 /* ThisKeyword */: + case 91 /* ImportKeyword */: + writeTokenNode(node, writeKeyword); + return; + // Expressions + case 185 /* ArrayLiteralExpression */: + return emitArrayLiteralExpression(node); + case 186 /* ObjectLiteralExpression */: + return emitObjectLiteralExpression(node); + case 187 /* PropertyAccessExpression */: + return emitPropertyAccessExpression(node); + case 188 /* ElementAccessExpression */: + return emitElementAccessExpression(node); + case 189 /* CallExpression */: + return emitCallExpression(node); + case 190 /* NewExpression */: + return emitNewExpression(node); + case 191 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 192 /* TypeAssertionExpression */: + return emitTypeAssertionExpression(node); + case 193 /* ParenthesizedExpression */: + return emitParenthesizedExpression(node); + case 194 /* FunctionExpression */: + return emitFunctionExpression(node); + case 195 /* ArrowFunction */: + return emitArrowFunction(node); + case 196 /* DeleteExpression */: + return emitDeleteExpression(node); + case 197 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 198 /* VoidExpression */: + return emitVoidExpression(node); + case 199 /* AwaitExpression */: + return emitAwaitExpression(node); + case 200 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 201 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 202 /* BinaryExpression */: + return emitBinaryExpression(node); + case 203 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 204 /* TemplateExpression */: + return emitTemplateExpression(node); + case 205 /* YieldExpression */: + return emitYieldExpression(node); + case 206 /* SpreadElement */: + return emitSpreadExpression(node); + case 207 /* ClassExpression */: + return emitClassExpression(node); + case 208 /* OmittedExpression */: + return; + case 210 /* AsExpression */: + return emitAsExpression(node); + case 211 /* NonNullExpression */: + return emitNonNullExpression(node); + case 212 /* MetaProperty */: + return emitMetaProperty(node); + // JSX + case 258 /* JsxElement */: + return emitJsxElement(node); + case 259 /* JsxSelfClosingElement */: + return emitJsxSelfClosingElement(node); + case 262 /* JsxFragment */: + return emitJsxFragment(node); + // Transformation nodes + case 305 /* PartiallyEmittedExpression */: + return emitPartiallyEmittedExpression(node); + case 306 /* CommaListExpression */: + return emitCommaList(node); + } } - } - function pipelineEmitSourceFile(node) { - ts.Debug.assertNode(node, ts.isSourceFile); - emitSourceFile(node); - } - function pipelineEmitIdentifierName(node) { - ts.Debug.assertNode(node, ts.isIdentifier); - emitIdentifier(node); } function emitMappedTypeParameter(node) { emit(node.name); @@ -72183,358 +78725,55 @@ var ts; writeSpace(); emit(node.constraint); } - function pipelineEmitUnspecified(node) { - var kind = node.kind; - // Reserved words - // Strict mode reserved words - // Contextual keywords - if (ts.isKeyword(kind)) { - writeTokenNode(node, writeKeyword); - return; - } - switch (kind) { - // Pseudo-literals - case 14 /* TemplateHead */: - case 15 /* TemplateMiddle */: - case 16 /* TemplateTail */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Parse tree nodes - // Names - case 145 /* QualifiedName */: - return emitQualifiedName(node); - case 146 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - // Signature elements - case 147 /* TypeParameter */: - return emitTypeParameter(node); - case 148 /* Parameter */: - return emitParameter(node); - case 149 /* Decorator */: - return emitDecorator(node); - // Type members - case 150 /* PropertySignature */: - return emitPropertySignature(node); - case 151 /* PropertyDeclaration */: - return emitPropertyDeclaration(node); - case 152 /* MethodSignature */: - return emitMethodSignature(node); - case 153 /* MethodDeclaration */: - return emitMethodDeclaration(node); - case 154 /* Constructor */: - return emitConstructor(node); - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 157 /* CallSignature */: - return emitCallSignature(node); - case 158 /* ConstructSignature */: - return emitConstructSignature(node); - case 159 /* IndexSignature */: - return emitIndexSignature(node); - // Types - case 160 /* TypePredicate */: - return emitTypePredicate(node); - case 161 /* TypeReference */: - return emitTypeReference(node); - case 162 /* FunctionType */: - return emitFunctionType(node); - case 280 /* JSDocFunctionType */: - return emitJSDocFunctionType(node); - case 163 /* ConstructorType */: - return emitConstructorType(node); - case 164 /* TypeQuery */: - return emitTypeQuery(node); - case 165 /* TypeLiteral */: - return emitTypeLiteral(node); - case 166 /* ArrayType */: - return emitArrayType(node); - case 167 /* TupleType */: - return emitTupleType(node); - case 168 /* UnionType */: - return emitUnionType(node); - case 169 /* IntersectionType */: - return emitIntersectionType(node); - case 170 /* ConditionalType */: - return emitConditionalType(node); - case 171 /* InferType */: - return emitInferType(node); - case 172 /* ParenthesizedType */: - return emitParenthesizedType(node); - case 205 /* ExpressionWithTypeArguments */: - return emitExpressionWithTypeArguments(node); - case 173 /* ThisType */: - return emitThisType(); - case 174 /* TypeOperator */: - return emitTypeOperator(node); - case 175 /* IndexedAccessType */: - return emitIndexedAccessType(node); - case 176 /* MappedType */: - return emitMappedType(node); - case 177 /* LiteralType */: - return emitLiteralType(node); - case 275 /* JSDocAllType */: - write("*"); - return; - case 276 /* JSDocUnknownType */: - write("?"); - return; - case 277 /* JSDocNullableType */: - return emitJSDocNullableType(node); - case 278 /* JSDocNonNullableType */: - return emitJSDocNonNullableType(node); - case 279 /* JSDocOptionalType */: - return emitJSDocOptionalType(node); - case 281 /* JSDocVariadicType */: - return emitJSDocVariadicType(node); - // Binding patterns - case 178 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 179 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 180 /* BindingElement */: - return emitBindingElement(node); - // Misc - case 209 /* TemplateSpan */: - return emitTemplateSpan(node); - case 210 /* SemicolonClassElement */: - return emitSemicolonClassElement(); - // Statements - case 211 /* Block */: - return emitBlock(node); - case 212 /* VariableStatement */: - return emitVariableStatement(node); - case 213 /* EmptyStatement */: - return emitEmptyStatement(); - case 214 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 215 /* IfStatement */: - return emitIfStatement(node); - case 216 /* DoStatement */: - return emitDoStatement(node); - case 217 /* WhileStatement */: - return emitWhileStatement(node); - case 218 /* ForStatement */: - return emitForStatement(node); - case 219 /* ForInStatement */: - return emitForInStatement(node); - case 220 /* ForOfStatement */: - return emitForOfStatement(node); - case 221 /* ContinueStatement */: - return emitContinueStatement(node); - case 222 /* BreakStatement */: - return emitBreakStatement(node); - case 223 /* ReturnStatement */: - return emitReturnStatement(node); - case 224 /* WithStatement */: - return emitWithStatement(node); - case 225 /* SwitchStatement */: - return emitSwitchStatement(node); - case 226 /* LabeledStatement */: - return emitLabeledStatement(node); - case 227 /* ThrowStatement */: - return emitThrowStatement(node); - case 228 /* TryStatement */: - return emitTryStatement(node); - case 229 /* DebuggerStatement */: - return emitDebuggerStatement(node); - // Declarations - case 230 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 231 /* VariableDeclarationList */: - return emitVariableDeclarationList(node); - case 232 /* FunctionDeclaration */: - return emitFunctionDeclaration(node); - case 233 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 234 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 235 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 236 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 237 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 238 /* ModuleBlock */: - return emitModuleBlock(node); - case 239 /* CaseBlock */: - return emitCaseBlock(node); - case 240 /* NamespaceExportDeclaration */: - return emitNamespaceExportDeclaration(node); - case 241 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 242 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 243 /* ImportClause */: - return emitImportClause(node); - case 244 /* NamespaceImport */: - return emitNamespaceImport(node); - case 245 /* NamedImports */: - return emitNamedImports(node); - case 246 /* ImportSpecifier */: - return emitImportSpecifier(node); - case 247 /* ExportAssignment */: - return emitExportAssignment(node); - case 248 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 249 /* NamedExports */: - return emitNamedExports(node); - case 250 /* ExportSpecifier */: - return emitExportSpecifier(node); - case 251 /* MissingDeclaration */: - return; - // Module references - case 252 /* ExternalModuleReference */: - return emitExternalModuleReference(node); - // JSX (non-expression) - case 10 /* JsxText */: - return emitJsxText(node); - case 255 /* JsxOpeningElement */: - case 258 /* JsxOpeningFragment */: - return emitJsxOpeningElementOrFragment(node); - case 256 /* JsxClosingElement */: - case 259 /* JsxClosingFragment */: - return emitJsxClosingElementOrFragment(node); - case 260 /* JsxAttribute */: - return emitJsxAttribute(node); - case 261 /* JsxAttributes */: - return emitJsxAttributes(node); - case 262 /* JsxSpreadAttribute */: - return emitJsxSpreadAttribute(node); - case 263 /* JsxExpression */: - return emitJsxExpression(node); - // Clauses - case 264 /* CaseClause */: - return emitCaseClause(node); - case 265 /* DefaultClause */: - return emitDefaultClause(node); - case 266 /* HeritageClause */: - return emitHeritageClause(node); - case 267 /* CatchClause */: - return emitCatchClause(node); - // Property assignments - case 268 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 269 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 270 /* SpreadAssignment */: - return emitSpreadAssignment(node); - // Enum - case 271 /* EnumMember */: - return emitEnumMember(node); - // JSDoc nodes (ignored) - // Transformation nodes (ignored) - } - // If the node is an expression, try to emit it as an expression with - // substitution. - if (ts.isExpression(node)) { - return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); - } - if (ts.isToken(node)) { - writeTokenNode(node, writePunctuation); - return; - } - } - function pipelineEmitExpression(node) { - var kind = node.kind; - switch (kind) { - // Literals - case 8 /* NumericLiteral */: - return emitNumericLiteral(node); - case 9 /* StringLiteral */: - case 12 /* RegularExpressionLiteral */: - case 13 /* NoSubstitutionTemplateLiteral */: - return emitLiteral(node); - // Identifiers - case 71 /* Identifier */: - return emitIdentifier(node); - // Reserved words - case 86 /* FalseKeyword */: - case 95 /* NullKeyword */: - case 97 /* SuperKeyword */: - case 101 /* TrueKeyword */: - case 99 /* ThisKeyword */: - case 91 /* ImportKeyword */: - writeTokenNode(node, writeKeyword); - return; - // Expressions - case 181 /* ArrayLiteralExpression */: - return emitArrayLiteralExpression(node); - case 182 /* ObjectLiteralExpression */: - return emitObjectLiteralExpression(node); - case 183 /* PropertyAccessExpression */: - return emitPropertyAccessExpression(node); - case 184 /* ElementAccessExpression */: - return emitElementAccessExpression(node); - case 185 /* CallExpression */: - return emitCallExpression(node); - case 186 /* NewExpression */: - return emitNewExpression(node); - case 187 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 188 /* TypeAssertionExpression */: - return emitTypeAssertionExpression(node); - case 189 /* ParenthesizedExpression */: - return emitParenthesizedExpression(node); - case 190 /* FunctionExpression */: - return emitFunctionExpression(node); - case 191 /* ArrowFunction */: - return emitArrowFunction(node); - case 192 /* DeleteExpression */: - return emitDeleteExpression(node); - case 193 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 194 /* VoidExpression */: - return emitVoidExpression(node); - case 195 /* AwaitExpression */: - return emitAwaitExpression(node); - case 196 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 197 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 198 /* BinaryExpression */: - return emitBinaryExpression(node); - case 199 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 200 /* TemplateExpression */: - return emitTemplateExpression(node); - case 201 /* YieldExpression */: - return emitYieldExpression(node); - case 202 /* SpreadElement */: - return emitSpreadExpression(node); - case 203 /* ClassExpression */: - return emitClassExpression(node); - case 204 /* OmittedExpression */: - return; - case 206 /* AsExpression */: - return emitAsExpression(node); - case 207 /* NonNullExpression */: - return emitNonNullExpression(node); - case 208 /* MetaProperty */: - return emitMetaProperty(node); - // JSX - case 253 /* JsxElement */: - return emitJsxElement(node); - case 254 /* JsxSelfClosingElement */: - return emitJsxSelfClosingElement(node); - case 257 /* JsxFragment */: - return emitJsxFragment(node); - // Transformation nodes - case 295 /* PartiallyEmittedExpression */: - return emitPartiallyEmittedExpression(node); - case 296 /* CommaListExpression */: - return emitCommaList(node); - } - } function trySubstituteNode(hint, node) { return node && substituteNode && substituteNode(hint, node) || node; } - function emitHelpersIndirect(node) { - if (onEmitHelpers) { - onEmitHelpers(node, writeLines); + function emitHelpers(node) { + var helpersEmitted = false; + var bundle = node.kind === 278 /* Bundle */ ? node : undefined; + if (bundle && moduleKind === ts.ModuleKind.None) { + return; } + var numNodes = bundle ? bundle.sourceFiles.length : 1; + for (var i = 0; i < numNodes; i++) { + var currentNode = bundle ? bundle.sourceFiles[i] : node; + var sourceFile = ts.isSourceFile(currentNode) ? currentNode : currentSourceFile; + var shouldSkip = printerOptions.noEmitHelpers || ts.getExternalHelpersModuleName(sourceFile) !== undefined; + var shouldBundle = ts.isSourceFile(currentNode) && !isOwnFileEmit; + var helpers = ts.getEmitHelpers(currentNode); + if (helpers) { + for (var _a = 0, _b = ts.stableSort(helpers, ts.compareEmitHelpers); _a < _b.length; _a++) { + var helper = _b[_a]; + if (!helper.scoped) { + // Skip the helper if it can be skipped and the noEmitHelpers compiler + // option is set, or if it can be imported and the importHelpers compiler + // option is set. + if (shouldSkip) + continue; + // Skip the helper if it can be bundled but hasn't already been emitted and we + // are emitting a bundled module. + if (shouldBundle) { + if (bundledHelpers.get(helper.name)) { + continue; + } + bundledHelpers.set(helper.name, true); + } + } + else if (bundle) { + // Skip the helper if it is scoped and we are emitting bundled helpers + continue; + } + if (typeof helper.text === "string") { + writeLines(helper.text); + } + else { + writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + } + helpersEmitted = true; + } + } + } + return helpersEmitted; } // // Literals/Pseudo-literals @@ -72560,6 +78799,10 @@ var ts; writeStringLiteral(text); } } + // SyntaxKind.UnparsedSource + function emitUnparsedSource(unparsed) { + writer.rawWrite(unparsed.text); + } // // Identifiers // @@ -72610,12 +78853,10 @@ var ts; function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.dotDotDotToken); - if (node.name) { - emitNodeWithWriter(node.name, writeParameter); - } - emitIfPresent(node.questionToken); - if (node.parent && node.parent.kind === 280 /* JSDocFunctionType */ && !node.name) { + emit(node.dotDotDotToken); + emitNodeWithWriter(node.name, writeParameter); + emit(node.questionToken); + if (node.parent && node.parent.kind === 287 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { @@ -72635,7 +78876,7 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitNodeWithWriter(node.name, writeProperty); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeAnnotation(node.type); writeSemicolon(); } @@ -72643,28 +78884,30 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); - emitIfPresent(node.exclamationToken); + emit(node.questionToken); + emit(node.exclamationToken); emitTypeAnnotation(node.type); emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node); writeSemicolon(); } function emitMethodSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); emit(node.name); - emitIfPresent(node.questionToken); + emit(node.questionToken); emitSignatureAndBody(node, emitSignatureHead); } function emitConstructor(node) { @@ -72675,20 +78918,23 @@ var ts; function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - writeKeyword(node.kind === 155 /* GetAccessor */ ? "get" : "set"); + writeKeyword(node.kind === 156 /* GetAccessor */ ? "get" : "set"); writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } function emitCallSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitConstructSignature(node) { + pushNameGenerationScope(node); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("new"); @@ -72697,6 +78943,7 @@ var ts; emitParameters(node, node.parameters); emitTypeAnnotation(node.type); writeSemicolon(); + popNameGenerationScope(node); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); @@ -72723,12 +78970,14 @@ var ts; emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { + pushNameGenerationScope(node); emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); writeSpace(); emit(node.type); + popNameGenerationScope(node); } function emitJSDocFunctionType(node) { write("function"); @@ -72749,6 +78998,7 @@ var ts; write("="); } function emitConstructorType(node) { + pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); emitTypeParameters(node, node.typeParameters); @@ -72757,6 +79007,7 @@ var ts; writePunctuation("=>"); writeSpace(); emit(node.type); + popNameGenerationScope(node); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -72765,7 +79016,7 @@ var ts; } function emitTypeLiteral(node) { writePunctuation("{"); - var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; + var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineTypeLiteralMembers */ : 16449 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); writePunctuation("}"); } @@ -72774,15 +79025,19 @@ var ts; writePunctuation("["); writePunctuation("]"); } - function emitJSDocVariadicType(node) { + function emitRestOrJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { writePunctuation("["); - emitList(node, node.elementTypes, 336 /* TupleTypeElements */); + emitList(node, node.elementTypes, 272 /* TupleTypeElements */); writePunctuation("]"); } + function emitOptionalType(node) { + emit(node.type); + write("?"); + } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); } @@ -72846,7 +79101,8 @@ var ts; writeSpace(); } writePunctuation("["); - pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); + var pipelinePhase = getPipelinePhase(0 /* Notification */, 3 /* MappedTypeParameter */); + pipelinePhase(3 /* MappedTypeParameter */, node.typeParameter); writePunctuation("]"); if (node.questionToken) { emit(node.questionToken); @@ -72870,6 +79126,21 @@ var ts; function emitLiteralType(node) { emitExpression(node.literal); } + function emitImportTypeNode(node) { + if (node.isTypeOf) { + writeKeyword("typeof"); + writeSpace(); + } + writeKeyword("import"); + writePunctuation("("); + emit(node.argument); + writePunctuation(")"); + if (node.qualifier) { + writePunctuation("."); + emit(node.qualifier); + } + emitTypeArguments(node, node.typeArguments); + } // // Binding patterns // @@ -72884,7 +79155,7 @@ var ts; writePunctuation("]"); } function emitBindingElement(node) { - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); if (node.propertyName) { emit(node.propertyName); writePunctuation(":"); @@ -72902,12 +79173,13 @@ var ts; emitExpressionList(node, elements, 4466 /* ArrayLiteralExpressionElements */ | preferNewLine); } function emitObjectLiteralExpression(node) { + ts.forEach(node.properties, generateMemberNames); var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } var preferNewLine = node.multiLine ? 32768 /* PreferNewLine */ : 0 /* None */; - var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ ? 32 /* AllowTrailingComma */ : 0 /* None */; + var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 32 /* AllowTrailingComma */ : 0 /* None */; emitList(node, node.properties, 263122 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine); if (indentedFlag) { decreaseIndent(); @@ -72957,9 +79229,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - var openPos = emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); + emitTokenWithComment(21 /* OpenBracketToken */, node.expression.end, writePunctuation, node); emitExpression(node.argumentExpression); - emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression ? node.argumentExpression.end : openPos, writePunctuation, node); + emitTokenWithComment(22 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node); } function emitCallExpression(node) { emitExpression(node.expression); @@ -72975,6 +79247,7 @@ var ts; } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); + emitTypeArguments(node, node.typeArguments); writeSpace(); emitExpression(node.template); } @@ -72990,6 +79263,7 @@ var ts; emitTokenWithComment(20 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node); } function emitFunctionExpression(node) { + generateNameIfNeeded(node.name); emitFunctionDeclarationOrExpression(node); } function emitArrowFunction(node) { @@ -73045,7 +79319,7 @@ var ts; // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. var operand = node.operand; - return operand.kind === 196 /* PrefixUnaryExpression */ + return operand.kind === 200 /* PrefixUnaryExpression */ && ((node.operator === 37 /* PlusToken */ && (operand.operator === 37 /* PlusToken */ || operand.operator === 43 /* PlusPlusToken */)) || (node.operator === 38 /* MinusToken */ && (operand.operator === 38 /* MinusToken */ || operand.operator === 44 /* MinusMinusToken */))); } @@ -73097,6 +79371,7 @@ var ts; emitExpression(node.expression); } function emitClassExpression(node) { + generateNameIfNeeded(node.name); emitClassDeclarationOrExpression(node); } function emitExpressionWithTypeArguments(node) { @@ -73150,7 +79425,9 @@ var ts; } function emitExpressionStatement(node) { emitExpression(node.expression); - writeSemicolon(); + if (!ts.isJsonSourceFile(currentSourceFile)) { + writeSemicolon(); + } } function emitIfStatement(node) { var openParenPos = emitTokenWithComment(90 /* IfKeyword */, node.pos, writeKeyword, node); @@ -73162,7 +79439,7 @@ var ts; if (node.elseStatement) { writeLineOrSpace(node); emitTokenWithComment(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); - if (node.elseStatement.kind === 215 /* IfStatement */) { + if (node.elseStatement.kind === 220 /* IfStatement */) { writeSpace(); emit(node.elseStatement); } @@ -73225,7 +79502,7 @@ var ts; emitTokenWithComment(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitForBinding(node.initializer); writeSpace(); - emitTokenWithComment(144 /* OfKeyword */, node.initializer.end, writeKeyword, node); + emitTokenWithComment(145 /* OfKeyword */, node.initializer.end, writeKeyword, node); writeSpace(); emitExpression(node.expression); emitTokenWithComment(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); @@ -73233,7 +79510,7 @@ var ts; } function emitForBinding(node) { if (node !== undefined) { - if (node.kind === 231 /* VariableDeclarationList */) { + if (node.kind === 236 /* VariableDeclarationList */) { emit(node); } else { @@ -73252,13 +79529,13 @@ var ts; writeSemicolon(); } function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) { - var node = contextNode && ts.getParseTreeNode(contextNode); + var node = ts.getParseTreeNode(contextNode); var isSimilarNode = node && node.kind === contextNode.kind; var startPos = pos; if (isSimilarNode) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - if (emitLeadingCommentsOfPosition && isSimilarNode) { + if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) { var needsIndent = indentLeading && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile); if (needsIndent) { increaseIndent(); @@ -73269,7 +79546,7 @@ var ts; } } pos = writeTokenText(token, writer, pos); - if (emitTrailingCommentsOfPosition && isSimilarNode) { + if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; @@ -73335,7 +79612,7 @@ var ts; emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node); } function emitVariableDeclarationList(node) { - writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var"); writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } @@ -73346,9 +79623,9 @@ var ts; emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("function"); - emitIfPresent(node.asteriskToken); + emit(node.asteriskToken); writeSpace(); - emitIdentifierName(node.name); + emitIdentifierName(node.name); // TODO: GH#18217 emitSignatureAndBody(node, emitSignatureHead); } function emitBlockCallback(_hint, body) { @@ -73363,6 +79640,8 @@ var ts; increaseIndent(); } pushNameGenerationScope(node); + ts.forEach(node.parameters, generateNames); + generateNames(node.body); emitSignatureHead(node); if (onEmitNode) { onEmitNode(4 /* Unspecified */, body, emitBlockCallback); @@ -73444,7 +79723,7 @@ var ts; // Emit all the prologue directives (like "use strict"). var statementOffset = emitPrologueDirectives(body.statements, /*startWithNewLine*/ true); var pos = writer.getTextPos(); - emitHelpersIndirect(body); + emitHelpers(body); if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) { decreaseIndent(); emitList(body, body.statements, 384 /* SingleLineFunctionBodyStatements */); @@ -73458,6 +79737,7 @@ var ts; emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { + ts.forEach(node.members, generateMemberNames); emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); writeKeyword("class"); @@ -73470,7 +79750,7 @@ var ts; increaseIndent(); } emitTypeParameters(node, node.typeParameters); - emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); + emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); @@ -73523,7 +79803,9 @@ var ts; } emit(node.name); var body = node.body; - while (body.kind === 237 /* ModuleDeclaration */) { + if (!body) + return writeSemicolon(); + while (body.kind === 242 /* ModuleDeclaration */) { writePunctuation("."); emit(body.name); body = body.body; @@ -73533,6 +79815,7 @@ var ts; } function emitModuleBlock(node) { pushNameGenerationScope(node); + ts.forEach(node.statements, generateNames); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); popNameGenerationScope(node); } @@ -73567,7 +79850,7 @@ var ts; if (node.importClause) { emit(node.importClause); writeSpace(); - emitTokenWithComment(142 /* FromKeyword */, node.importClause.end, writeKeyword, node); + emitTokenWithComment(143 /* FromKeyword */, node.importClause.end, writeKeyword, node); writeSpace(); } emitExpression(node.moduleSpecifier); @@ -73619,7 +79902,7 @@ var ts; if (node.moduleSpecifier) { writeSpace(); var fromPos = node.exportClause ? node.exportClause.end : nextPos; - emitTokenWithComment(142 /* FromKeyword */, fromPos, writeKeyword, node); + emitTokenWithComment(143 /* FromKeyword */, fromPos, writeKeyword, node); writeSpace(); emitExpression(node.moduleSpecifier); } @@ -73643,7 +79926,7 @@ var ts; } function emitNamedImportsOrExports(node) { writePunctuation("{"); - emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); + emitList(node, node.elements, 262576 /* NamedImportsOrExportsElements */); writePunctuation("}"); } function emitImportOrExportSpecifier(node) { @@ -73676,10 +79959,7 @@ var ts; writePunctuation("<"); emitJsxTagName(node.tagName); writeSpace(); - // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap - if (node.attributes.properties && node.attributes.properties.length > 0) { - emit(node.attributes); - } + emit(node.attributes); writePunctuation("/>"); } function emitJsxFragment(node) { @@ -73691,11 +79971,10 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); - // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); - emit(node.attributes); } + emit(node.attributes); } writePunctuation(">"); } @@ -73715,7 +79994,7 @@ var ts; } function emitJsxAttribute(node) { emit(node.name); - emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); // TODO: GH#18217 } function emitJsxSpreadAttribute(node) { writePunctuation("{..."); @@ -73725,7 +80004,7 @@ var ts; function emitJsxExpression(node) { if (node.expression) { writePunctuation("{"); - emitIfPresent(node.dotDotDotToken); + emit(node.dotDotDotToken); emitExpression(node.expression); writePunctuation("}"); } @@ -73848,11 +80127,52 @@ var ts; } emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node) { + emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + function emitTripleSlashDirectivesIfNeeded(node) { + if (node.isDeclarationFile) + emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives); + } + function emitTripleSlashDirectives(hasNoDefaultLib, files, types) { + if (hasNoDefaultLib) { + write("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.moduleName) { + write("/// "); + writeLine(); + } + if (currentSourceFile && currentSourceFile.amdDependencies) { + for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) { + var dep = _b[_a]; + if (dep.name) { + write("/// "); + } + else { + write("/// "); + } + writeLine(); + } + } + for (var _c = 0, files_1 = files; _c < files_1.length; _c++) { + var directive = files_1[_c]; + write("/// "); + writeLine(); + } + for (var _d = 0, types_17 = types; _d < types_17.length; _d++) { + var directive = types_17[_d]; + write("/// "); + writeLine(); + } + } function emitSourceFileWorker(node) { var statements = node.statements; pushNameGenerationScope(node); - emitHelpersIndirect(node); + ts.forEach(node.statements, generateNames); + emitHelpers(node); var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); }); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -73926,6 +80246,8 @@ var ts; // Helpers // function emitNodeWithWriter(node, writer) { + if (!node) + return; var savedWrite = write; write = writer; emit(node); @@ -74034,7 +80356,7 @@ var ts; emitNodeList(emit, parentNode, children, format, start, count); } function emitExpressionList(parentNode, children, format, start, count) { - emitNodeList(emitExpression, parentNode, children, format, start, count); + emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217 } function writeDelimiter(format) { switch (format & 28 /* DelimitersMask */) { @@ -74060,7 +80382,7 @@ var ts; if (isUndefined && format & 8192 /* OptionalIfUndefined */) { return; } - var isEmpty = isUndefined || start >= children.length || count === 0; + var isEmpty = children === undefined || start >= children.length || count === 0; if (isEmpty && format & 16384 /* OptionalIfEmpty */) { if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -74072,7 +80394,8 @@ var ts; } if (format & 7680 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); - if (isEmpty) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -74092,7 +80415,7 @@ var ts; // Write the opening line terminator or leading whitespace. var mayEmitInterveningComments = (format & 131072 /* NoInterveningComments */) === 0; var shouldEmitInterveningComments = mayEmitInterveningComments; - if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { + if (shouldWriteLeadingLineTerminator(parentNode, children, format)) { // TODO: GH#18217 writeLine(); shouldEmitInterveningComments = false; } @@ -74105,7 +80428,7 @@ var ts; } // Emit each child. var previousSibling = void 0; - var shouldDecreaseIndentAfterEmit = void 0; + var shouldDecreaseIndentAfterEmit = false; for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -74182,7 +80505,8 @@ var ts; onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - if (isEmpty) { + if (isEmpty && !isUndefined) { + // TODO: GH#18217 emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -74281,9 +80605,9 @@ var ts; } function writeLines(text) { var lines = text.split(/\r\n?|\n/g); - var indentation = guessIndentation(lines); - for (var _a = 0, lines_1 = lines; _a < lines_1.length; _a++) { - var lineText = lines_1[_a]; + var indentation = ts.guessIndentation(lines); + for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { + var lineText = lines_2[_a]; var line = indentation ? lineText.slice(indentation) : lineText; if (line.length) { writeLine(); @@ -74292,21 +80616,6 @@ var ts; } } } - function guessIndentation(lines) { - var indentation; - for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) { - var line = lines_2[_a]; - for (var i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { - if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) { - if (indentation === undefined || i < indentation) { - indentation = i; - break; - } - } - } - } - return indentation; - } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { increaseIndent(); @@ -74421,7 +80730,7 @@ var ts; && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function skipSynthesizedParentheses(node) { - while (node.kind === 189 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { + while (node.kind === 193 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) { node = node.expression; } return node; @@ -74430,7 +80739,7 @@ var ts; if (ts.isGeneratedIdentifier(node)) { return generateName(node); } - else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent)) { + else if (ts.isIdentifier(node) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) { return ts.idText(node); } else if (node.kind === 9 /* StringLiteral */ && node.textSourceNode) { @@ -74482,6 +80791,113 @@ var ts; } reservedNames.set(name, true); } + function generateNames(node) { + if (!node) + return; + switch (node.kind) { + case 216 /* Block */: + ts.forEach(node.statements, generateNames); + break; + case 231 /* LabeledStatement */: + case 229 /* WithStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + generateNames(node.statement); + break; + case 220 /* IfStatement */: + generateNames(node.thenStatement); + generateNames(node.elseStatement); + break; + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: + generateNames(node.initializer); + generateNames(node.statement); + break; + case 230 /* SwitchStatement */: + generateNames(node.caseBlock); + break; + case 244 /* CaseBlock */: + ts.forEach(node.clauses, generateNames); + break; + case 269 /* CaseClause */: + case 270 /* DefaultClause */: + ts.forEach(node.statements, generateNames); + break; + case 233 /* TryStatement */: + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); + break; + case 272 /* CatchClause */: + generateNames(node.variableDeclaration); + generateNames(node.block); + break; + case 217 /* VariableStatement */: + generateNames(node.declarationList); + break; + case 236 /* VariableDeclarationList */: + ts.forEach(node.declarations, generateNames); + break; + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: + case 184 /* BindingElement */: + case 238 /* ClassDeclaration */: + generateNameIfNeeded(node.name); + break; + case 237 /* FunctionDeclaration */: + generateNameIfNeeded(node.name); + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { + ts.forEach(node.parameters, generateNames); + generateNames(node.body); + } + break; + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + ts.forEach(node.elements, generateNames); + break; + case 247 /* ImportDeclaration */: + generateNames(node.importClause); + break; + case 248 /* ImportClause */: + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); + break; + case 249 /* NamespaceImport */: + generateNameIfNeeded(node.name); + break; + case 250 /* NamedImports */: + ts.forEach(node.elements, generateNames); + break; + case 251 /* ImportSpecifier */: + generateNameIfNeeded(node.propertyName || node.name); + break; + } + } + function generateMemberNames(node) { + if (!node) + return; + switch (node.kind) { + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + generateNameIfNeeded(node.name); + break; + } + } + function generateNameIfNeeded(name) { + if (name) { + if (ts.isGeneratedIdentifier(name)) { + generateName(name); + } + else if (ts.isBindingPattern(name)) { + generateNames(name); + } + } + } /** * Generate the text for a generated identifier. */ @@ -74489,17 +80905,7 @@ var ts; if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) { // Node names generate unique names based on their original node // and are cached based on that node's id. - if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { - var savedTempFlags = tempFlags; - popNameGenerationScope(/*node*/ undefined); - var result = generateNameCached(getNodeForGeneratedName(name)); - pushNameGenerationScope(/*node*/ undefined); - tempFlags = savedTempFlags; - return result; - } - else { - return generateNameCached(getNodeForGeneratedName(name)); - } + return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags); } else { // Auto, Loop, and Unique names are cached based on their unique @@ -74508,20 +80914,25 @@ var ts; return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name)); } } - function generateNameCached(node) { + function generateNameCached(node, flags) { var nodeId = ts.getNodeId(node); - return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node)); + return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags)); } /** * Returns a value indicating whether a name is unique globally, within the current file, * or within the NameGenerator. */ function isUniqueName(name) { - return !(hasGlobalName && hasGlobalName(name)) - && !currentSourceFile.identifiers.has(name) + return isFileLevelUniqueName(name) && !generatedNames.has(name) && !(reservedNames && reservedNames.has(name)); } + /** + * Returns a value indicating whether a name is unique globally or within the current file. + */ + function isFileLevelUniqueName(name) { + return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; + } /** * Returns a value indicating whether a name is unique within a container. */ @@ -74575,8 +80986,21 @@ var ts; * in global scope. The name is formed by adding an '_n' suffix to the specified base name, * where n is a positive integer. Note that names generated by makeTempVariableName and * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName) { + function makeUniqueName(baseName, checkFn, optimistic, scoped) { + if (checkFn === void 0) { checkFn = isUniqueName; } + if (optimistic) { + if (checkFn(baseName)) { + if (scoped) { + reserveNameInNestedScopes(baseName); + } + else { + generatedNames.set(baseName, true); + } + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { baseName += "_"; @@ -74584,13 +81008,21 @@ var ts; var i = 1; while (true) { var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - generatedNames.set(generatedName, true); + if (checkFn(generatedName)) { + if (scoped) { + reserveNameInNestedScopes(generatedName); + } + else { + generatedNames.set(generatedName, true); + } return generatedName; } i++; } } + function makeFileLevelOptmiisticUniqueName(name) { + return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); + } /** * Generates a unique name for a ModuleDeclaration or EnumDeclaration. */ @@ -74603,7 +81035,7 @@ var ts; * Generates a unique name for an ImportDeclaration or ExportDeclaration. */ function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); + var expr = ts.getExternalModuleName(node); // TODO: GH#18217 var baseName = ts.isStringLiteral(expr) ? ts.makeIdentifierFromModuleName(expr.text) : "module"; return makeUniqueName(baseName); @@ -74629,25 +81061,25 @@ var ts; /** * Generates a unique name from a node. */ - function generateNameForNode(node) { + function generateNameForNode(node, flags) { switch (node.kind) { case 71 /* Identifier */: - return makeUniqueName(getTextOfNode(node)); - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: + return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */)); + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: return generateNameForModuleOrEnum(node); - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: return generateNameForImportOrExportDeclaration(node); - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: - case 247 /* ExportAssignment */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 252 /* ExportAssignment */: return generateNameForExportDefault(); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: return generateNameForClassExpression(); - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return generateNameForMethodOrAccessor(node); default: return makeTempVariableName(0 /* Auto */); @@ -74659,13 +81091,13 @@ var ts; function makeName(name) { switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); case 3 /* Unique */: - return makeUniqueName(ts.idText(name)); + return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */)); } - ts.Debug.fail("Unsupported GeneratedIdentifierKind."); + return ts.Debug.fail("Unsupported GeneratedIdentifierKind."); } /** * Gets the node from which a name should be generated. @@ -74679,7 +81111,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateFlags === 4 /* Node */ + && !!(node.autoGenerateFlags & 4 /* Node */) && node.autoGenerateId !== autoGenerateId) { break; } @@ -74712,2788 +81144,6 @@ var ts; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); })(ts || (ts = {})); -/// -/// -/// -var ts; -(function (ts) { - var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; - function findConfigFile(searchPath, fileExists, configName) { - if (configName === void 0) { configName = "tsconfig.json"; } - return ts.forEachAncestorDirectory(searchPath, function (ancestor) { - var fileName = ts.combinePaths(ancestor, configName); - return fileExists(fileName) ? fileName : undefined; - }); - } - ts.findConfigFile = findConfigFile; - function resolveTripleslashReference(moduleName, containingFile) { - var basePath = ts.getDirectoryPath(containingFile); - var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); - return ts.normalizePath(referencedFileName); - } - ts.resolveTripleslashReference = resolveTripleslashReference; - /* @internal */ - function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { - var commonPathComponents; - var failed = ts.forEach(fileNames, function (sourceFile) { - // Each file contributes into common source file path - var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); - sourcePathComponents.pop(); // The base file name is not part of the common directory path - if (!commonPathComponents) { - // first file - commonPathComponents = sourcePathComponents; - return; - } - var n = Math.min(commonPathComponents.length, sourcePathComponents.length); - for (var i = 0; i < n; i++) { - if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { - if (i === 0) { - // Failed to find any common path component - return true; - } - // New common path found that is 0 -> i-1 - commonPathComponents.length = i; - break; - } - } - // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents - if (sourcePathComponents.length < commonPathComponents.length) { - commonPathComponents.length = sourcePathComponents.length; - } - }); - // A common path can not be found when paths span multiple drives on windows, for example - if (failed) { - return ""; - } - if (!commonPathComponents) { // Can happen when all input files are .d.ts files - return currentDirectory; - } - return ts.getNormalizedPathFromPathComponents(commonPathComponents); - } - ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function createCompilerHost(options, setParentNodes) { - var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } - function getSourceFile(fileName, languageVersion, onError) { - var text; - try { - ts.performance.mark("beforeIORead"); - text = ts.sys.readFile(fileName, options.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - text = ""; - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; - } - function directoryExists(directoryPath) { - if (existingDirectories.has(directoryPath)) { - return true; - } - if (ts.sys.directoryExists(directoryPath)) { - existingDirectories.set(directoryPath, true); - return true; - } - return false; - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); - } - } - var outputFingerprints; - function writeFileIfUpdated(fileName, data, writeByteOrderMark) { - if (!outputFingerprints) { - outputFingerprints = ts.createMap(); - } - var hash = ts.sys.createHash(data); - var mtimeBefore = ts.sys.getModifiedTime(fileName); - if (mtimeBefore) { - var fingerprint = outputFingerprints.get(fileName); - // If output has not been changed, and the file has no external modification - if (fingerprint && - fingerprint.byteOrderMark === writeByteOrderMark && - fingerprint.hash === hash && - fingerprint.mtime.getTime() === mtimeBefore.getTime()) { - return; - } - } - ts.sys.writeFile(fileName, data, writeByteOrderMark); - var mtimeAfter = ts.sys.getModifiedTime(fileName); - outputFingerprints.set(fileName, { - hash: hash, - byteOrderMark: writeByteOrderMark, - mtime: mtimeAfter - }); - } - function writeFile(fileName, data, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { - writeFileIfUpdated(fileName, data, writeByteOrderMark); - } - else { - ts.sys.writeFile(fileName, data, writeByteOrderMark); - } - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); - } - var newLine = ts.getNewLineCharacter(options); - var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); - return { - getSourceFile: getSourceFile, - getDefaultLibLocation: getDefaultLibLocation, - getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, - writeFile: writeFile, - getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, - readFile: function (fileName) { return ts.sys.readFile(fileName); }, - trace: function (s) { return ts.sys.write(s + newLine); }, - directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return ts.sys.getDirectories(path); }, - realpath: realpath - }; - } - ts.createCompilerHost = createCompilerHost; - function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (program.getCompilerOptions().declaration) { - ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); - } - return ts.sortAndDeduplicateDiagnostics(diagnostics); - } - ts.getPreEmitDiagnostics = getPreEmitDiagnostics; - function formatDiagnostics(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { - var diagnostic = diagnostics_1[_i]; - output += formatDiagnostic(diagnostic, host); - } - return output; - } - ts.formatDiagnostics = formatDiagnostics; - function formatDiagnostic(diagnostic, host) { - var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); - if (diagnostic.file) { - var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; - var fileName = diagnostic.file.fileName; - var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); - return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; - } - return errorMessage; - } - ts.formatDiagnostic = formatDiagnostic; - /** @internal */ - var ForegroundColorEscapeSequences; - (function (ForegroundColorEscapeSequences) { - ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; - ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; - ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; - ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; - ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; - })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); - var gutterStyleSequence = "\u001b[30;47m"; - var gutterSeparator = " "; - var resetEscapeSequence = "\u001b[0m"; - var ellipsis = "..."; - function getCategoryFormat(category) { - switch (category) { - case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; - case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; - case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); - case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; - } - } - /** @internal */ - function formatColorAndReset(text, formatStyle) { - return formatStyle + text + resetEscapeSequence; - } - ts.formatColorAndReset = formatColorAndReset; - function padLeft(s, length) { - while (s.length < length) { - s = " " + s; - } - return s; - } - function formatDiagnosticsWithColorAndContext(diagnostics, host) { - var output = ""; - for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { - var diagnostic = diagnostics_2[_i]; - var context = ""; - if (diagnostic.file) { - var start = diagnostic.start, length_4 = diagnostic.length, file = diagnostic.file; - var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; - var _b = ts.getLineAndCharacterOfPosition(file, start + length_4), lastLine = _b.line, lastLineChar = _b.character; - var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; - var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; - var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; - var gutterWidth = (lastLine + 1 + "").length; - if (hasMoreThanFiveLines) { - gutterWidth = Math.max(ellipsis.length, gutterWidth); - } - for (var i = firstLine; i <= lastLine; i++) { - context += host.getNewLine(); - // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, - // so we'll skip ahead to the second-to-last line. - if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { - context += formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); - i = lastLine - 1; - } - var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); - var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; - var lineContent = file.text.slice(lineStart, lineEnd); - lineContent = lineContent.replace(/\s+$/g, ""); // trim from end - lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces - // Output the gutter and the actual contents of the line. - context += formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += lineContent + host.getNewLine(); - // Output the gutter and the error span for the line using tildes. - context += formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; - context += ForegroundColorEscapeSequences.Red; - if (i === firstLine) { - // If we're on the last line, then limit it to the last character of the last line. - // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. - var lastCharForLine = i === lastLine ? lastLineChar : undefined; - context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); - context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); - } - else if (i === lastLine) { - context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); - } - else { - // Squiggle the entire line. - context += lineContent.replace(/./g, "~"); - } - context += resetEscapeSequence; - } - output += formatColorAndReset(relativeFileName, ForegroundColorEscapeSequences.Cyan); - output += ":"; - output += formatColorAndReset("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); - output += ":"; - output += formatColorAndReset("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); - output += " - "; - } - output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); - output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); - output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); - if (diagnostic.file) { - output += host.getNewLine(); - output += context; - } - output += host.getNewLine(); - } - return output + host.getNewLine(); - } - ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; - function flattenDiagnosticMessageText(messageText, newLine) { - if (ts.isString(messageText)) { - return messageText; - } - else { - var diagnosticChain = messageText; - var result = ""; - var indent = 0; - while (diagnosticChain) { - if (indent) { - result += newLine; - for (var i = 0; i < indent; i++) { - result += " "; - } - } - result += diagnosticChain.messageText; - indent++; - diagnosticChain = diagnosticChain.next; - } - return result; - } - } - ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { - if (names.length === 0) { - return []; - } - var resolutions = []; - var cache = ts.createMap(); - for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name = names_1[_i]; - var result = void 0; - if (cache.has(name)) { - result = cache.get(name); - } - else { - cache.set(name, result = loader(name, containingFile)); - } - resolutions.push(result); - } - return resolutions; - } - /** - * Determines if program structure is upto date or needs to be recreated - */ - /* @internal */ - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { - // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date - if (!program || hasChangedAutomaticTypeDirectiveNames) { - return false; - } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { - return false; - } - // If any file is not up-to-date, then the whole program is not up-to-date - if (program.getSourceFiles().some(sourceFileNotUptoDate)) { - return false; - } - // If any of the missing file paths are now created - if (program.getMissingFilePaths().some(fileExists)) { - return false; - } - var currentOptions = program.getCompilerOptions(); - // If the compilation settings do no match, then the program is not up-to-date - if (!ts.compareDataObjects(currentOptions, newOptions)) { - return false; - } - // If everything matches but the text of config file is changed, - // error locations can change for program options, so update the program - if (currentOptions.configFile && newOptions.configFile) { - return currentOptions.configFile.text === newOptions.configFile.text; - } - return true; - function sourceFileNotUptoDate(sourceFile) { - return sourceFile.version !== getSourceVersion(sourceFile.path) || - hasInvalidatedResolution(sourceFile.path); - } - } - ts.isProgramUptoDate = isProgramUptoDate; - /** - * Determined if source file needs to be re-created even if its text hasn't changed - */ - function shouldProgramCreateNewSourceFiles(program, newOptions) { - // If any of these options change, we can't reuse old source file even if version match - // The change in options like these could result in change in syntax tree change - var oldOptions = program && program.getCompilerOptions(); - return oldOptions && (oldOptions.target !== newOptions.target || - oldOptions.module !== newOptions.module || - oldOptions.moduleResolution !== newOptions.moduleResolution || - oldOptions.noResolve !== newOptions.noResolve || - oldOptions.jsx !== newOptions.jsx || - oldOptions.allowJs !== newOptions.allowJs || - oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || - oldOptions.baseUrl !== newOptions.baseUrl || - !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); - } - /** - * Create a new 'Program' instance. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' - * that represent a compilation unit. - * - * Creating a program proceeds from a set of root files, expanding the set of inputs by following imports and - * triple-slash-reference-path directives transitively. '@types' and triple-slash-reference-types are also pulled in. - * - * @param rootNames - A set of root files. - * @param options - The compiler options which should be used. - * @param host - The host interacts with the underlying file system. - * @param oldProgram - Reuses an old program structure. - * @returns A 'Program' object. - */ - function createProgram(rootNames, options, host, oldProgram) { - var program; - var files = []; - var commonSourceDirectory; - var diagnosticsProducingTypeChecker; - var noDiagnosticsTypeChecker; - var classifiableNames; - var modifiedFilePaths; - var cachedSemanticDiagnosticsForFile = {}; - var cachedDeclarationDiagnosticsForFile = {}; - var resolvedTypeReferenceDirectives = ts.createMap(); - var fileProcessingDiagnostics = ts.createDiagnosticCollection(); - // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. - // This works as imported modules are discovered recursively in a depth first manner, specifically: - // - For each root file, findSourceFile is called. - // - This calls processImportedModules for each module imported in the source file. - // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. - // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. - // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. - var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; - var currentNodeModulesDepth = 0; - // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track - // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. - var modulesWithElidedImports = ts.createMap(); - // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. - var sourceFilesFoundSearchingNodeModules = ts.createMap(); - ts.performance.mark("beforeProgram"); - host = host || createCompilerHost(options); - var skipDefaultLib = options.noLib; - var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); - var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); - var programDiagnostics = ts.createDiagnosticCollection(); - var currentDirectory = host.getCurrentDirectory(); - var supportedExtensions = ts.getSupportedExtensions(options); - // Map storing if there is emit blocking diagnostics for given input - var hasEmitBlockingDiagnostics = ts.createMap(); - var _compilerOptionsObjectLiteralSyntax; - var moduleResolutionCache; - var resolveModuleNamesWorker; - var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; - if (host.resolveModuleNames) { - resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(checkAllDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { - // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. - if (!resolved || resolved.extension !== undefined) { - return resolved; - } - var withExtension = ts.clone(resolved); - withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); - return withExtension; - }); }; - } - else { - moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); - var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; - resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(checkAllDefined(moduleNames), containingFile, loader_1); }; - } - var resolveTypeReferenceDirectiveNamesWorker; - if (host.resolveTypeReferenceDirectives) { - resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(checkAllDefined(typeDirectiveNames), containingFile); }; - } - else { - 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(); - var missingFilePaths; - // stores 'filename -> file association' ignoring case - // used to track cases when two file names differ only in casing - var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; - var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); - var structuralIsReused = tryReuseStructureFromOldProgram(); - if (structuralIsReused !== 2 /* Completely */) { - ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); - // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); - if (typeReferences.length) { - // This containingFilename needs to match with the one used in managed-side - var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); - for (var i = 0; i < typeReferences.length; i++) { - processTypeReferenceDirective(typeReferences[i], resolutions[i]); - } - } - // Do not process the default library if: - // - The '--noLib' flag is used. - // - A 'no-default-lib' reference comment is encountered in - // processing the root files. - if (!skipDefaultLib) { - // If '--lib' is not specified, include default library file according to '--target' - // otherwise, using options specified in '--lib' instead of '--target' default library file - if (!options.lib) { - processRootFile(getDefaultLibraryFileName(), /*isDefaultLib*/ true); - } - else { - ts.forEach(options.lib, function (libFileName) { - processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true); - }); - } - } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); - } - ts.Debug.assert(!!missingFilePaths); - // unconditionally set moduleResolutionCache to undefined to avoid unnecessary leaks - moduleResolutionCache = undefined; - // Release any files we have acquired in the old program but are - // not part of the new program. - if (oldProgram && host.onReleaseOldSourceFile) { - var oldSourceFiles = oldProgram.getSourceFiles(); - for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { - var oldSourceFile = oldSourceFiles_1[_i]; - if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { - host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); - } - } - } - // unconditionally set oldProgram to undefined to prevent it from being captured in closure - oldProgram = undefined; - program = { - getRootFileNames: function () { return rootNames; }, - getSourceFile: getSourceFile, - getSourceFileByPath: getSourceFileByPath, - getSourceFiles: function () { return files; }, - getMissingFilePaths: function () { return missingFilePaths; }, - getCompilerOptions: function () { return options; }, - getSyntacticDiagnostics: getSyntacticDiagnostics, - getOptionsDiagnostics: getOptionsDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getSemanticDiagnostics: getSemanticDiagnostics, - getDeclarationDiagnostics: getDeclarationDiagnostics, - getTypeChecker: getTypeChecker, - getClassifiableNames: getClassifiableNames, - getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, - getCommonSourceDirectory: getCommonSourceDirectory, - emit: emit, - getCurrentDirectory: function () { return currentDirectory; }, - getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, - getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, - getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, - getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, - getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, - isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, - dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, - getSourceFileFromReference: getSourceFileFromReference, - sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet, - isEmittedFile: isEmittedFile - }; - verifyCompilerOptions(); - ts.performance.mark("afterProgram"); - ts.performance.measure("Program", "beforeProgram", "afterProgram"); - return program; - function toPath(fileName) { - return ts.toPath(fileName, currentDirectory, getCanonicalFileName); - } - function getCommonSourceDirectory() { - if (commonSourceDirectory === undefined) { - var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); - if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { - // If a rootDir is specified and is valid use it as the commonSourceDirectory - commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); - } - else { - commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); - } - if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += ts.directorySeparator; - } - } - return commonSourceDirectory; - } - function getClassifiableNames() { - if (!classifiableNames) { - // Initialize a checker so that all our files are bound. - getTypeChecker(); - classifiableNames = ts.createUnderscoreEscapedMap(); - for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { - var sourceFile = files_1[_i]; - ts.copyEntries(sourceFile.classifiableNames, classifiableNames); - } - } - return classifiableNames; - } - function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { - if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { - // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, - // the best we can do is fallback to the default logic. - return resolveModuleNamesWorker(moduleNames, containingFile); - } - var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); - if (oldSourceFile !== file && file.resolvedModules) { - // `file` was created for the new program. - // - // We only set `file.resolvedModules` via work from the current function, - // so it is defined iff we already called the current function on `file`. - // That call happened no later than the creation of the `file` object, - // which per above occured during the current program creation. - // Since we assume the filesystem does not change during program creation, - // it is safe to reuse resolutions from the earlier call. - var result_3 = []; - for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { - var moduleName = moduleNames_1[_i]; - var resolvedModule = file.resolvedModules.get(moduleName); - result_3.push(resolvedModule); - } - return result_3; - } - // At this point, we know at least one of the following hold: - // - file has local declarations for ambient modules - // - old program state is available - // With this information, we can infer some module resolutions without performing resolution. - /** An ordered list of module names for which we cannot recover the resolution. */ - var unknownModuleNames; - /** - * The indexing of elements in this list matches that of `moduleNames`. - * - * Before combining results, result[i] is in one of the following states: - * * undefined: needs to be recomputed, - * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. - * Needs to be reset to undefined before returning, - * * ResolvedModuleFull instance: can be reused. - */ - var result; - var reusedNames; - /** A transient placeholder used to mark predicted resolution in the result list. */ - var predictedToResolveToAmbientModuleMarker = {}; - for (var i = 0; i < moduleNames.length; i++) { - var moduleName = moduleNames[i]; - // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions - if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { - var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); - if (oldResolvedModule) { - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); - } - (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; - (reusedNames || (reusedNames = [])).push(moduleName); - continue; - } - } - // We know moduleName resolves to an ambient module provided that moduleName: - // - is in the list of ambient modules locally declared in the current source file. - // - resolved to an ambient module in the old program whose declaration is in an unmodified file - // (so the same module declaration will land in the new program) - var resolvesToAmbientModuleInNonModifiedFile = false; - if (ts.contains(file.ambientModuleNames, moduleName)) { - resolvesToAmbientModuleInNonModifiedFile = true; - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); - } - } - else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); - } - if (resolvesToAmbientModuleInNonModifiedFile) { - (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; - } - else { - // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. - (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); - } - } - var resolutions = unknownModuleNames && unknownModuleNames.length - ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) - : ts.emptyArray; - // Combine results of resolutions and predicted results - if (!result) { - // There were no unresolved/ambient resolutions. - ts.Debug.assert(resolutions.length === moduleNames.length); - return resolutions; - } - var j = 0; - for (var i = 0; i < result.length; i++) { - if (result[i]) { - // `result[i]` is either a `ResolvedModuleFull` or a marker. - // If it is the former, we can leave it as is. - if (result[i] === predictedToResolveToAmbientModuleMarker) { - result[i] = undefined; - } - } - else { - result[i] = resolutions[j]; - j++; - } - } - ts.Debug.assert(j === resolutions.length); - return result; - // If we change our policy of rechecking failed lookups on each program create, - // we should adjust the value returned here. - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { - var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); - var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); - if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { - // In the old program, we resolved to an ambient module that was in the same - // place as we expected to find an actual module file. - // We actually need to return 'false' here even though this seems like a 'true' case - // because the normal module resolution algorithm will find this anyway. - return false; - } - var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } - // at least one of declarations should come from non-modified source file - var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { - var f = ts.getSourceFileOfNode(d); - return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); - if (!firstUnmodifiedFile) { - return false; - } - if (ts.isTraceEnabled(options, host)) { - ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); - } - return true; - } - } - function tryReuseStructureFromOldProgram() { - if (!oldProgram) { - return 0 /* Not */; - } - // check properties that can affect structure of the program or module resolution strategy - // if any of these properties has changed - structure cannot be reused - var oldOptions = oldProgram.getCompilerOptions(); - if (ts.changesAffectModuleResolution(oldOptions, options)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); - // there is an old program, check if we can reuse its structure - var oldRootNames = oldProgram.getRootFileNames(); - if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { - return oldProgram.structureIsReused = 0 /* Not */; - } - // check if program source files has changed in the way that can affect structure of the program - var newSourceFiles = []; - var filePaths = []; - var modifiedSourceFiles = []; - oldProgram.structureIsReused = 2 /* Completely */; - // If the missing file paths are now present, it can change the progam structure, - // and hence cant reuse the structure. - // This is same as how we dont reuse the structure if one of the file from old program is now missing - if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { - return oldProgram.structureIsReused = 0 /* Not */; - } - 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_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { - var oldSourceFile = oldSourceFiles_2[_i]; - var newSourceFile = host.getSourceFileByPath - ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) - : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); - 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); - 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 - // this will affect if default library is injected into the list of files - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // check tripleslash references - if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { - // tripleslash references has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // check imports and module augmentations - collectExternalModuleReferences(newSourceFile); - if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { - // imports has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { - // moduleAugmentations has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if ((oldSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */) !== (newSourceFile.flags & 524288 /* PossiblyContainsDynamicImport */)) { - // dynamicImport has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { - // 'types' references has changed - oldProgram.structureIsReused = 1 /* SafeModules */; - } - // tentatively approve the file - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); - } - else if (hasInvalidatedResolution(oldSourceFile.path)) { - // 'module/types' references could have changed - oldProgram.structureIsReused = 1 /* SafeModules */; - // add file to the modified list so that we will resolve it later - modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); - } - // if file has passed all checks it should be safe to reuse it - newSourceFiles.push(newSourceFile); - } - if (oldProgram.structureIsReused !== 2 /* Completely */) { - return oldProgram.structureIsReused; - } - modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); - // try to verify results of module resolution - for (var _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 = getModuleNames(newSourceFile); - var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); - // ensure that module resolution results are still correct - var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); - if (resolutionsChanged) { - oldProgram.structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); - } - else { - newSourceFile.resolvedModules = oldSourceFile.resolvedModules; - } - } - if (resolveTypeReferenceDirectiveNamesWorker) { - var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); - // ensure that types resolutions are still correct - var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); - if (resolutionsChanged) { - oldProgram.structureIsReused = 1 /* SafeModules */; - newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); - } - else { - newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; - } - } - } - if (oldProgram.structureIsReused !== 2 /* Completely */) { - return oldProgram.structureIsReused; - } - if (host.hasChangedAutomaticTypeDirectiveNames) { - return oldProgram.structureIsReused = 1 /* SafeModules */; - } - missingFilePaths = oldProgram.getMissingFilePaths(); - // update fileName -> file mapping - for (var i = 0; i < newSourceFiles.length; i++) { - filesByName.set(filePaths[i], newSourceFiles[i]); - // Set the file as found during node modules search if it was found that way in old progra, - if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { - sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); - } - } - files = newSourceFiles; - fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { - var modifiedFile = modifiedSourceFiles_2[_c]; - fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); - } - resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - sourceFileToPackageName = oldProgram.sourceFileToPackageName; - redirectTargetsSet = oldProgram.redirectTargetsSet; - return oldProgram.structureIsReused = 2 /* Completely */; - } - function getEmitHost(writeFileCallback) { - return { - getCanonicalFileName: getCanonicalFileName, - getCommonSourceDirectory: program.getCommonSourceDirectory, - getCompilerOptions: program.getCompilerOptions, - getCurrentDirectory: function () { return currentDirectory; }, - getNewLine: function () { return host.getNewLine(); }, - getSourceFile: program.getSourceFile, - getSourceFileByPath: program.getSourceFileByPath, - getSourceFiles: program.getSourceFiles, - isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, - writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), - isEmitBlocked: isEmitBlocked, - }; - } - function isSourceFileFromExternalLibrary(file) { - return sourceFilesFoundSearchingNodeModules.get(file.path); - } - function isSourceFileDefaultLibrary(file) { - if (file.hasNoDefaultLib) { - return true; - } - if (!options.noLib) { - return false; - } - // If '--lib' is not specified, include default library file according to '--target' - // otherwise, using options specified in '--lib' instead of '--target' default library file - var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; - if (!options.lib) { - return equalityComparer(file.fileName, getDefaultLibraryFileName()); - } - else { - return ts.forEach(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); - } - } - function getDiagnosticsProducingTypeChecker() { - return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); - } - function dropDiagnosticsProducingTypeChecker() { - diagnosticsProducingTypeChecker = undefined; - } - function getTypeChecker() { - return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); - } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); - } - function isEmitBlocked(emitFileName) { - return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); - } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var declarationDiagnostics = []; - if (!emitOnlyDtsFiles) { - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); - } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; - } - } - } - // Create the emit resolver outside of the "emitTime" tracking code below. That way - // any cost associated with it (like type checking) are appropriate associated with - // the type-checking counter. - // - // If the -out option is specified, we should not pass the source file to getEmitResolver. - // This is because in the -out scenario all files need to be emitted, and therefore all - // files need to be type checked. And the way to specify that all files need to be type - // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); - ts.performance.mark("beforeEmit"); - var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); - ts.performance.mark("afterEmit"); - ts.performance.measure("Emit", "beforeEmit", "afterEmit"); - return emitResult; - } - function getSourceFile(fileName) { - return getSourceFileByPath(toPath(fileName)); - } - function getSourceFileByPath(path) { - return filesByName.get(path); - } - function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { - if (sourceFile) { - return getDiagnostics(sourceFile, cancellationToken); - } - return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { - if (cancellationToken) { - cancellationToken.throwIfCancellationRequested(); - } - return getDiagnostics(sourceFile, cancellationToken); - })); - } - function getSyntacticDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); - } - function getSemanticDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); - } - function getDeclarationDiagnostics(sourceFile, cancellationToken) { - var options = program.getCompilerOptions(); - // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) - if (!sourceFile || options.out || options.outFile) { - return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); - } - else { - return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); - } - } - function getSyntacticDiagnosticsForFile(sourceFile) { - // For JavaScript files, we report semantic errors for using TypeScript-only - // constructs from within a JavaScript file as syntactic errors. - if (ts.isSourceFileJavaScript(sourceFile)) { - if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); - } - return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); - } - return sourceFile.parseDiagnostics; - } - function runWithCancellationToken(func) { - try { - return func(); - } - catch (e) { - if (e instanceof ts.OperationCanceledException) { - // We were canceled while performing the operation. Because our type checker - // might be a bad state, we need to throw it away. - // - // Note: we are overly aggressive here. We do not actually *have* to throw away - // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep - // the lifetimes of these two TypeCheckers the same. Also, we generally only - // cancel when the user has made a change anyways. And, in that case, we (the - // program instance) will get thrown away anyways. So trying to keep one of - // these type checkers alive doesn't serve much purpose. - noDiagnosticsTypeChecker = undefined; - diagnosticsProducingTypeChecker = undefined; - } - throw e; - } - } - function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); - } - function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { - return runWithCancellationToken(function () { - // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. - // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a - // '/// ' directive. - if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { - return ts.emptyArray; - } - var typeChecker = getDiagnosticsProducingTypeChecker(); - ts.Debug.assert(!!sourceFile.bindDiagnostics); - var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); - // By default, only type-check .ts, .tsx, and 'External' files (external files are added by plugins) - var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || - sourceFile.scriptKind === 5 /* External */ || isCheckJs; - var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; - var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; - var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); - var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); - var diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile); - if (isCheckJs) { - diagnostics = ts.concatenate(diagnostics, sourceFile.jsDocDiagnostics); - } - return ts.filter(diagnostics, shouldReportDiagnostic); - }); - } - /** - * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines - */ - function shouldReportDiagnostic(diagnostic) { - var file = diagnostic.file, start = diagnostic.start; - if (file) { - var lineStarts = ts.getLineStarts(file); - var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; - while (line > 0) { - var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); - var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); - if (!result) { - // non-empty line - return true; - } - if (result[3]) { - // @ts-ignore - return false; - } - line--; - } - } - return true; - } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { - return runWithCancellationToken(function () { - var diagnostics = []; - var parent = sourceFile; - walk(sourceFile); - return diagnostics; - function walk(node) { - // Return directly from the case if the given node doesnt want to visit each child - // Otherwise break to visit each child - switch (parent.kind) { - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - if (parent.questionToken === node) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - return; - } - // falls through - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 230 /* VariableDeclaration */: - // type annotation - if (parent.type === node) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); - return; - } - } - switch (node.kind) { - case 241 /* ImportEqualsDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); - return; - case 247 /* ExportAssignment */: - if (node.isExportEquals) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 266 /* HeritageClause */: - var heritageClause = node; - if (heritageClause.token === 108 /* ImplementsKeyword */) { - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 234 /* InterfaceDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); - return; - case 237 /* ModuleDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); - return; - case 235 /* TypeAliasDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); - return; - case 236 /* EnumDeclaration */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); - return; - case 207 /* NonNullExpression */: - diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); - return; - case 206 /* AsExpression */: - diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); - return; - case 188 /* TypeAssertionExpression */: - ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. - } - var prevParent = parent; - parent = node; - ts.forEachChild(node, walk, walkArray); - parent = prevParent; - } - function walkArray(nodes) { - if (parent.decorators === nodes && !options.experimentalDecorators) { - diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); - } - switch (parent.kind) { - case 233 /* ClassDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - // Check type parameters - if (nodes === parent.typeParameters) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); - return; - } - // falls through - case 212 /* VariableStatement */: - // Check modifiers - if (nodes === parent.modifiers) { - return checkModifiers(nodes, parent.kind === 212 /* VariableStatement */); - } - break; - case 151 /* PropertyDeclaration */: - // Check modifiers of property declaration - if (nodes === parent.modifiers) { - for (var _i = 0, _a = nodes; _i < _a.length; _i++) { - var modifier = _a[_i]; - if (modifier.kind !== 115 /* StaticKeyword */) { - diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - } - } - return; - } - break; - case 148 /* Parameter */: - // Check modifiers of parameter declaration - if (nodes === parent.modifiers) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); - return; - } - break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 205 /* ExpressionWithTypeArguments */: - // Check type arguments - if (nodes === parent.typeArguments) { - diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); - return; - } - break; - } - for (var _b = 0, nodes_8 = nodes; _b < nodes_8.length; _b++) { - var node = nodes_8[_b]; - walk(node); - } - } - function checkModifiers(modifiers, isConstValid) { - for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { - var modifier = modifiers_1[_i]; - switch (modifier.kind) { - case 76 /* ConstKeyword */: - if (isConstValid) { - continue; - } - // to report error, - // falls through - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 124 /* DeclareKeyword */: - case 117 /* AbstractKeyword */: - diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); - break; - // These are all legal modifiers. - case 115 /* StaticKeyword */: - case 84 /* ExportKeyword */: - case 79 /* DefaultKeyword */: - } - } - } - function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { - var start = nodes.pos; - return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); - } - // Since these are syntactic diagnostics, parent might not have been set - // this means the sourceFile cannot be infered from the node - function createDiagnosticForNode(node, message, arg0, arg1, arg2) { - return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); - } - }); - } - function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); - } - function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { - return runWithCancellationToken(function () { - var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); - // Don't actually write any files since we're just getting diagnostics. - return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); - }); - } - function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { - var cachedResult = sourceFile - ? cache.perFile && cache.perFile.get(sourceFile.path) - : cache.allDiagnostics; - if (cachedResult) { - return cachedResult; - } - var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; - if (sourceFile) { - if (!cache.perFile) { - cache.perFile = ts.createMap(); - } - cache.perFile.set(sourceFile.path, result); - } - else { - cache.allDiagnostics = result; - } - return result; - } - function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); - } - function getOptionsDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); - } - function getGlobalDiagnostics() { - return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); - } - function processRootFile(fileName, isDefaultLib) { - processSourceFile(ts.normalizePath(fileName), isDefaultLib, /*packageId*/ undefined); - } - function fileReferenceIsEqualTo(a, b) { - return a.fileName === b.fileName; - } - function moduleNameIsEqualTo(a, b) { - return a.kind === 9 /* StringLiteral */ - ? b.kind === 9 /* StringLiteral */ && a.text === b.text - : b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText; - } - function collectExternalModuleReferences(file) { - if (file.imports) { - return; - } - var isJavaScriptFile = ts.isSourceFileJavaScript(file); - var isExternalModuleFile = ts.isExternalModule(file); - // file.imports may not be undefined if there exists dynamic import - var imports; - var moduleAugmentations; - var ambientModules; - // If we are importing helpers, we need to add a synthetic reference to resolve the - // helpers library. - if (options.importHelpers - && (options.isolatedModules || isExternalModuleFile) - && !file.isDeclarationFile) { - // synthesize 'import "tslib"' declaration - var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); - var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); - ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); - externalHelpersModuleReference.parent = importDecl; - importDecl.parent = file; - imports = [externalHelpersModuleReference]; - } - for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { - var node = _a[_i]; - collectModuleReferences(node, /*inAmbientModule*/ false); - if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { - collectDynamicImportOrRequireCalls(node); - } - } - file.imports = imports || ts.emptyArray; - file.moduleAugmentations = moduleAugmentations || ts.emptyArray; - file.ambientModuleNames = ambientModules || ts.emptyArray; - return; - function collectModuleReferences(node, inAmbientModule) { - switch (node.kind) { - case 242 /* ImportDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 248 /* ExportDeclaration */: - var moduleNameExpr = ts.getExternalModuleName(node); - if (!moduleNameExpr || !ts.isStringLiteral(moduleNameExpr)) { - break; - } - if (!moduleNameExpr.text) { - break; - } - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules - // only through top - level external module names. Relative external module names are not permitted. - if (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text)) { - (imports || (imports = [])).push(moduleNameExpr); - } - break; - case 237 /* ModuleDeclaration */: - if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { - var moduleName = node.name; - var nameText = ts.getTextOfIdentifierOrLiteral(moduleName); - // Ambient module declarations can be interpreted as augmentations for some existing external modules. - // This will happen in two cases: - // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope - // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name - // immediately nested in top level ambient module declaration . - if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { - (moduleAugmentations || (moduleAugmentations = [])).push(moduleName); - } - else if (!inAmbientModule) { - if (file.isDeclarationFile) { - // for global .d.ts files record name of ambient module - (ambientModules || (ambientModules = [])).push(nameText); - } - // An AmbientExternalModuleDeclaration declares an external module. - // This type of declaration is permitted only in the global module. - // The StringLiteral must specify a top - level external module name. - // Relative external module names are not permitted - // NOTE: body of ambient module is always a module block, if it exists - var body = node.body; - if (body) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - collectModuleReferences(statement, /*inAmbientModule*/ true); - } - } - } - } - } - } - function collectDynamicImportOrRequireCalls(node) { - if (ts.isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) { - (imports || (imports = [])).push(node.arguments[0]); - } - // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. - else if (ts.isImportCall(node) && node.arguments.length === 1 && node.arguments[0].kind === 9 /* StringLiteral */) { - (imports || (imports = [])).push(node.arguments[0]); - } - else { - ts.forEachChild(node, collectDynamicImportOrRequireCalls); - } - } - } - /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ - function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); - } - function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { - if (ts.hasExtension(fileName)) { - if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { - if (fail) - fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); - return undefined; - } - var sourceFile = getSourceFile(fileName); - if (fail) { - if (!sourceFile) { - fail(ts.Diagnostics.File_0_not_found, fileName); - } - else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { - fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); - } - } - return sourceFile; - } - else { - var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); - if (sourceFileNoExtension) - return sourceFileNoExtension; - if (fail && options.allowNonTsExtensions) { - fail(ts.Diagnostics.File_0_not_found, fileName); - return undefined; - } - var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); - if (fail && !sourceFileWithAddedExtension) - fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); - return sourceFileWithAddedExtension; - } - } - /** This has side effects through `findSourceFile`. */ - function processSourceFile(fileName, isDefaultLib, packageId, refFile, refPos, refEnd) { - getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, refFile, refPos, refEnd, packageId); }, function (diagnostic) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined - ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); - }, refFile); - } - function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { - if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); - } - else { - 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, 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 - // NOTE: this only makes sense for case-insensitive file systems - if (file_1 && options.forceConsistentCasingInFileNames && ts.getNormalizedAbsolutePath(file_1.fileName, currentDirectory) !== ts.getNormalizedAbsolutePath(fileName, currentDirectory)) { - reportFileNamesDifferOnlyInCasingError(fileName, file_1.fileName, refFile, refPos, refEnd); - } - // If the file was previously found via a node_modules search, but is now being processed as a root file, - // then everything it sucks in may also be marked incorrectly, and needs to be checked again. - if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { - sourceFilesFoundSearchingNodeModules.set(file_1.path, false); - if (!options.noResolve) { - processReferencedFiles(file_1, isDefaultLib); - processTypeReferenceDirectives(file_1); - } - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); - } - // See if we need to reprocess the imports due to prior skipped imports - else if (file_1 && modulesWithElidedImports.get(file_1.path)) { - if (currentNodeModulesDepth < maxNodeModuleJsDepth) { - modulesWithElidedImports.set(file_1.path, false); - processImportedModules(file_1); - } - } - return file_1; - } - // We haven't looked for this file, do so now and cache result - var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { - if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { - fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); - } - else { - fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); - } - }, shouldCreateNewSourceFile); - if (packageId) { - var packageIdKey = ts.packageIdToString(packageId); - 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); - file.path = path; - if (host.useCaseSensitiveFileNames()) { - var pathLowerCase = path.toLowerCase(); - // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case - var existingFile = filesByNameIgnoreCase.get(pathLowerCase); - if (existingFile) { - reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); - } - else { - filesByNameIgnoreCase.set(pathLowerCase, file); - } - } - skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - if (!options.noResolve) { - processReferencedFiles(file, isDefaultLib); - processTypeReferenceDirectives(file); - } - // always process imported modules to record module name resolutions - processImportedModules(file); - if (isDefaultLib) { - files.unshift(file); - } - else { - files.push(file); - } - } - return file; - } - function processReferencedFiles(file, isDefaultLib) { - ts.forEach(file.referencedFiles, function (ref) { - var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); - processSourceFile(referencedFileName, isDefaultLib, /*packageId*/ undefined, file, ref.pos, ref.end); - }); - } - function processTypeReferenceDirectives(file) { - // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. - var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); - var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); - for (var i = 0; i < typeDirectives.length; i++) { - var ref = file.typeReferenceDirectives[i]; - var resolvedTypeReferenceDirective = resolutions[i]; - // store resolved type directive on the file - var fileName = ref.fileName.toLocaleLowerCase(); - ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); - processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); - } - } - function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { - // If we already found this library as a primary reference - nothing to do - var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); - if (previousResolution && previousResolution.primary) { - return; - } - var saveResolution = true; - if (resolvedTypeReferenceDirective) { - if (resolvedTypeReferenceDirective.primary) { - // resolved from the primary path - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); - } - else { - // If we already resolved to this file, it must have been a secondary reference. Check file contents - // for sameness and possibly issue an error - if (previousResolution) { - // Don't bother reading the file again if it's the same file. - if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { - var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); - } - } - // don't overwrite previous resolution result - saveResolution = false; - } - else { - // First resolution of this library - processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); - } - } - } - else { - fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); - } - if (saveResolution) { - resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); - } - } - function createDiagnostic(refFile, refPos, refEnd, message) { - var args = []; - for (var _i = 4; _i < arguments.length; _i++) { - args[_i - 4] = arguments[_i]; - } - if (refFile === undefined || refPos === undefined || refEnd === undefined) { - return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); - } - else { - return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); - } - } - function getCanonicalFileName(fileName) { - return host.getCanonicalFileName(fileName); - } - function processImportedModules(file) { - collectExternalModuleReferences(file); - if (file.imports.length || file.moduleAugmentations.length) { - // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. - var moduleNames = getModuleNames(file); - var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; - var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); - ts.Debug.assert(resolutions.length === moduleNames.length); - for (var i = 0; i < moduleNames.length; i++) { - var resolution = resolutions[i]; - ts.setResolvedModule(file, moduleNames[i], resolution); - if (!resolution) { - continue; - } - var isFromNodeModulesSearch = resolution.isExternalLibraryImport; - var isJsFile = !ts.extensionIsTypeScript(resolution.extension); - var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; - var resolvedFileName = resolution.resolvedFileName; - if (isFromNodeModulesSearch) { - currentNodeModulesDepth++; - } - // add file to program only if: - // - resolution was successful - // - noResolve is falsy - // - module name comes from the list of imports - // - it's not a top level JavaScript module that exceeded the search max - var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; - // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') - // This may still end up being an untyped module -- the file won't be included but imports will be allowed. - var shouldAddFile = resolvedFileName - && !getResolutionDiagnostic(options, resolution) - && !options.noResolve - && i < file.imports.length - && !elideImport - && !(isJsFile && !options.allowJs); - if (elideImport) { - modulesWithElidedImports.set(file.path, true); - } - 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, resolution.packageId); - } - if (isFromNodeModulesSearch) { - currentNodeModulesDepth--; - } - } - } - else { - // no imports - drop cached module resolutions - file.resolvedModules = undefined; - } - } - function computeCommonSourceDirectory(sourceFiles) { - var fileNames = []; - for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { - var file = sourceFiles_2[_i]; - if (!file.isDeclarationFile) { - fileNames.push(file.fileName); - } - } - return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); - } - function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { - var allFilesBelongToPath = true; - if (sourceFiles) { - var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { - var sourceFile = sourceFiles_3[_i]; - if (!sourceFile.isDeclarationFile) { - var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); - if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); - allFilesBelongToPath = false; - } - } - } - } - return allFilesBelongToPath; - } - function verifyCompilerOptions() { - if (options.isolatedModules) { - if (options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); - } - if (options.noEmitOnError) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); - } - if (options.out) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); - } - if (options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); - } - } - if (options.inlineSourceMap) { - if (options.sourceMap) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); - } - if (options.mapRoot) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); - } - } - if (options.paths && options.baseUrl === undefined) { - createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); - } - if (options.paths) { - for (var key in options.paths) { - if (!ts.hasProperty(options.paths, key)) { - continue; - } - if (!ts.hasZeroOrOneAsteriskCharacter(key)) { - createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); - } - if (ts.isArray(options.paths[key])) { - var len = options.paths[key].length; - if (len === 0) { - createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); - } - for (var i = 0; i < len; i++) { - var subst = options.paths[key][i]; - var typeOfSubst = typeof subst; - if (typeOfSubst === "string") { - if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { - createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); - } - } - else { - createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); - } - } - } - else { - createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); - } - } - } - if (!options.sourceMap && !options.inlineSourceMap) { - if (options.inlineSources) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); - } - if (options.sourceRoot) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); - } - } - if (options.out && options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); - } - if (options.mapRoot && !options.sourceMap) { - // Error to specify --mapRoot without --sourcemap - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"); - } - if (options.declarationDir) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); - } - if (options.out || options.outFile) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); - } - } - if (options.lib && options.noLib) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); - } - if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); - } - var languageVersion = options.target || 0 /* ES3 */; - var outFile = options.outFile || options.out; - var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); - if (options.isolatedModules) { - if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { - createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); - } - var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); - if (firstNonExternalModuleSourceFile) { - var span_7 = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); - programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span_7.start, span_7.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); - } - } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var span_8 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_8.start, span_8.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); - } - // Cannot specify module gen that isn't amd or system with --out - if (outFile) { - if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { - createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); - } - else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { - var span_9 = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); - programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span_9.start, span_9.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); - } - } - // 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 || // there is --outDir specified - options.sourceRoot || // there is --sourceRoot specified - options.mapRoot) { // there is --mapRoot specified - // Precalculate and cache the common source directory - var dir = getCommonSourceDirectory(); - // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure - if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { - createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); - } - } - if (!options.noEmit && options.allowJs && options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); - } - if (options.checkJs && !options.allowJs) { - programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); - } - if (options.emitDeclarationOnly) { - if (!options.declaration) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); - } - if (options.noEmit) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); - } - } - if (options.emitDecoratorMetadata && - !options.experimentalDecorators) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); - } - if (options.jsxFactory) { - if (options.reactNamespace) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); - } - if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { - createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); - } - } - else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { - createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); - } - // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files - if (!options.noEmit && !options.suppressOutputPathCheck) { - var emitHost = getEmitHost(); - var emitFilesSeen_1 = ts.createMap(); - ts.forEachEmittedFile(emitHost, function (emitFileNames) { - if (!options.emitDeclarationOnly) { - verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); - } - verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); - }); - } - // Verify that all the emit files are unique and don't overwrite input files - function verifyEmitFilePath(emitFileName, emitFilesSeen) { - if (emitFileName) { - var emitFilePath = toPath(emitFileName); - // Report error if the output overwrites input file - if (filesByName.has(emitFilePath)) { - var chain_2; - if (!options.configFilePath) { - // The program is from either an inferred project or an external project - chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); - } - chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); - } - var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; - // Report error if multiple files write into same file - if (emitFilesSeen.has(emitFileKey)) { - // Already seen the same emit file - report error - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); - } - else { - emitFilesSeen.set(emitFileKey, true); - } - } - } - } - function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { - var pathProp = pathsSyntax_1[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer)) { - for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { - var keyProps = _b[_a]; - if (ts.isArrayLiteralExpression(keyProps.initializer) && - keyProps.initializer.elements.length > valueIndex) { - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, keyProps.initializer.elements[valueIndex], message, arg0, arg1, arg2)); - needCompilerDiagnostic = false; - } - } - } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); - } - } - function createDiagnosticForOptionPaths(onKey, key, message, arg0) { - var needCompilerDiagnostic = true; - var pathsSyntax = getOptionPathsSyntax(); - for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { - var pathProp = pathsSyntax_2[_i]; - if (ts.isObjectLiteralExpression(pathProp.initializer) && - createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { - needCompilerDiagnostic = false; - } - } - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); - } - } - function getOptionPathsSyntax() { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - if (compilerOptionsObjectLiteralSyntax) { - return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, "paths"); - } - return ts.emptyArray; - } - function createDiagnosticForOptionName(message, option1, option2) { - createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2); - } - function createOptionValueDiagnostic(option1, message, arg0) { - createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); - } - function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1) { - var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); - var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || - !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1); - if (needCompilerDiagnostic) { - programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); - } - } - function getCompilerOptionsObjectLiteralSyntax() { - if (_compilerOptionsObjectLiteralSyntax === undefined) { - _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword - if (options.configFile && options.configFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(options.configFile.jsonObject, "compilerOptions"); _i < _a.length; _i++) { - var prop = _a[_i]; - if (ts.isObjectLiteralExpression(prop.initializer)) { - _compilerOptionsObjectLiteralSyntax = prop.initializer; - break; - } - } - } - } - return _compilerOptionsObjectLiteralSyntax; - } - function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1) { - var props = ts.getPropertyAssignment(objectLiteral, key1, key2); - for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { - var prop = props_2[_i]; - programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1)); - } - return !!props.length; - } - function blockEmittingOfFile(emitFileName, diag) { - hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); - programDiagnostics.add(diag); - } - function isEmittedFile(file) { - if (options.noEmit) { - return false; - } - // If this is source file, its not emitted file - var filePath = toPath(file); - if (getSourceFileByPath(filePath)) { - return false; - } - // If options have --outFile or --out just check that - var out = options.outFile || options.out; - if (out) { - return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); - } - // If --outDir, check if file is in that directory - if (options.outDir) { - return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); - } - if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { - // Otherwise just check if sourceFile with the name exists - var filePathWithoutExtension = ts.removeFileExtension(filePath); - return !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".ts" /* Ts */)) || - !!getSourceFileByPath(ts.combinePaths(filePathWithoutExtension, ".tsx" /* Tsx */)); - } - return false; - } - function isSameFile(file1, file2) { - return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; - } - } - ts.createProgram = createProgram; - /* @internal */ - /** - * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. - * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. - * This returns a diagnostic even if the module will be an untyped module. - */ - function getResolutionDiagnostic(options, _a) { - var extension = _a.extension; - switch (extension) { - case ".ts" /* Ts */: - case ".d.ts" /* Dts */: - // These are always allowed. - return undefined; - case ".tsx" /* Tsx */: - return needJsx(); - case ".jsx" /* Jsx */: - return needJsx() || needAllowJs(); - case ".js" /* Js */: - return needAllowJs(); - } - function needJsx() { - return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; - } - function needAllowJs() { - return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; - } - } - ts.getResolutionDiagnostic = getResolutionDiagnostic; - function checkAllDefined(names) { - ts.Debug.assert(names.every(function (name) { return name !== undefined; }), "A name is undefined.", function () { return JSON.stringify(names); }); - return names; - } - function getModuleNames(_a) { - var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; - var res = imports.map(function (i) { return i.text; }); - for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { - var aug = moduleAugmentations_1[_i]; - if (aug.kind === 9 /* StringLiteral */) { - res.push(aug.text); - } - } - return res; - } -})(ts || (ts = {})); -/// -/*@internal*/ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; -})(ts || (ts = {})); -/*@internal*/ -(function (ts) { - var BuilderState; - (function (BuilderState) { - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile, getCanonicalFileName) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed - */ - function canReuseOldState(newReferencedMap, oldState) { - return oldState && !oldState.referencedMap === !newReferencedMap; - } - BuilderState.canReuseOldState = canReuseOldState; - /** - * Creates the state of file references and signature for the new program from oldState if it is safe - */ - function create(newProgram, getCanonicalFileName, oldState) { - var fileInfos = ts.createMap(); - var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; - var hasCalledUpdateShapeSignature = ts.createMap(); - var useOldState = canReuseOldState(referencedMap, oldState); - // Create the reference map, and set the file infos - for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - var version_1 = sourceFile.version; - var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); - if (referencedMap) { - var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); - if (newReferences) { - referencedMap.set(sourceFile.path, newReferences); - } - } - fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); - } - return { - fileInfos: fileInfos, - referencedMap: referencedMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined - }; - } - BuilderState.create = create; - /** - * Gets the files affected by the path from the program - */ - function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { - // Since the operation could be cancelled, the signatures are always stored in the cache - // They will be commited once it is safe to use them - // eg when calling this api from tsserver, if there is no cancellation of the operation - // In the other cases the affected files signatures are commited only after the iteration through the result is complete - var signatureCache = cacheToUpdateSignature || ts.createMap(); - var sourceFile = programOfThisState.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { - return [sourceFile]; - } - var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); - if (!cacheToUpdateSignature) { - // Commit all the signatures in the signature cache - updateSignaturesFromCache(state, signatureCache); - } - return result; - } - BuilderState.getFilesAffectedBy = getFilesAffectedBy; - /** - * Updates the signatures from the cache into state's fileinfo signatures - * This should be called whenever it is safe to commit the state of the builder - */ - function updateSignaturesFromCache(state, signatureCache) { - signatureCache.forEach(function (signature, path) { - state.fileInfos.get(path).signature = signature; - state.hasCalledUpdateShapeSignature.set(path, true); - }); - } - BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; - /** - * Returns if the shape of the signature has changed since last emit - */ - function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { - ts.Debug.assert(!!sourceFile); - // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { - return false; - } - var info = state.fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - } - else { - var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = computeHash(emitOutput.outputFiles[0].text); - } - else { - latestSignature = prevSignature; - } - } - cacheToUpdateSignature.set(sourceFile.path, latestSignature); - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Get all the dependencies of the sourceFile - */ - function getAllDependencies(state, programOfThisState, sourceFile) { - var compilerOptions = programOfThisState.getCompilerOptions(); - // With --out or --outFile all outputs go into single file, all files depend on each other - if (compilerOptions.outFile || compilerOptions.out) { - return getAllFileNames(state, programOfThisState); - } - // If this is non module emit, or its a global file, it depends on all the source files - if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { - return getAllFileNames(state, programOfThisState); - } - // Get the references, traversing deep from the referenceMap - var seenMap = ts.createMap(); - var queue = [sourceFile.path]; - while (queue.length) { - var path = queue.pop(); - if (!seenMap.has(path)) { - seenMap.set(path, true); - var references = state.referencedMap.get(path); - if (references) { - var iterator = references.keys(); - for (var _a = iterator.next(), value = _a.value, done = _a.done; !done; _b = iterator.next(), value = _b.value, done = _b.done, _b) { - queue.push(value); - } - } - } - } - return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { - var file = programOfThisState.getSourceFileByPath(path); - return file ? file.fileName : path; - })); - var _b; - } - BuilderState.getAllDependencies = getAllDependencies; - /** - * Gets the names of all files from the program - */ - function getAllFileNames(state, programOfThisState) { - if (!state.allFileNames) { - var sourceFiles = programOfThisState.getSourceFiles(); - state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); - } - return state.allFileNames; - } - /** - * Gets the files referenced by the the file path - */ - function getReferencedByPaths(state, referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * Gets all files of the program excluding the default library file - */ - function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { - // Use cached result - if (state.allFilesExcludingDefaultLibraryFile) { - return state.allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return state.allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - /** - * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed - */ - function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { - var compilerOptions = programOfThisState.getCompilerOptions(); - // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, - // so returning the file itself is good enough. - if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { - return [sourceFileWithUpdatedShape]; - } - return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); - } - /** - * When program emits modular code, gets the files affected by the sourceFile whose shape has changed - */ - function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { - if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { - return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); - } - var compilerOptions = programOfThisState.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFileWithUpdatedShape]; - } - // Now we need to if each file in the referencedBy list has a shape change as well. - // Because if so, its own referencedBy files need to be saved as well to make the - // emitting result consistent with files on disk. - var seenFileNamesMap = ts.createMap(); - // Start with the paths this file was referenced by - seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); - } - } - } - // Return array of values that needs emit - // Return array of values that needs emit - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); -})(ts || (ts = {})); -/// -/*@internal*/ -var ts; -(function (ts) { - function hasSameKeys(map1, map2) { - // Has same size and every key is present in both maps - return map1 === map2 || map1 && map2 && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); - } - /** - * Create the state so that we can iterate on changedFiles/affected files - */ - function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { - var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); - state.program = newProgram; - var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { - state.semanticDiagnosticsPerFile = ts.createMap(); - } - state.changedFilesSet = ts.createMap(); - var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; - if (useOldState) { - // Verify the sanity of old state - if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); - } - if (canCopySemanticDiagnostics) { - ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); - } - // Copy old state's changed files set - ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); - } - // Update changed files and copy semantic diagnostics if we can - var referencedMap = state.referencedMap; - var oldReferencedMap = useOldState && oldState.referencedMap; - state.fileInfos.forEach(function (info, sourceFilePath) { - var oldInfo; - var newReferences; - // if not using old state, every file is changed - if (!useOldState || - // File wasnt present in old state - !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || - // versions dont match - oldInfo.version !== info.version || - // Referenced files changed - !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || - // Referenced file was deleted in the new program - newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { - // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated - state.changedFilesSet.set(sourceFilePath, true); - } - else if (canCopySemanticDiagnostics) { - // Unchanged file copy diagnostics - var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); - if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); - } - } - }); - return state; - } - /** - * Verifies that source file is ok to be used in calls that arent handled by next - */ - function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { - ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); - } - /** - * This function returns the next affected file to be processed. - * Note that until doneAffected is called it would keep reporting same result - * This is to allow the callers to be able to actually remove affected file only when the operation is complete - * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained - */ - function getNextAffectedFile(state, cancellationToken, computeHash) { - while (true) { - var affectedFiles = state.affectedFiles; - if (affectedFiles) { - var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; - var affectedFilesIndex = state.affectedFilesIndex; - while (affectedFilesIndex < affectedFiles.length) { - var affectedFile = affectedFiles[affectedFilesIndex]; - if (!seenAffectedFiles.has(affectedFile.path)) { - // Set the next affected file as seen and remove the cached semantic diagnostics - state.affectedFilesIndex = affectedFilesIndex; - semanticDiagnosticsPerFile.delete(affectedFile.path); - return affectedFile; - } - seenAffectedFiles.set(affectedFile.path, true); - affectedFilesIndex++; - } - // Remove the changed file from the change set - state.changedFilesSet.delete(state.currentChangedFilePath); - state.currentChangedFilePath = undefined; - // Commit the changes in file signature - ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); - state.currentAffectedFilesSignatures.clear(); - state.affectedFiles = undefined; - } - // Get next changed file - var nextKey = state.changedFilesSet.keys().next(); - if (nextKey.done) { - // Done - return undefined; - } - // With --out or --outFile all outputs go into single file - // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; - } - // Get next batch of affected files - state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); - state.currentChangedFilePath = nextKey.value; - state.semanticDiagnosticsPerFile.delete(nextKey.value); - state.affectedFilesIndex = 0; - state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); - } - } - /** - * This is called after completing operation on the next affected file. - * The operations here are postponed to ensure that cancellation during the iteration is handled correctly - */ - function doneWithAffectedFile(state, affected) { - if (affected === state.program) { - state.changedFilesSet.clear(); - } - else { - state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; - } - } - /** - * Returns the result with affected file - */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); - return { result: result, affected: affected }; - } - /** - * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it - * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set - */ - function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; - } - // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - var BuilderProgramKind; - (function (BuilderProgramKind) { - BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; - BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; - })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); - function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - var host; - var newProgram; - if (ts.isArray(newProgramOrRootNames)) { - newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); - host = oldProgramOrHost; - } - else { - newProgram = newProgramOrRootNames; - host = hostOrOptions; - oldProgram = oldProgramOrHost; - } - return { host: host, newProgram: newProgram, oldProgram: oldProgram }; - } - ts.getBuilderCreationParameters = getBuilderCreationParameters; - function createBuilderProgram(kind, _a) { - var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; - // Return same program if underlying program doesnt change - var oldState = oldProgram && oldProgram.getState(); - if (oldState && newProgram === oldState.program) { - newProgram = undefined; - oldState = undefined; - return oldProgram; - } - /** - * Create the canonical file name for identity - */ - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - /** - * Computing hash to for signature verification - */ - var computeHash = host.createHash || ts.identity; - var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); - // To ensure that we arent storing any references to old program or new program without state - newProgram = undefined; - oldProgram = undefined; - oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } - }; - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; - } - else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { - result.emitNextAffectedFile = emitNextAffectedFile; - } - else { - ts.notImplemented(); - } - return result; - /** - * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash); - if (!affected) { - // Done - return undefined; - } - return toAffectedFileResult(state, - // When whole program is affected, do emit only once (eg when --out or --outFile is specified) - // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); - } - /** - * Emits the JavaScript and declaration files. - * When targetSource file is specified, emits the files corresponding to that source file, - * otherwise for the whole program. - * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, - * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, - * it will only emit all the affected files instead of whole program - * - * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host - * in that order would be used to write the files - */ - function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { - if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { - assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); - if (!targetSourceFile) { - // Emit and report any errors we ran into. - var sourceMaps = []; - var emitSkipped = void 0; - var diagnostics = void 0; - var emittedFiles = []; - var affectedEmitResult = void 0; - while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { - emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; - diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); - emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); - sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); - } - return { - emitSkipped: emitSkipped, - diagnostics: diagnostics || ts.emptyArray, - emittedFiles: emittedFiles, - sourceMaps: sourceMaps - }; - } - } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - } - /** - * Return the semantic diagnostics for the next affected file or undefined if iteration is complete - * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true - */ - function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { - while (true) { - var affected = getNextAffectedFile(state, cancellationToken, computeHash); - if (!affected) { - // Done - return undefined; - } - else if (affected === state.program) { - // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) - return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); - } - // Get diagnostics for the affected file if its not ignored - if (ignoreSourceFile && ignoreSourceFile(affected)) { - // Get next affected file - doneWithAffectedFile(state, affected); - continue; - } - return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); - } - } - /** - * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program - * The semantic diagnostics are cached and managed here - * Note that it is assumed that when asked about semantic diagnostics through this API, - * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics - * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, - * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics - */ - function getSemanticDiagnostics(sourceFile, cancellationToken) { - assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(!state.semanticDiagnosticsPerFile); - // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - } - if (sourceFile) { - return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); - } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); - } - } - var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_1 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - } - ts.createBuilderProgram = createBuilderProgram; -})(ts || (ts = {})); -(function (ts) { - function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); - } - ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); - } - ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; - function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; - } - ts.createAbstractBuilder = createAbstractBuilder; -})(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -77520,7 +81170,7 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); + return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath)); } function getCachedFileSystemEntriesForBaseDir(path) { return getCachedFileSystemEntries(ts.getDirectoryPath(path)); @@ -77533,7 +81183,7 @@ var ts; files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], directories: host.getDirectories(rootDir) || [] }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost); return resultFromHost; } /** @@ -77542,6 +81192,7 @@ var ts; * The host request is done under try catch block to avoid caching incorrect result */ function tryReadDirectory(rootDir, rootDirPath) { + rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath); var cachedResult = getCachedFileSystemEntries(rootDirPath); if (cachedResult) { return cachedResult; @@ -77551,7 +81202,7 @@ var ts; } catch (_e) { // If there is exception to read directories, dont cache the result and direct the calls to host - ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath))); return undefined; } } @@ -77587,7 +81238,7 @@ var ts; } function directoryExists(dirPath) { var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath); } function createDirectory(dirPath) { var path = toPath(dirPath); @@ -77777,7 +81428,7 @@ var ts; case WatchLogLevel.TriggerOnly: return createFileWatcherWithTriggerLogging; case WatchLogLevel.Verbose: - return createFileWatcherWithLogging; + return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging; } } function createFileWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { @@ -77790,9 +81441,27 @@ var ts; } }; } + function createDirectoryWatcherWithLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { + var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + return { + close: function () { + var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + log(watchInfo); + var start = ts.timestamp(); + watcher.close(); + var elapsed = ts.timestamp() - start; + log("Elapsed:: " + elapsed + "ms " + watchInfo); + } + }; + } function createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) { return addWatch(host, file, function (fileName, cbOptional) { - var triggerredInfo = watchCaption + ":: Triggered with " + fileName + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); + var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo); log(triggerredInfo); var start = ts.timestamp(); cb(fileName, cbOptional, passThrough); @@ -77801,16 +81470,3190 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : ""); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); } ts.closeFileWatcherOf = closeFileWatcherOf; })(ts || (ts = {})); -/// -/// -/// +var ts; +(function (ts) { + var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; + function findConfigFile(searchPath, fileExists, configName) { + if (configName === void 0) { configName = "tsconfig.json"; } + return ts.forEachAncestorDirectory(searchPath, function (ancestor) { + var fileName = ts.combinePaths(ancestor, configName); + return fileExists(fileName) ? fileName : undefined; + }); + } + ts.findConfigFile = findConfigFile; + function resolveTripleslashReference(moduleName, containingFile) { + var basePath = ts.getDirectoryPath(containingFile); + var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName); + return ts.normalizePath(referencedFileName); + } + ts.resolveTripleslashReference = resolveTripleslashReference; + /* @internal */ + function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { + var commonPathComponents; + var failed = ts.forEach(fileNames, function (sourceFile) { + // Each file contributes into common source file path + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory); + sourcePathComponents.pop(); // The base file name is not part of the common directory path + if (!commonPathComponents) { + // first file + commonPathComponents = sourcePathComponents; + return; + } + var n = Math.min(commonPathComponents.length, sourcePathComponents.length); + for (var i = 0; i < n; i++) { + if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) { + if (i === 0) { + // Failed to find any common path component + return true; + } + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + }); + // A common path can not be found when paths span multiple drives on windows, for example + if (failed) { + return ""; + } + if (!commonPathComponents) { // Can happen when all input files are .d.ts files + return currentDirectory; + } + return ts.getPathFromPathComponents(commonPathComponents); + } + ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; + function createCompilerHost(options, setParentNodes) { + var existingDirectories = ts.createMap(); + function getCanonicalFileName(fileName) { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + function getSourceFile(fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = ts.sys.readFile(fileName, options.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined; + } + function directoryExists(directoryPath) { + if (existingDirectories.has(directoryPath)) { + return true; + } + if (ts.sys.directoryExists(directoryPath)) { + existingDirectories.set(directoryPath, true); + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + ts.sys.createDirectory(directoryPath); + } + } + var outputFingerprints; + function writeFileIfUpdated(fileName, data, writeByteOrderMark) { + if (!outputFingerprints) { + outputFingerprints = ts.createMap(); + } + var hash = ts.sys.createHash(data); // TODO: GH#18217 + var mtimeBefore = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + if (mtimeBefore) { + var fingerprint = outputFingerprints.get(fileName); + // If output has not been changed, and the file has no external modification + if (fingerprint && + fingerprint.byteOrderMark === writeByteOrderMark && + fingerprint.hash === hash && + fingerprint.mtime.getTime() === mtimeBefore.getTime()) { + return; + } + } + ts.sys.writeFile(fileName, data, writeByteOrderMark); + var mtimeAfter = ts.sys.getModifiedTime(fileName); // TODO: GH#18217 + outputFingerprints.set(fileName, { + hash: hash, + byteOrderMark: writeByteOrderMark, + mtime: mtimeAfter + }); + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + if (ts.isWatchSet(options) && ts.sys.createHash && ts.sys.getModifiedTime) { + writeFileIfUpdated(fileName, data, writeByteOrderMark); + } + else { + ts.sys.writeFile(fileName, data, writeByteOrderMark); + } + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())); + } + var newLine = ts.getNewLineCharacter(options); + var realpath = ts.sys.realpath && (function (path) { return ts.sys.realpath(path); }); + return { + getSourceFile: getSourceFile, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return ts.sys.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: function (fileName) { return ts.sys.fileExists(fileName); }, + readFile: function (fileName) { return ts.sys.readFile(fileName); }, + trace: function (s) { return ts.sys.write(s + newLine); }, + directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, + getDirectories: function (path) { return ts.sys.getDirectories(path); }, + realpath: realpath, + readDirectory: function (path, extensions, include, exclude, depth) { return ts.sys.readDirectory(path, extensions, include, exclude, depth); }, + getModifiedTime: ts.sys.getModifiedTime && (function (path) { return ts.sys.getModifiedTime(path); }), + setModifiedTime: ts.sys.setModifiedTime && (function (path, date) { return ts.sys.setModifiedTime(path, date); }), + deleteFile: ts.sys.deleteFile && (function (path) { return ts.sys.deleteFile(path); }) + }; + } + ts.createCompilerHost = createCompilerHost; + function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { + var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (program.getCompilerOptions().declaration) { + ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); + } + return ts.sortAndDeduplicateDiagnostics(diagnostics); + } + ts.getPreEmitDiagnostics = getPreEmitDiagnostics; + function formatDiagnostics(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + output += formatDiagnostic(diagnostic, host); + } + return output; + } + ts.formatDiagnostics = formatDiagnostics; + function formatDiagnostic(diagnostic, host) { + var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine(); + if (diagnostic.file) { + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217 + var fileName = diagnostic.file.fileName; + var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }); + return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage; + } + return errorMessage; + } + ts.formatDiagnostic = formatDiagnostic; + /** @internal */ + var ForegroundColorEscapeSequences; + (function (ForegroundColorEscapeSequences) { + ForegroundColorEscapeSequences["Grey"] = "\u001B[90m"; + ForegroundColorEscapeSequences["Red"] = "\u001B[91m"; + ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m"; + ForegroundColorEscapeSequences["Blue"] = "\u001B[94m"; + ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m"; + })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {})); + var gutterStyleSequence = "\u001b[30;47m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var ellipsis = "..."; + var halfIndent = " "; + var indent = " "; + function getCategoryFormat(category) { + switch (category) { + case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red; + case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow; + case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line."); + case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue; + } + } + /** @internal */ + function formatColorAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + ts.formatColorAndReset = formatColorAndReset; + function padLeft(s, length) { + while (s.length < length) { + s = " " + s; + } + return s; + } + function formatCodeSpan(file, start, length, indent, squiggleColor, host) { + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(ellipsis.length, gutterWidth); + } + var context = ""; + for (var i = firstLine; i <= lastLine; i++) { + context += host.getNewLine(); + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + context += indent + formatColorAndReset(padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine(); + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + // Output the gutter and the actual contents of the line. + context += indent + formatColorAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += lineContent + host.getNewLine(); + // Output the gutter and the error span for the line using tildes. + context += indent + formatColorAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + context += squiggleColor; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + context += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + context += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + context += lineContent.replace(/./g, "~"); + } + context += resetEscapeSequence; + } + return context; + } + /* @internal */ + function formatLocation(file, start, host, color) { + if (color === void 0) { color = formatColorAndReset; } + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217 + var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName; + var output = ""; + output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan); + output += ":"; + output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow); + output += ":"; + output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow); + return output; + } + ts.formatLocation = formatLocation; + function formatDiagnosticsWithColorAndContext(diagnostics, host) { + var output = ""; + for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { + var diagnostic = diagnostics_2[_i]; + if (diagnostic.file) { + var file = diagnostic.file, start = diagnostic.start; + output += formatLocation(file, start, host); // TODO: GH#18217 + output += " - "; + } + output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category)); + output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey); + output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()); + if (diagnostic.file) { + output += host.getNewLine(); + output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217 + if (diagnostic.relatedInformation) { + output += host.getNewLine(); + for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) { + var _c = _b[_a], file = _c.file, start = _c.start, length_5 = _c.length, messageText = _c.messageText; + if (file) { + output += host.getNewLine(); + output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217 + output += formatCodeSpan(file, start, length_5, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217 + } + output += host.getNewLine(); + output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine()); + } + } + } + output += host.getNewLine(); + } + return output; + } + ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext; + function flattenDiagnosticMessageText(messageText, newLine) { + if (ts.isString(messageText)) { + return messageText; + } + else { + var diagnosticChain = messageText; + var result = ""; + var indent_1 = 0; + while (diagnosticChain) { + if (indent_1) { + result += newLine; + for (var i = 0; i < indent_1; i++) { + result += " "; + } + } + result += diagnosticChain.messageText; + indent_1++; + diagnosticChain = diagnosticChain.next; + } + return result; + } + } + ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; + function loadWithLocalCache(names, containingFile, loader) { + if (names.length === 0) { + return []; + } + var resolutions = []; + var cache = ts.createMap(); + for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { + var name = names_1[_i]; + var result = void 0; + if (cache.has(name)) { + result = cache.get(name); + } + else { + cache.set(name, result = loader(name, containingFile)); + } + resolutions.push(result); + } + return resolutions; + } + /** + * Determines if program structure is upto date or needs to be recreated + */ + /* @internal */ + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames) { + // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date + if (!program || hasChangedAutomaticTypeDirectiveNames) { + return false; + } + // If number of files in the program do not match, it is not up-to-date + if (program.getRootFileNames().length !== rootFileNames.length) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date + if (program.getSourceFiles().some(sourceFileNotUptoDate)) { + return false; + } + // If any of the missing file paths are now created + if (program.getMissingFilePaths().some(fileExists)) { + return false; + } + var currentOptions = program.getCompilerOptions(); + // If the compilation settings do no match, then the program is not up-to-date + if (!ts.compareDataObjects(currentOptions, newOptions)) { + return false; + } + // If everything matches but the text of config file is changed, + // error locations can change for program options, so update the program + if (currentOptions.configFile && newOptions.configFile) { + return currentOptions.configFile.text === newOptions.configFile.text; + } + return true; + function sourceFileNotUptoDate(sourceFile) { + return sourceFile.version !== getSourceVersion(sourceFile.path) || + hasInvalidatedResolution(sourceFile.path); + } + } + ts.isProgramUptoDate = isProgramUptoDate; + function getConfigFileParsingDiagnostics(configFileParseResult) { + return configFileParseResult.options.configFile ? configFileParseResult.options.configFile.parseDiagnostics.concat(configFileParseResult.errors) : + configFileParseResult.errors; + } + ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics; + /** + * Determined if source file needs to be re-created even if its text hasn't changed + */ + function shouldProgramCreateNewSourceFiles(program, newOptions) { + // If any of these options change, we can't reuse old source file even if version match + // The change in options like these could result in change in syntax tree change + var oldOptions = program && program.getCompilerOptions(); + return oldOptions && (oldOptions.target !== newOptions.target || + oldOptions.module !== newOptions.module || + oldOptions.moduleResolution !== newOptions.moduleResolution || + oldOptions.noResolve !== newOptions.noResolve || + oldOptions.jsx !== newOptions.jsx || + oldOptions.allowJs !== newOptions.allowJs || + oldOptions.disableSizeLimit !== newOptions.disableSizeLimit || + oldOptions.baseUrl !== newOptions.baseUrl || + !ts.equalOwnProperties(oldOptions.paths, newOptions.paths)); + } + function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) { + return { + rootNames: rootNames, + options: options, + host: host, + oldProgram: oldProgram, + configFileParsingDiagnostics: configFileParsingDiagnostics + }; + } + function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { + var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 + var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences; + var oldProgram = createProgramOptions.oldProgram; + var program; + var processingDefaultLibFiles; + var processingOtherFiles; + var files; + var commonSourceDirectory; + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var classifiableNames; + var modifiedFilePaths; + var cachedSemanticDiagnosticsForFile = {}; + var cachedDeclarationDiagnosticsForFile = {}; + var resolvedTypeReferenceDirectives = ts.createMap(); + var fileProcessingDiagnostics = ts.createDiagnosticCollection(); + // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules. + // This works as imported modules are discovered recursively in a depth first manner, specifically: + // - For each root file, findSourceFile is called. + // - This calls processImportedModules for each module imported in the source file. + // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module. + // As all these operations happen - and are nested - within the createProgram call, they close over the below variables. + // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses. + var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; + var currentNodeModulesDepth = 0; + // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track + // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed. + var modulesWithElidedImports = ts.createMap(); + // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled. + var sourceFilesFoundSearchingNodeModules = ts.createMap(); + ts.performance.mark("beforeProgram"); + var host = createProgramOptions.host || createCompilerHost(options); + var configParsingHost = parseConfigHostFromCompilerHost(host); + var skipDefaultLib = options.noLib; + var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); + var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); + var programDiagnostics = ts.createDiagnosticCollection(); + var currentDirectory = host.getCurrentDirectory(); + var supportedExtensions = ts.getSupportedExtensions(options); + var supportedExtensionsWithJsonIfResolveJsonModule = options.resolveJsonModule ? supportedExtensions.concat([".json" /* Json */]) : undefined; + // Map storing if there is emit blocking diagnostics for given input + var hasEmitBlockingDiagnostics = ts.createMap(); + var _compilerOptionsObjectLiteralSyntax; + var _referencesArrayLiteralSyntax; + var moduleResolutionCache; + var resolveModuleNamesWorker; + var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; + if (host.resolveModuleNames) { + resolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(ts.Debug.assertEachDefined(moduleNames), containingFile, reusedNames).map(function (resolved) { + // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName. + if (!resolved || resolved.extension !== undefined) { + return resolved; + } + var withExtension = ts.clone(resolved); + withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName); + return withExtension; + }); }; + } + else { + moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }); + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache).resolvedModule; }; // TODO: GH#18217 + resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(moduleNames), containingFile, loader_1); }; + } + var resolveTypeReferenceDirectiveNamesWorker; + if (host.resolveTypeReferenceDirectives) { + resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(ts.Debug.assertEachDefined(typeDirectiveNames), containingFile); }; + } + else { + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; // TODO: GH#18217 + resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(ts.Debug.assertEachDefined(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(); + var redirectTargetsSet = ts.createMap(); + var filesByName = ts.createMap(); + var missingFilePaths; + // stores 'filename -> file association' ignoring case + // used to track cases when two file names differ only in casing + var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined; + // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files + var resolvedProjectReferences = projectReferences ? [] : undefined; + var projectReferenceRedirects = ts.createMap(); + var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); + var structuralIsReused = tryReuseStructureFromOldProgram(); + if (structuralIsReused !== 2 /* Completely */) { + processingDefaultLibFiles = []; + processingOtherFiles = []; + if (projectReferences) { + for (var _i = 0, projectReferences_1 = projectReferences; _i < projectReferences_1.length; _i++) { + var ref = projectReferences_1[_i]; + var parsedRef = parseProjectReferenceConfigFile(ref); + resolvedProjectReferences.push(parsedRef); + if (parsedRef) { + if (parsedRef.commandLine.options.outFile) { + var dtsOutfile = ts.changeExtension(parsedRef.commandLine.options.outFile, ".d.ts"); + processSourceFile(dtsOutfile, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined); + } + addProjectReferenceRedirects(parsedRef.commandLine, projectReferenceRedirects); + } + } + } + ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); }); + // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { + // This containingFilename needs to match with the one used in managed-side + var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); + for (var i = 0; i < typeReferences.length; i++) { + processTypeReferenceDirective(typeReferences[i], resolutions[i]); + } + } + // Do not process the default library if: + // - The '--noLib' flag is used. + // - A 'no-default-lib' reference comment is encountered in + // processing the root files. + if (!skipDefaultLib) { + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var defaultLibraryFileName = getDefaultLibraryFileName(); + if (!options.lib && defaultLibraryFileName) { + processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + } + else { + ts.forEach(options.lib, function (libFileName) { + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false); + }); + } + } + missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + processingDefaultLibFiles = undefined; + processingOtherFiles = undefined; + } + ts.Debug.assert(!!missingFilePaths); + // Release any files we have acquired in the old program but are + // not part of the new program. + if (oldProgram && host.onReleaseOldSourceFile) { + var oldSourceFiles = oldProgram.getSourceFiles(); + for (var _a = 0, oldSourceFiles_1 = oldSourceFiles; _a < oldSourceFiles_1.length; _a++) { + var oldSourceFile = oldSourceFiles_1[_a]; + if (!getSourceFile(oldSourceFile.path) || shouldCreateNewSourceFile) { + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions()); + } + } + } + // unconditionally set oldProgram to undefined to prevent it from being captured in closure + oldProgram = undefined; + program = { + getRootFileNames: function () { return rootNames; }, + getSourceFile: getSourceFile, + getSourceFileByPath: getSourceFileByPath, + getSourceFiles: function () { return files; }, + getMissingFilePaths: function () { return missingFilePaths; }, + getCompilerOptions: function () { return options; }, + getSyntacticDiagnostics: getSyntacticDiagnostics, + getOptionsDiagnostics: getOptionsDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getSemanticDiagnostics: getSemanticDiagnostics, + getSuggestionDiagnostics: getSuggestionDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getClassifiableNames: getClassifiableNames, + getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker, + getCommonSourceDirectory: getCommonSourceDirectory, + emit: emit, + getCurrentDirectory: function () { return currentDirectory; }, + getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); }, + getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); }, + getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, + getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, + getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, + isSourceFileDefaultLibrary: isSourceFileDefaultLibrary, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, + getSourceFileFromReference: getSourceFileFromReference, + getLibFileFromReference: getLibFileFromReference, + sourceFileToPackageName: sourceFileToPackageName, + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile, + getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, + getProjectReferences: getProjectReferences + }; + verifyCompilerOptions(); + ts.performance.mark("afterProgram"); + ts.performance.measure("Program", "beforeProgram", "afterProgram"); + return program; + function compareDefaultLibFiles(a, b) { + return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b)); + } + function getDefaultLibFilePriority(a) { + if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) { + var basename = ts.getBaseFileName(a.fileName); + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") + return 0; + var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts"); + var index = ts.libs.indexOf(name); + if (index !== -1) + return index + 1; + } + return ts.libs.length + 2; + } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCommonSourceDirectory() { + if (commonSourceDirectory === undefined) { + var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary); }); + if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) { + // If a rootDir is specified use it as the commonSourceDirectory + commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory); + } + else if (options.composite) { + // Project compilations never infer their root from the input source paths + commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath)); // TODO: GH#18217 + checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory); + } + else { + commonSourceDirectory = computeCommonSourceDirectory(emittedFiles); + } + if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += ts.directorySeparator; + } + } + return commonSourceDirectory; + } + function getClassifiableNames() { + if (!classifiableNames) { + // Initialize a checker so that all our files are bound. + getTypeChecker(); + classifiableNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var sourceFile = files_2[_i]; + ts.copyEntries(sourceFile.classifiableNames, classifiableNames); + } + } + return classifiableNames; + } + function resolveModuleNamesReusingOldState(moduleNames, containingFile, file, oldProgramState) { + if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { + // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules, + // the best we can do is fallback to the default logic. + return resolveModuleNamesWorker(moduleNames, containingFile); + } + var oldSourceFile = oldProgramState.program && oldProgramState.program.getSourceFile(containingFile); + if (oldSourceFile !== file && file.resolvedModules) { + // `file` was created for the new program. + // + // We only set `file.resolvedModules` via work from the current function, + // so it is defined iff we already called the current function on `file`. + // That call happened no later than the creation of the `file` object, + // which per above occurred during the current program creation. + // Since we assume the filesystem does not change during program creation, + // it is safe to reuse resolutions from the earlier call. + var result_4 = []; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; + var resolvedModule = file.resolvedModules.get(moduleName); + result_4.push(resolvedModule); + } + return result_4; + } + // At this point, we know at least one of the following hold: + // - file has local declarations for ambient modules + // - old program state is available + // With this information, we can infer some module resolutions without performing resolution. + /** An ordered list of module names for which we cannot recover the resolution. */ + var unknownModuleNames; + /** + * The indexing of elements in this list matches that of `moduleNames`. + * + * Before combining results, result[i] is in one of the following states: + * * undefined: needs to be recomputed, + * * predictedToResolveToAmbientModuleMarker: known to be an ambient module. + * Needs to be reset to undefined before returning, + * * ResolvedModuleFull instance: can be reused. + */ + var result; + var reusedNames; + /** A transient placeholder used to mark predicted resolution in the result list. */ + var predictedToResolveToAmbientModuleMarker = {}; + for (var i = 0; i < moduleNames.length; i++) { + var moduleName = moduleNames[i]; + // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions + if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) { + var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName); + if (oldResolvedModule) { + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile); + } + (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule; + (reusedNames || (reusedNames = [])).push(moduleName); + continue; + } + } + // We know moduleName resolves to an ambient module provided that moduleName: + // - is in the list of ambient modules locally declared in the current source file. + // - resolved to an ambient module in the old program whose declaration is in an unmodified file + // (so the same module declaration will land in the new program) + var resolvesToAmbientModuleInNonModifiedFile = false; + if (ts.contains(file.ambientModuleNames, moduleName)) { + resolvesToAmbientModuleInNonModifiedFile = true; + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile); + } + } + else { + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + } + if (resolvesToAmbientModuleInNonModifiedFile) { + (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; + } + else { + // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result. + (unknownModuleNames || (unknownModuleNames = [])).push(moduleName); + } + } + var resolutions = unknownModuleNames && unknownModuleNames.length + ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames) + : ts.emptyArray; + // Combine results of resolutions and predicted results + if (!result) { + // There were no unresolved/ambient resolutions. + ts.Debug.assert(resolutions.length === moduleNames.length); + return resolutions; + } + var j = 0; + for (var i = 0; i < result.length; i++) { + if (result[i]) { + // `result[i]` is either a `ResolvedModuleFull` or a marker. + // If it is the former, we can leave it as is. + if (result[i] === predictedToResolveToAmbientModuleMarker) { + result[i] = undefined; // TODO: GH#18217 + } + } + else { + result[i] = resolutions[j]; + j++; + } + } + ts.Debug.assert(j === resolutions.length); + return result; + // If we change our policy of rechecking failed lookups on each program create, + // we should adjust the value returned here. + function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState) { + var resolutionToFile = ts.getResolvedModule(oldProgramState.oldSourceFile, moduleName); // TODO: GH#18217 + var resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { + // In the old program, we resolved to an ambient module that was in the same + // place as we expected to find an actual module file. + // We actually need to return 'false' here even though this seems like a 'true' case + // because the normal module resolution algorithm will find this anyway. + return false; + } + var ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); + if (!(ambientModule && ambientModule.declarations)) { + return false; + } + // at least one of declarations should come from non-modified source file + var firstUnmodifiedFile = ts.forEach(ambientModule.declarations, function (d) { + var f = ts.getSourceFileOfNode(d); + return !ts.contains(oldProgramState.modifiedFilePaths, f.path) && f; + }); + if (!firstUnmodifiedFile) { + return false; + } + if (ts.isTraceEnabled(options, host)) { + ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, firstUnmodifiedFile.fileName); + } + return true; + } + } + function tryReuseStructureFromOldProgram() { + if (!oldProgram) { + return 0 /* Not */; + } + // check properties that can affect structure of the program or module resolution strategy + // if any of these properties has changed - structure cannot be reused + var oldOptions = oldProgram.getCompilerOptions(); + if (ts.changesAffectModuleResolution(oldOptions, options)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */))); + // there is an old program, check if we can reuse its structure + var oldRootNames = oldProgram.getRootFileNames(); + if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) { + return oldProgram.structureIsReused = 0 /* Not */; + } + // Check if any referenced project tsconfig files are different + var oldRefs = oldProgram.getProjectReferences(); + if (projectReferences) { + if (!oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + for (var i = 0; i < projectReferences.length; i++) { + var oldRef = oldRefs[i]; + if (oldRef) { + var newRef = parseProjectReferenceConfigFile(projectReferences[i]); + if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { + // Resolved project reference has gone missing or changed + return oldProgram.structureIsReused = 0 /* Not */; + } + } + else { + // A previously-unresolved reference may be resolved now + if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + } + } + else { + if (oldRefs) { + return oldProgram.structureIsReused = 0 /* Not */; + } + } + // check if program source files has changed in the way that can affect structure of the program + var newSourceFiles = []; + var filePaths = []; + var modifiedSourceFiles = []; + oldProgram.structureIsReused = 2 /* Completely */; + // If the missing file paths are now present, it can change the progam structure, + // and hence cant reuse the structure. + // This is same as how we dont reuse the structure if one of the file from old program is now missing + if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) { + return oldProgram.structureIsReused = 0 /* Not */; + } + 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_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) { + var oldSourceFile = oldSourceFiles_2[_i]; + var newSourceFile = host.getSourceFileByPath + ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath || oldSourceFile.path, options.target, /*onError*/ undefined, shouldCreateNewSourceFile) + : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217 + 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); + 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 (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) { + // 'lib' references has changed. Matches behavior in changesAffectModuleResolution + return oldProgram.structureIsReused = 0 /* Not */; + } + if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { + // value of no-default-lib has changed + // this will affect if default library is injected into the list of files + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check tripleslash references + if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) { + // tripleslash references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // check imports and module augmentations + collectExternalModuleReferences(newSourceFile); + if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) { + // imports has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) { + // moduleAugmentations has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if ((oldSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 1572864 /* PermanentlySetIncrementalFlags */)) { + // dynamicImport has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) { + // 'types' references has changed + oldProgram.structureIsReused = 1 /* SafeModules */; + } + // tentatively approve the file + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + else if (hasInvalidatedResolution(oldSourceFile.path)) { + // 'module/types' references could have changed + oldProgram.structureIsReused = 1 /* SafeModules */; + // add file to the modified list so that we will resolve it later + modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile }); + } + // if file has passed all checks it should be safe to reuse it + newSourceFiles.push(newSourceFile); + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + modifiedFilePaths = modifiedSourceFiles.map(function (f) { return f.newFile.path; }); + // try to verify results of module resolution + for (var _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 = getModuleNames(newSourceFile); + var oldProgramState = { program: oldProgram, oldSourceFile: oldSourceFile, modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile, oldProgramState); + // ensure that module resolution results are still correct + var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions); + } + else { + newSourceFile.resolvedModules = oldSourceFile.resolvedModules; + } + } + if (resolveTypeReferenceDirectiveNamesWorker) { + var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (x) { return x.fileName; }); + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); + // ensure that types resolutions are still correct + var resolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo); + if (resolutionsChanged) { + oldProgram.structureIsReused = 1 /* SafeModules */; + newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions); + } + else { + newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames; + } + } + } + if (oldProgram.structureIsReused !== 2 /* Completely */) { + return oldProgram.structureIsReused; + } + if (host.hasChangedAutomaticTypeDirectiveNames) { + return oldProgram.structureIsReused = 1 /* SafeModules */; + } + missingFilePaths = oldProgram.getMissingFilePaths(); + // update fileName -> file mapping + for (var i = 0; i < newSourceFiles.length; i++) { + filesByName.set(filePaths[i], newSourceFiles[i]); + // Set the file as found during node modules search if it was found that way in old progra, + if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(filePaths[i]))) { + sourceFilesFoundSearchingNodeModules.set(filePaths[i], true); + } + } + files = newSourceFiles; + fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); + for (var _c = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _c < modifiedSourceFiles_2.length; _c++) { + var modifiedFile = modifiedSourceFiles_2[_c]; + fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); + } + resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); + resolvedProjectReferences = oldProgram.getProjectReferences(); + sourceFileToPackageName = oldProgram.sourceFileToPackageName; + redirectTargetsSet = oldProgram.redirectTargetsSet; + return oldProgram.structureIsReused = 2 /* Completely */; + } + function getEmitHost(writeFileCallback) { + return __assign({ getPrependNodes: getPrependNodes, + getCanonicalFileName: getCanonicalFileName, getCommonSourceDirectory: program.getCommonSourceDirectory, getCompilerOptions: program.getCompilerOptions, getCurrentDirectory: function () { return currentDirectory; }, getNewLine: function () { return host.getNewLine(); }, getSourceFile: program.getSourceFile, getSourceFileByPath: program.getSourceFileByPath, getSourceFiles: program.getSourceFiles, isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary, writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }), isEmitBlocked: isEmitBlocked, readFile: function (f) { return host.readFile(f); }, fileExists: function (f) { + // Use local caches + var path = toPath(f); + if (getSourceFileByPath(path)) + return true; + if (ts.contains(missingFilePaths, path)) + return false; + // Before falling back to the host + return host.fileExists(f); + } }, (host.directoryExists ? { directoryExists: function (f) { return host.directoryExists(f); } } : {}), { useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); } }); + } + function getProjectReferences() { + if (!resolvedProjectReferences) + return; + return resolvedProjectReferences; + } + function getPrependNodes() { + if (!projectReferences) { + return ts.emptyArray; + } + var nodes = []; + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i].commandLine; + if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) { + // Upstream project didn't have outFile set -- skip (error will have been issued earlier) + if (!resolvedRefOpts.options.outFile) + continue; + var dtsFilename = ts.changeExtension(resolvedRefOpts.options.outFile, ".d.ts"); + var js = host.readFile(resolvedRefOpts.options.outFile) || "/* Input file " + resolvedRefOpts.options.outFile + " was missing */\r\n"; + var jsMapPath = resolvedRefOpts.options.outFile + ".map"; // TODO: try to read sourceMappingUrl comment from the file + var jsMap = host.readFile(jsMapPath); + var dts = host.readFile(dtsFilename) || "/* Input file " + dtsFilename + " was missing */\r\n"; + var dtsMapPath = dtsFilename + ".map"; + var dtsMap = host.readFile(dtsMapPath); + var node = ts.createInputFiles(js, dts, jsMap && jsMapPath, jsMap, dtsMap && dtsMapPath, dtsMap); + nodes.push(node); + } + } + return nodes; + } + function isSourceFileFromExternalLibrary(file) { + return !!sourceFilesFoundSearchingNodeModules.get(file.path); + } + function isSourceFileDefaultLibrary(file) { + if (file.hasNoDefaultLib) { + return true; + } + if (!options.noLib) { + return false; + } + // If '--lib' is not specified, include default library file according to '--target' + // otherwise, using options specified in '--lib' instead of '--target' default library file + var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive; + if (!options.lib) { + return equalityComparer(file.fileName, getDefaultLibraryFileName()); + } + else { + return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); }); + } + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } + function getTypeChecker() { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); + } + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers); }); + } + function isEmitBlocked(emitFileName) { + return hasEmitBlockingDiagnostics.has(toPath(emitFileName)); + } + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var declarationDiagnostics = []; + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; + } + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } + } + } + // Create the emit resolver outside of the "emitTime" tracking code below. That way + // any cost associated with it (like type checking) are appropriate associated with + // the type-checking counter. + // + // If the -out option is specified, we should not pass the source file to getEmitResolver. + // This is because in the -out scenario all files need to be emitted, and therefore all + // files need to be type checked. And the way to specify that all files need to be type + // checked is to not pass the file to getEmitResolver. + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken); + ts.performance.mark("beforeEmit"); + var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, // TODO: GH#18217 + emitOnlyDtsFiles, transformers, customTransformers && customTransformers.afterDeclarations); + ts.performance.mark("afterEmit"); + ts.performance.measure("Emit", "beforeEmit", "afterEmit"); + return emitResult; + } + function getSourceFile(fileName) { + return getSourceFileByPath(toPath(fileName)); + } + function getSourceFileByPath(path) { + return filesByName.get(path); + } + function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { + if (sourceFile) { + return getDiagnostics(sourceFile, cancellationToken); + } + return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) { + if (cancellationToken) { + cancellationToken.throwIfCancellationRequested(); + } + return getDiagnostics(sourceFile, cancellationToken); + })); + } + function getSyntacticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + } + function getDeclarationDiagnostics(sourceFile, cancellationToken) { + var options = program.getCompilerOptions(); + // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit) + if (!sourceFile || options.out || options.outFile) { + return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + else { + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); + } + } + function getSyntacticDiagnosticsForFile(sourceFile) { + // For JavaScript files, we report semantic errors for using TypeScript-only + // constructs from within a JavaScript file as syntactic errors. + if (ts.isSourceFileJavaScript(sourceFile)) { + if (!sourceFile.additionalSyntacticDiagnostics) { + sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + } + return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); + } + return sourceFile.parseDiagnostics; + } + function runWithCancellationToken(func) { + try { + return func(); + } + catch (e) { + if (e instanceof ts.OperationCanceledException) { + // We were canceled while performing the operation. Because our type checker + // might be a bad state, we need to throw it away. + // + // Note: we are overly aggressive here. We do not actually *have* to throw away + // the "noDiagnosticsTypeChecker". However, for simplicity, i'd like to keep + // the lifetimes of these two TypeCheckers the same. Also, we generally only + // cancel when the user has made a change anyways. And, in that case, we (the + // program instance) will get thrown away anyways. So trying to keep one of + // these type checkers alive doesn't serve much purpose. + noDiagnosticsTypeChecker = undefined; + diagnosticsProducingTypeChecker = undefined; + } + throw e; + } + } + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedSemanticDiagnosticsForFile, getSemanticDiagnosticsForFileNoCache); + } + function getSemanticDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. + // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a + // '/// ' directive. + if (options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) { + return ts.emptyArray; + } + var typeChecker = getDiagnosticsProducingTypeChecker(); + ts.Debug.assert(!!sourceFile.bindDiagnostics); + var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + var includeBindAndCheckDiagnostics = sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || + sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; + var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; + var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; + var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + var diagnostics; + for (var _i = 0, _a = [bindDiagnostics, checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile, isCheckJs ? sourceFile.jsDocDiagnostics : undefined]; _i < _a.length; _i++) { + var diags = _a[_i]; + if (diags) { + for (var _b = 0, diags_1 = diags; _b < diags_1.length; _b++) { + var diag = diags_1[_b]; + if (shouldReportDiagnostic(diag)) { + diagnostics = ts.append(diagnostics, diag); + } + } + } + } + return diagnostics; + }); + } + function getSuggestionDiagnostics(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken); + }); + } + /** + * Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines + */ + function shouldReportDiagnostic(diagnostic) { + var file = diagnostic.file, start = diagnostic.start; + if (file) { + var lineStarts = ts.getLineStarts(file); + var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line; // TODO: GH#18217 + while (line > 0) { + var previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]); + var result = ignoreDiagnosticCommentRegEx.exec(previousLineText); + if (!result) { + // non-empty line + return true; + } + if (result[3]) { + // @ts-ignore + return false; + } + line--; + } + } + return true; + } + function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + return runWithCancellationToken(function () { + var diagnostics = []; + var parent = sourceFile; + walk(sourceFile); + return diagnostics; + function walk(node) { + // Return directly from the case if the given node doesnt want to visit each child + // Otherwise break to visit each child + switch (parent.kind) { + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + if (parent.questionToken === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); + return; + } + // falls through + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 235 /* VariableDeclaration */: + // type annotation + if (parent.type === node) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.types_can_only_be_used_in_a_ts_file)); + return; + } + } + switch (node.kind) { + case 246 /* ImportEqualsDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_a_ts_file)); + return; + case 252 /* ExportAssignment */: + if (node.isExportEquals) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 271 /* HeritageClause */: + var heritageClause = node; + if (heritageClause.token === 108 /* ImplementsKeyword */) { + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 239 /* InterfaceDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.interface_declarations_can_only_be_used_in_a_ts_file)); + return; + case 242 /* ModuleDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.module_declarations_can_only_be_used_in_a_ts_file)); + return; + case 240 /* TypeAliasDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.type_aliases_can_only_be_used_in_a_ts_file)); + return; + case 241 /* EnumDeclaration */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.enum_declarations_can_only_be_used_in_a_ts_file)); + return; + case 211 /* NonNullExpression */: + diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.non_null_assertions_can_only_be_used_in_a_ts_file)); + return; + case 210 /* AsExpression */: + diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.type_assertion_expressions_can_only_be_used_in_a_ts_file)); + return; + case 192 /* TypeAssertionExpression */: + ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. + } + var prevParent = parent; + parent = node; + ts.forEachChild(node, walk, walkArray); + parent = prevParent; + } + function walkArray(nodes) { + if (parent.decorators === nodes && !options.experimentalDecorators) { + diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning)); + } + switch (parent.kind) { + case 238 /* ClassDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + // Check type parameters + if (nodes === parent.typeParameters) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); + return; + } + // falls through + case 217 /* VariableStatement */: + // Check modifiers + if (nodes === parent.modifiers) { + return checkModifiers(nodes, parent.kind === 217 /* VariableStatement */); + } + break; + case 152 /* PropertyDeclaration */: + // Check modifiers of property declaration + if (nodes === parent.modifiers) { + for (var _i = 0, _a = nodes; _i < _a.length; _i++) { + var modifier = _a[_i]; + if (modifier.kind !== 115 /* StaticKeyword */) { + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + } + } + return; + } + break; + case 149 /* Parameter */: + // Check modifiers of parameter declaration + if (nodes === parent.modifiers) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); + return; + } + break; + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + // Check type arguments + if (nodes === parent.typeArguments) { + diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); + return; + } + break; + } + for (var _b = 0, nodes_6 = nodes; _b < nodes_6.length; _b++) { + var node = nodes_6[_b]; + walk(node); + } + } + function checkModifiers(modifiers, isConstValid) { + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; + switch (modifier.kind) { + case 76 /* ConstKeyword */: + if (isConstValid) { + continue; + } + // to report error, + // falls through + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 132 /* ReadonlyKeyword */: + case 124 /* DeclareKeyword */: + case 117 /* AbstractKeyword */: + diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, ts.tokenToString(modifier.kind))); + break; + // These are all legal modifiers. + case 115 /* StaticKeyword */: + case 84 /* ExportKeyword */: + case 79 /* DefaultKeyword */: + } + } + } + function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) { + var start = nodes.pos; + return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2); + } + // Since these are syntactic diagnostics, parent might not have been set + // this means the sourceFile cannot be infered from the node + function createDiagnosticForNode(node, message, arg0, arg1, arg2) { + return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2); + } + }); + } + function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { + return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + } + function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + return runWithCancellationToken(function () { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + // Don't actually write any files since we're just getting diagnostics. + return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile); + }); + } + function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) { + var cachedResult = sourceFile + ? cache.perFile && cache.perFile.get(sourceFile.path) + : cache.allDiagnostics; + if (cachedResult) { + return cachedResult; + } + var result = getDiagnostics(sourceFile, cancellationToken) || ts.emptyArray; // TODO: GH#18217 + if (sourceFile) { + if (!cache.perFile) { + cache.perFile = ts.createMap(); + } + cache.perFile.set(sourceFile.path, result); + } + else { + cache.allDiagnostics = result; + } + return result; + } + function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { + return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + } + function getOptionsDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), options.configFile ? programDiagnostics.getDiagnostics(options.configFile.fileName) : []))); + } + function getGlobalDiagnostics() { + return ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()); + } + function getConfigFileParsingDiagnostics() { + return configFileParsingDiagnostics || ts.emptyArray; + } + function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) { + processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined); + } + function fileReferenceIsEqualTo(a, b) { + return a.fileName === b.fileName; + } + function moduleNameIsEqualTo(a, b) { + return a.kind === 71 /* Identifier */ + ? b.kind === 71 /* Identifier */ && a.escapedText === b.escapedText + : b.kind === 9 /* StringLiteral */ && a.text === b.text; + } + function collectExternalModuleReferences(file) { + if (file.imports) { + return; + } + var isJavaScriptFile = ts.isSourceFileJavaScript(file); + var isExternalModuleFile = ts.isExternalModule(file); + // file.imports may not be undefined if there exists dynamic import + var imports; + var moduleAugmentations; + var ambientModules; + // If we are importing helpers, we need to add a synthetic reference to resolve the + // helpers library. + if (options.importHelpers + && (options.isolatedModules || isExternalModuleFile) + && !file.isDeclarationFile) { + // synthesize 'import "tslib"' declaration + var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); + var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); + externalHelpersModuleReference.parent = importDecl; + importDecl.parent = file; + imports = [externalHelpersModuleReference]; + } + for (var _i = 0, _a = file.statements; _i < _a.length; _i++) { + var node = _a[_i]; + collectModuleReferences(node, /*inAmbientModule*/ false); + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(node); + } + } + if ((file.flags & 524288 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) { + collectDynamicImportOrRequireCalls(file.endOfFileToken); + } + file.imports = imports || ts.emptyArray; + file.moduleAugmentations = moduleAugmentations || ts.emptyArray; + file.ambientModuleNames = ambientModules || ts.emptyArray; + return; + function collectModuleReferences(node, inAmbientModule) { + if (ts.isAnyImportOrReExport(node)) { + var moduleNameExpr = ts.getExternalModuleName(node); + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) { + imports = ts.append(imports, moduleNameExpr); + } + } + else if (ts.isModuleDeclaration(node)) { + if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) { + var nameText = ts.getTextOfIdentifierOrLiteral(node.name); + // Ambient module declarations can be interpreted as augmentations for some existing external modules. + // This will happen in two cases: + // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope + // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name + // immediately nested in top level ambient module declaration . + if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) { + (moduleAugmentations || (moduleAugmentations = [])).push(node.name); + } + else if (!inAmbientModule) { + if (file.isDeclarationFile) { + // for global .d.ts files record name of ambient module + (ambientModules || (ambientModules = [])).push(nameText); + } + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + // NOTE: body of ambient module is always a module block, if it exists + var body = node.body; + if (body) { + for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + collectModuleReferences(statement, /*inAmbientModule*/ true); + } + } + } + } + } + } + function collectDynamicImportOrRequireCalls(node) { + if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) { + imports = ts.append(imports, node.arguments[0]); + } + // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error. + else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) { + imports = ts.append(imports, node.arguments[0]); + } + else if (ts.isLiteralImportTypeNode(node)) { + imports = ts.append(imports, node.argument.literal); + } + collectDynamicImportOrRequireCallsForEachChild(node); + if (ts.hasJSDocNodes(node)) { + ts.forEach(node.jsDoc, collectDynamicImportOrRequireCallsForEachChild); + } + } + function collectDynamicImportOrRequireCallsForEachChild(node) { + ts.forEachChild(node, collectDynamicImportOrRequireCalls); + } + } + function getLibFileFromReference(ref) { + var libName = ref.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName)); + } + } + /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ + function getSourceFileFromReference(referencingFile, ref) { + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + } + function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { + if (ts.hasExtension(fileName)) { + if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule || supportedExtensions, function (extension) { return ts.fileExtensionIs(host.getCanonicalFileName(fileName), extension); })) { + if (fail) + fail(ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'"); + return undefined; + } + var sourceFile = getSourceFile(fileName); + if (fail) { + if (!sourceFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName); + } + else { + fail(ts.Diagnostics.File_0_not_found, fileName); + } + } + else if (refFile && host.getCanonicalFileName(fileName) === host.getCanonicalFileName(refFile.fileName)) { + fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself); + } + } + return sourceFile; + } + else { + var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName); + if (sourceFileNoExtension) + return sourceFileNoExtension; + if (fail && options.allowNonTsExtensions) { + fail(ts.Diagnostics.File_0_not_found, fileName); + return undefined; + } + var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); }); + if (fail && !sourceFileWithAddedExtension) + fail(ts.Diagnostics.File_0_not_found, fileName + ".ts" /* Ts */); + return sourceFileWithAddedExtension; + } + } + /** This has side effects through `findSourceFile`. */ + function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile, refPos, refEnd) { + getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, refPos, refEnd, packageId); }, // TODO: GH#18217 + function (diagnostic) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + fileProcessingDiagnostics.add(refFile !== undefined && refEnd !== undefined && refPos !== undefined + ? ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, diagnostic].concat(args)) : ts.createCompilerDiagnostic.apply(void 0, [diagnostic].concat(args))); + }, refFile); + } + function reportFileNamesDifferOnlyInCasingError(fileName, existingFileName, refFile, refPos, refEnd) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFileName)); + } + else { + 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, ignoreNoDefaultLib, 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 + // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected + if (file_1 && options.forceConsistentCasingInFileNames) { + var inputName = fileName; + var checkedName = file_1.fileName; + var isRedirect = toPath(checkedName) !== toPath(inputName); + if (isRedirect) { + inputName = getProjectReferenceRedirect(fileName) || fileName; + } + if (ts.getNormalizedAbsolutePath(checkedName, currentDirectory) !== ts.getNormalizedAbsolutePath(inputName, currentDirectory)) { + reportFileNamesDifferOnlyInCasingError(inputName, checkedName, refFile, refPos, refEnd); + } + } + // If the file was previously found via a node_modules search, but is now being processed as a root file, + // then everything it sucks in may also be marked incorrectly, and needs to be checked again. + if (file_1 && sourceFilesFoundSearchingNodeModules.get(file_1.path) && currentNodeModulesDepth === 0) { + sourceFilesFoundSearchingNodeModules.set(file_1.path, false); + if (!options.noResolve) { + processReferencedFiles(file_1, isDefaultLib); + processTypeReferenceDirectives(file_1); + } + processLibReferenceDirectives(file_1); + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + // See if we need to reprocess the imports due to prior skipped imports + else if (file_1 && modulesWithElidedImports.get(file_1.path)) { + if (currentNodeModulesDepth < maxNodeModuleJsDepth) { + modulesWithElidedImports.set(file_1.path, false); + processImportedModules(file_1); + } + } + return file_1; + } + var redirectedPath; + if (refFile) { + var redirect = getProjectReferenceRedirect(fileName); + if (redirect) { + (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); + fileName = redirect; + // Once we start redirecting to a file, we can potentially come back to it + // via a back-reference from another file in the .d.ts folder. If that happens we'll + // end up trying to add it to the program *again* because we were tracking it via its + // original (un-redirected) name. So we have to map both the original path and the redirected path + // to the source file we're about to find/create + redirectedPath = toPath(redirect); + } + } + // We haven't looked for this file, do so now and cache result + var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { + if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { + fileProcessingDiagnostics.add(ts.createFileDiagnostic(refFile, refPos, refEnd - refPos, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + else { + fileProcessingDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); + } + }, shouldCreateNewSourceFile); + if (packageId) { + var packageIdKey = ts.packageIdToString(packageId); + 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); // TODO: GH#18217 + redirectTargetsSet.set(fileFromPackageId.path, true); + filesByName.set(path, dupFile); + sourceFileToPackageName.set(path, packageId.name); + processingOtherFiles.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 (redirectedPath) { + filesByName.set(redirectedPath, file); + } + if (file) { + sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0); + file.path = path; + file.resolvedPath = toPath(fileName); + if (host.useCaseSensitiveFileNames()) { + var pathLowerCase = path.toLowerCase(); + // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case + var existingFile = filesByNameIgnoreCase.get(pathLowerCase); + if (existingFile) { + reportFileNamesDifferOnlyInCasingError(fileName, existingFile.fileName, refFile, refPos, refEnd); + } + else { + filesByNameIgnoreCase.set(pathLowerCase, file); + } + } + skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib); + if (!options.noResolve) { + processReferencedFiles(file, isDefaultLib); + processTypeReferenceDirectives(file); + } + processLibReferenceDirectives(file); + // always process imported modules to record module name resolutions + processImportedModules(file); + if (isDefaultLib) { + processingDefaultLibFiles.push(file); + } + else { + processingOtherFiles.push(file); + } + } + return file; + } + function getProjectReferenceRedirect(fileName) { + var path = toPath(fileName); + // If this file is produced by a referenced project, we need to rewrite it to + // look in the output folder of the referenced project rather than the input + var normalized = ts.getNormalizedAbsolutePath(fileName, path); + var result; + projectReferenceRedirects.forEach(function (v, k) { + if (result !== undefined) { + return undefined; + } + if (normalized.indexOf(k) === 0) { + result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); + } + }); + return result; + } + function processReferencedFiles(file, isDefaultLib) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + processSourceFile(referencedFileName, isDefaultLib, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, file, ref.pos, ref.end); + }); + } + function processTypeReferenceDirectives(file) { + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ref.fileName.toLocaleLowerCase(); }); + if (!typeDirectives) { + return; + } + var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName); + for (var i = 0; i < typeDirectives.length; i++) { + var ref = file.typeReferenceDirectives[i]; + var resolvedTypeReferenceDirective = resolutions[i]; + // store resolved type directive on the file + var fileName = ref.fileName.toLocaleLowerCase(); + ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective); + processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end); + } + } + function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile, refPos, refEnd) { + // If we already found this library as a primary reference - nothing to do + var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective); + if (previousResolution && previousResolution.primary) { + return; + } + var saveResolution = true; + if (resolvedTypeReferenceDirective) { + if (resolvedTypeReferenceDirective.primary) { + // resolved from the primary path + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); // TODO: GH#18217 + } + else { + // If we already resolved to this file, it must have been a secondary reference. Check file contents + // for sameness and possibly issue an error + if (previousResolution) { + // Don't bother reading the file again if it's the same file. + if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { + var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); + if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, // TODO: GH#18217 + ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName)); + } + } + // don't overwrite previous resolution result + saveResolution = false; + } + else { + // First resolution of this library + processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile, refPos, refEnd); + } + } + } + else { + fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective)); // TODO: GH#18217 + } + if (saveResolution) { + resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective); + } + } + function processLibReferenceDirectives(file) { + ts.forEach(file.libReferenceDirectives, function (libReference) { + var libName = libReference.fileName.toLocaleLowerCase(); + var libFileName = ts.libMap.get(libName); + if (libFileName) { + // we ignore any 'no-default-lib' reference set on this file. + processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true); + } + else { + var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts"); + var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity); + var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0; + fileProcessingDiagnostics.add(createDiagnostic(file, libReference.pos, libReference.end, message, libName, suggestion)); + } + }); + } + function createDiagnostic(refFile, refPos, refEnd, message) { + var args = []; + for (var _i = 4; _i < arguments.length; _i++) { + args[_i - 4] = arguments[_i]; + } + if (refFile === undefined || refPos === undefined || refEnd === undefined) { + return ts.createCompilerDiagnostic.apply(void 0, [message].concat(args)); + } + else { + return ts.createFileDiagnostic.apply(void 0, [refFile, refPos, refEnd - refPos, message].concat(args)); + } + } + function getCanonicalFileName(fileName) { + return host.getCanonicalFileName(fileName); + } + function processImportedModules(file) { + collectExternalModuleReferences(file); + if (file.imports.length || file.moduleAugmentations.length) { + // Because global augmentation doesn't have string literal name, we can check for global augmentation as such. + var moduleNames = getModuleNames(file); + var oldProgramState = { program: oldProgram, oldSourceFile: oldProgram && oldProgram.getSourceFile(file.fileName), modifiedFilePaths: modifiedFilePaths }; + var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.fileName, currentDirectory), file, oldProgramState); + ts.Debug.assert(resolutions.length === moduleNames.length); + for (var i = 0; i < moduleNames.length; i++) { + var resolution = resolutions[i]; + ts.setResolvedModule(file, moduleNames[i], resolution); + if (!resolution) { + continue; + } + var isFromNodeModulesSearch = resolution.isExternalLibraryImport; + var isJsFile = !ts.resolutionExtensionIsTypeScriptOrJson(resolution.extension); + var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; + var resolvedFileName = resolution.resolvedFileName; + if (isFromNodeModulesSearch) { + currentNodeModulesDepth++; + } + // add file to program only if: + // - resolution was successful + // - noResolve is falsy + // - module name comes from the list of imports + // - it's not a top level JavaScript module that exceeded the search max + var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth; + // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs') + // This may still end up being an untyped module -- the file won't be included but imports will be allowed. + var shouldAddFile = resolvedFileName + && !getResolutionDiagnostic(options, resolution) + && !options.noResolve + && i < file.imports.length + && !elideImport + && !(isJsFile && !options.allowJs) + && (ts.isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & 2097152 /* JSDoc */)); + if (elideImport) { + modulesWithElidedImports.set(file.path, true); + } + else if (shouldAddFile) { + var path = toPath(resolvedFileName); + var pos = ts.skipTrivia(file.text, file.imports[i].pos); + findSourceFile(resolvedFileName, path, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, file, pos, file.imports[i].end, resolution.packageId); + } + if (isFromNodeModulesSearch) { + currentNodeModulesDepth--; + } + } + } + else { + // no imports - drop cached module resolutions + file.resolvedModules = undefined; + } + } + function computeCommonSourceDirectory(sourceFiles) { + var fileNames = []; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var file = sourceFiles_2[_i]; + if (!file.isDeclarationFile) { + fileNames.push(file.fileName); + } + } + return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName); + } + function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) { + var allFilesBelongToPath = true; + if (sourceFiles) { + var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + for (var _i = 0, sourceFiles_3 = sourceFiles; _i < sourceFiles_3.length; _i++) { + var sourceFile = sourceFiles_3[_i]; + if (!sourceFile.isDeclarationFile) { + var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory)); + allFilesBelongToPath = false; + } + } + } + } + return allFilesBelongToPath; + } + function parseProjectReferenceConfigFile(ref) { + // The actual filename (i.e. add "/tsconfig.json" if necessary) + var refPath = resolveProjectReferencePath(host, ref); + // An absolute path pointing to the containing directory of the config file + var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory()); + var sourceFile = host.getSourceFile(refPath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath); + return { commandLine: commandLine, sourceFile: sourceFile }; + } + function addProjectReferenceRedirects(referencedProject, target) { + var rootDir = ts.normalizePath(referencedProject.options.rootDir || ts.getDirectoryPath(referencedProject.options.configFilePath)); // TODO: GH#18217 + target.set(rootDir, getDeclarationOutputDirectory(referencedProject)); + } + function getDeclarationOutputDirectory(proj) { + return proj.options.declarationDir || + proj.options.outDir || + ts.getDirectoryPath(proj.options.configFilePath); // TODO: GH#18217 + } + function verifyCompilerOptions() { + if (options.strictPropertyInitialization && !options.strictNullChecks) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks"); + } + if (options.isolatedModules) { + if (options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"); + } + if (options.noEmitOnError) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"); + } + if (options.out) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"); + } + if (options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"); + } + } + if (options.inlineSourceMap) { + if (options.sourceMap) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"); + } + if (options.mapRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"); + } + } + if (options.paths && options.baseUrl === undefined) { + createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths"); + } + if (options.composite) { + if (options.declaration === false) { + createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration"); + } + } + if (projectReferences) { + for (var i = 0; i < projectReferences.length; i++) { + var ref = projectReferences[i]; + var resolvedRefOpts = resolvedProjectReferences[i] && resolvedProjectReferences[i].commandLine.options; + if (resolvedRefOpts === undefined) { + createDiagnosticForReference(i, ts.Diagnostics.File_0_does_not_exist, ref.path); + continue; + } + if (!resolvedRefOpts.composite) { + createDiagnosticForReference(i, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + } + if (ref.prepend) { + if (resolvedRefOpts.outFile) { + if (!host.fileExists(resolvedRefOpts.outFile)) { + createDiagnosticForReference(i, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, resolvedRefOpts.outFile, ref.path); + } + } + else { + createDiagnosticForReference(i, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path); + } + } + } + } + // List of collected files is complete; validate exhautiveness if this is a project with a file list + if (options.composite && rootNames.length < files.length) { + var normalizedRootNames = rootNames.map(function (r) { return ts.normalizePath(r).toLowerCase(); }); + var sourceFiles = files.filter(function (f) { return !f.isDeclarationFile; }).map(function (f) { return ts.normalizePath(f.path).toLowerCase(); }); + var _loop_11 = function (file) { + if (normalizedRootNames.every(function (r) { return r !== file; })) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } + }; + for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { + var file = sourceFiles_4[_i]; + _loop_11(file); + } + } + if (options.paths) { + for (var key in options.paths) { + if (!ts.hasProperty(options.paths, key)) { + continue; + } + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { + createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key); + } + if (ts.isArray(options.paths[key])) { + var len = options.paths[key].length; + if (len === 0) { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key); + } + for (var i = 0; i < len; i++) { + var subst = options.paths[key][i]; + var typeOfSubst = typeof subst; + if (typeOfSubst === "string") { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key); + } + } + else { + createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst); + } + } + } + else { + createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key); + } + } + } + if (!options.sourceMap && !options.inlineSourceMap) { + if (options.inlineSources) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources"); + } + if (options.sourceRoot) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot"); + } + } + if (options.out && options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"); + } + if (options.mapRoot && !(options.sourceMap || options.declarationMap)) { + // Error to specify --mapRoot without --sourcemap + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap"); + } + if (options.declarationDir) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationDir", "declaration"); + } + if (options.out || options.outFile) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile"); + } + } + if (options.declarationMap && !ts.getEmitDeclarations(options)) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "declarationMap", "declaration"); + } + if (options.lib && options.noLib) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"); + } + if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict"); + } + var languageVersion = options.target || 0 /* ES3 */; + var outFile = options.outFile || options.out; + var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + if (options.isolatedModules) { + if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) { + createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target"); + } + var firstNonExternalModuleSourceFile = ts.forEach(files, function (f) { return !ts.isExternalModule(f) && !f.isDeclarationFile ? f : undefined; }); + if (firstNonExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); + } + } + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); + } + // Cannot specify module gen that isn't amd or system with --out + if (outFile) { + if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) { + createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module"); + } + else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) { + var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); + programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_compile_modules_using_option_0_unless_the_module_flag_is_amd_or_system, options.out ? "out" : "outFile")); + } + } + if (options.resolveJsonModule) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); + } + // Any emit other than common js is error + else if (ts.getEmitModuleKind(options) !== ts.ModuleKind.CommonJS) { + createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + } + } + // 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 || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + options.mapRoot) { // there is --mapRoot specified + // Precalculate and cache the common source directory + var dir = getCommonSourceDirectory(); + // If we failed to find a good common directory, but outDir is specified and at least one of our files is on a windows drive/URL/other resource, add a failure + if (options.outDir && dir === "" && ts.forEach(files, function (file) { return ts.getRootLength(file.fileName) > 1; })) { + createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir"); + } + } + if (!options.noEmit && options.allowJs && options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"); + } + if (options.checkJs && !options.allowJs) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs")); + } + if (options.emitDeclarationOnly) { + if (!options.declaration) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDeclarationOnly", "declaration"); + } + if (options.noEmit) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); + } + } + if (options.emitDecoratorMetadata && + !options.experimentalDecorators) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); + } + if (options.jsxFactory) { + if (options.reactNamespace) { + createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory"); + } + if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) { + createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory); + } + } + else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) { + createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace); + } + // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files + if (!options.noEmit && !options.suppressOutputPathCheck) { + var emitHost = getEmitHost(); + var emitFilesSeen_1 = ts.createMap(); + ts.forEachEmittedFile(emitHost, function (emitFileNames) { + if (!options.emitDeclarationOnly) { + verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1); + } + verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1); + }); + } + // Verify that all the emit files are unique and don't overwrite input files + function verifyEmitFilePath(emitFileName, emitFilesSeen) { + if (emitFileName) { + var emitFilePath = toPath(emitFileName); + // Report error if the output overwrites input file + if (filesByName.has(emitFilePath)) { + var chain_2; + if (!options.configFilePath) { + // The program is from either an inferred project or an external project + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + } + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); + } + var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; + // Report error if multiple files write into same file + if (emitFilesSeen.has(emitFileKey)) { + // Already seen the same emit file - report error + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName)); + } + else { + emitFilesSeen.set(emitFileKey, true); + } + } + } + } + function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) { + var pathProp = pathsSyntax_1[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer)) { + for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) { + var keyProps = _b[_a]; + var initializer = keyProps.initializer; + if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) { + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2)); + needCompilerDiagnostic = false; + } + } + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function createDiagnosticForOptionPaths(onKey, key, message, arg0) { + var needCompilerDiagnostic = true; + var pathsSyntax = getOptionPathsSyntax(); + for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) { + var pathProp = pathsSyntax_2[_i]; + if (ts.isObjectLiteralExpression(pathProp.initializer) && + createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) { + needCompilerDiagnostic = false; + } + } + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0)); + } + } + function getOptionsSyntaxByName(name) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + if (compilerOptionsObjectLiteralSyntax) { + return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name); + } + return undefined; + } + function getOptionPathsSyntax() { + return getOptionsSyntaxByName("paths") || ts.emptyArray; + } + function createDiagnosticForOptionName(message, option1, option2, option3) { + createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3); + } + function createOptionValueDiagnostic(option1, message, arg0) { + createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0); + } + function createDiagnosticForReference(index, message, arg0, arg1) { + var referencesSyntax = getProjectReferencesSyntax(); + if (referencesSyntax) { + if (createOptionDiagnosticInArrayLiteralSyntax(referencesSyntax, index, message, arg0, arg1)) { + return; + } + } + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1)); + } + function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) { + var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax(); + var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax || + !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2); + if (needCompilerDiagnostic) { + programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2)); + } + } + function getProjectReferencesSyntax() { + if (_referencesArrayLiteralSyntax === undefined) { + _referencesArrayLiteralSyntax = null; // tslint:disable-line:no-null-keyword + if (options.configFile) { + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); // TODO: GH#18217 + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "references"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isArrayLiteralExpression(prop.initializer)) { + _referencesArrayLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _referencesArrayLiteralSyntax; + } + function getCompilerOptionsObjectLiteralSyntax() { + if (_compilerOptionsObjectLiteralSyntax === undefined) { + _compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile); + if (jsonObjectLiteral) { + for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) { + var prop = _a[_i]; + if (ts.isObjectLiteralExpression(prop.initializer)) { + _compilerOptionsObjectLiteralSyntax = prop.initializer; + break; + } + } + } + } + return _compilerOptionsObjectLiteralSyntax; + } + function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) { + var props = ts.getPropertyAssignment(objectLiteral, key1, key2); + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2)); + } + return !!props.length; + } + function createOptionDiagnosticInArrayLiteralSyntax(arrayLiteral, index, message, arg0, arg1, arg2) { + if (arrayLiteral.elements.length <= index) { + // Out-of-bounds + return false; + } + programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, arrayLiteral.elements[index], message, arg0, arg1, arg2)); + return false; // TODO: GH#18217 This function always returns `false`!` + } + function blockEmittingOfFile(emitFileName, diag) { + hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); + programDiagnostics.add(diag); + } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + // If this is source file, its not emitted file + var filePath = toPath(file); + if (getSourceFileByPath(filePath)) { + return false; + } + // If options have --outFile or --out just check that + var out = options.outFile || options.out; + if (out) { + return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */); + } + // If declarationDir is specified, return if its a file in that directory + if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + // If --outDir, check if file is in that directory + if (options.outDir) { + return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); + } + if (ts.fileExtensionIsOneOf(filePath, ts.supportedJavascriptExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) { + // Otherwise just check if sourceFile with the name exists + var filePathWithoutExtension = ts.removeFileExtension(filePath); + return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) || + !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */)); + } + return false; + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } + } + ts.createProgram = createProgram; + /* @internal */ + function parseConfigHostFromCompilerHost(host) { + return { + fileExists: function (f) { return host.fileExists(f); }, + readDirectory: function (root, extensions, includes, depth) { return host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : []; }, + readFile: function (f) { return host.readFile(f); }, + useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), + getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + onUnRecoverableConfigFileDiagnostic: function () { return undefined; } + }; + } + ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + /** + * Returns the target config filename of a project reference. + * Note: The file might not exist. + */ + function resolveProjectReferencePath(host, ref) { + if (!host.fileExists(ref.path)) { + return ts.combinePaths(ref.path, "tsconfig.json"); + } + return ref.path; + } + ts.resolveProjectReferencePath = resolveProjectReferencePath; + /* @internal */ + /** + * Returns a DiagnosticMessage if we won't include a resolved module due to its extension. + * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to. + * This returns a diagnostic even if the module will be an untyped module. + */ + function getResolutionDiagnostic(options, _a) { + var extension = _a.extension; + switch (extension) { + case ".ts" /* Ts */: + case ".d.ts" /* Dts */: + case ".json" /* Json */: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check + // These are always allowed. + return undefined; + case ".tsx" /* Tsx */: + return needJsx(); + case ".jsx" /* Jsx */: + return needJsx() || needAllowJs(); + case ".js" /* Js */: + return needAllowJs(); + } + function needJsx() { + return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set; + } + function needAllowJs() { + return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type; + } + } + ts.getResolutionDiagnostic = getResolutionDiagnostic; + function getModuleNames(_a) { + var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations; + var res = imports.map(function (i) { return i.text; }); + for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) { + var aug = moduleAugmentations_1[_i]; + if (aug.kind === 9 /* StringLiteral */) { + res.push(aug.text); + } + // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`. + } + return res; + } +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217 + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + if (!info) + return ts.Debug.fail(); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; // TODO: GH#18217 + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + var _a; + var compilerOptions = programOfThisState.getCompilerOptions(); + // With --out or --outFile all outputs go into single file, all files depend on each other + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + var references = state.referencedMap.get(path); + if (references) { + var iterator = references.keys(); + for (var _b = iterator.next(), value = _b.value, done = _b.done; !done; _a = iterator.next(), value = _a.value, done = _a.done, _a) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { // TODO: GH#18217 + queue.push.apply(// TODO: GH#18217 + queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + // Has same size and every key is present in both maps + return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217 + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + var host; + var newProgram; + var oldProgram; + if (newProgramOrRootNames === undefined) { + ts.Debug.assert(hostOrOptions === undefined); + host = oldProgramOrHost; + oldProgram = configFileParsingDiagnosticsOrOldProgram; + ts.Debug.assert(!!oldProgram); + newProgram = oldProgram.getProgram(); + } + else if (ts.isArray(newProgramOrRootNames)) { + oldProgram = configFileParsingDiagnosticsOrOldProgram; + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { + newProgram = undefined; // TODO: GH#18217 + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; // TODO: GH#18217 + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = false; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + var diagnostics; + for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile_2 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getConfigFileParsingDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); /*@internal*/ var ts; (function (ts) { @@ -77818,8 +84661,10 @@ var ts; function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; + var filesWithInvalidatedNonRelativeUnresolvedImports; var allFilesHaveInvalidatedResolution = false; - var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var nonRelativeExternalModuleResolutions = ts.createMultiMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217 var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. // The key in the map is source file's path. @@ -77840,7 +84685,7 @@ var ts; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); - var rootPath = rootDir && resolutionHost.toPath(rootDir); + var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217 // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames var typeRootsWatches = ts.createMap(); return { @@ -77851,9 +84696,11 @@ var ts; startCachingPerDirectoryResolution: clearPerDirectoryResolutions, finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, resolveModuleNames: resolveModuleNames, + getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, + setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, createHasInvalidatedResolution: createHasInvalidatedResolution, updateTypeRootsWatch: updateTypeRootsWatch, closeTypeRootsWatch: closeTypeRootsWatch, @@ -77874,6 +84721,7 @@ var ts; function clear() { ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); customFailedLookupPaths.clear(); + nonRelativeExternalModuleResolutions.clear(); closeTypeRootsWatch(); resolvedModuleNames.clear(); resolvedTypeReferenceDirectives.clear(); @@ -77890,6 +84738,14 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } + function isFileWithInvalidatedNonRelativeUnresolvedImports(path) { + if (!filesWithInvalidatedNonRelativeUnresolvedImports) { + return false; + } + // Invalidated if file has unresolved imports + var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); + return !!value && !!value.length; + } function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { // Any file asked would have invalidated resolution @@ -77898,22 +84754,26 @@ var ts; } var collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = undefined; - return function (path) { return collected && collected.has(path); }; + return function (path) { return (!!collected && collected.has(path)) || + isFileWithInvalidatedNonRelativeUnresolvedImports(path); }; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); nonRelaticeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); + nonRelativeExternalModuleResolutions.clear(); } function finishCachingPerDirectoryResolution() { allFilesHaveInvalidatedResolution = false; + filesWithInvalidatedNonRelativeUnresolvedImports = undefined; + clearPerDirectoryResolutions(); directoryWatchesOfFailedLookups.forEach(function (watcher, path) { if (watcher.refCount === 0) { directoryWatchesOfFailedLookups.delete(path); watcher.watcher.close(); } }); - clearPerDirectoryResolutions(); } function resolveModuleName(moduleName, containingFile, compilerOptions, host) { var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache); @@ -77945,13 +84805,16 @@ var ts; } var resolvedModules = []; var compilerOptions = resolutionHost.getCompilationSettings(); + var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path); var seenNamesInFile = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { var name = names_2[_i]; var resolution = resolutionsInFile.get(name); // Resolution is valid if it is present and not invalidated if (!seenNamesInFile.has(name) && - allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated || + // If the name is unresolved import that was invalidated, recalculate + (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && !getResolutionWithResolvedFileName(resolution))) { var existingResolution = resolution; var resolutionInDirectory = perDirectoryResolution.get(name); if (resolutionInDirectory) { @@ -77962,7 +84825,7 @@ var ts; perDirectoryResolution.set(name, resolution); } resolutionsInFile.set(name, resolution); - watchFailedLookupLocationOfResolution(resolution); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution); } @@ -77974,7 +84837,7 @@ var ts; } ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); seenNamesInFile.set(name, true); - resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); // TODO: GH#18217 } // Stop watching and remove the unused name resolutionsInFile.forEach(function (resolution, name) { @@ -77988,7 +84851,7 @@ var ts; if (oldResolution === newResolution) { return true; } - if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + if (!oldResolution || !newResolution) { return false; } var oldResult = getResolutionWithResolvedFileName(oldResolution); @@ -78009,14 +84872,39 @@ var ts; function resolveModuleNames(moduleNames, containingFile, reusedNames) { return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } + function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) { + var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile)); + return cache && cache.get(moduleName); + } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); } function isNodeModulesAtTypesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules/@types"); } - function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { - for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + /** + * Filter out paths like + * "/", "/user", "/user/username", "/user/username/folderAtRoot", + * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot" + * @param dirPath + */ + function canWatchDirectory(dirPath) { + var rootLength = ts.getRootLength(dirPath); + if (dirPath.length === rootLength) { + // Ignore "/", "c:/" + return false; + } + var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength); + if (nextDirectorySeparator === -1) { + // ignore "/user", "c:/users" or "c:/folderAtRoot" + return false; + } + if (dirPath.charCodeAt(0) !== 47 /* slash */ && + dirPath.substr(rootLength, nextDirectorySeparator).search(/users/i) === -1) { + // Paths like c:/folderAtRoot/subFolder are allowed + return true; + } + for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) { searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; if (searchIndex === 0) { // Folder isnt at expected minimun levels @@ -78025,14 +84913,6 @@ var ts; } return true; } - function canWatchDirectory(dirPath) { - return isDirectoryAtleastAtLevelFromFSRoot(dirPath, - // When root is "/" do not watch directories like: - // "/", "/user", "/user/username", "/user/username/folderAtRoot" - // When root is "c:/" do not watch directories like: - // "c:/", "c:/folderAtRoot" - dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); - } function filterFSRootDirectoriesToWatch(watchPath, dirPath) { if (!canWatchDirectory(dirPath)) { watchPath.ignore = true; @@ -78041,7 +84921,8 @@ var ts; } function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { - return { dir: rootDir, dirPath: rootPath }; + // Always watch root directory recursively + return { dir: rootDir, dirPath: rootPath }; // TODO: GH#18217 } return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath)); } @@ -78051,42 +84932,56 @@ var ts; dir = ts.getDirectoryPath(dir); dirPath = ts.getDirectoryPath(dirPath); } - // If the directory is node_modules use it to watch + // If the directory is node_modules use it to watch, always watch it recursively if (isNodeModulesDirectory(dirPath)) { return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); } + var nonRecursive = true; // Use some ancestor of the root directory + var subDirectoryPath, subDirectory; if (rootPath !== undefined) { while (!isInDirectoryPath(dirPath, rootPath)) { var parentPath = ts.getDirectoryPath(dirPath); if (parentPath === dirPath) { break; } + nonRecursive = false; + subDirectoryPath = dirPath; + subDirectory = dir; dirPath = parentPath; dir = ts.getDirectoryPath(dir); } } - return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + return filterFSRootDirectoriesToWatch({ dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive }, dirPath); } function isPathWithDefaultFailedLookupExtension(path) { return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); } - function watchFailedLookupLocationOfResolution(resolution) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution) { // No need to set the resolution refCount - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { - return; + if (resolution.failedLookupLocations && resolution.failedLookupLocations.length) { + if (resolution.refCount) { + resolution.refCount++; + } + else { + resolution.refCount = 1; + if (ts.isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); + } + else { + nonRelativeExternalModuleResolutions.add(name, resolution); + } + } } - if (resolution.refCount !== undefined) { - resolution.refCount++; - return; - } - resolution.refCount = 1; + } + function watchFailedLookupLocationOfResolution(resolution) { + ts.Debug.assert(!!resolution.refCount); var failedLookupLocations = resolution.failedLookupLocations; var setAtRoot = false; for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) { var failedLookupLocation = failedLookupLocations_1[_i]; var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, ignore = _a.ignore; + var _a = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _a.dir, dirPath = _a.dirPath, nonRecursive = _a.nonRecursive, ignore = _a.ignore; if (!ignore) { // If the failed lookup location path is not one of the supported extensions, // store it in the custom path @@ -78098,25 +84993,35 @@ var ts; setAtRoot = true; } else { - setDirectoryWatcher(dir, dirPath); + setDirectoryWatcher(dir, dirPath, nonRecursive); } } } if (setAtRoot) { - setDirectoryWatcher(rootDir, rootPath); + // This is always recursive + setDirectoryWatcher(rootDir, rootPath); // TODO: GH#18217 } } - function setDirectoryWatcher(dir, dirPath) { + function setRefCountToUndefined(resolution) { + resolution.refCount = undefined; + } + function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { + var updateResolution = resolutionHost.getCurrentProgram().getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name) ? + setRefCountToUndefined : watchFailedLookupLocationOfResolution; + resolutions.forEach(updateResolution); + } + function setDirectoryWatcher(dir, dirPath, nonRecursive) { var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); if (dirWatcher) { + ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive); dirWatcher.refCount++; } else { - directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive }); } } function stopWatchFailedLookupLocationOfResolution(resolution) { - if (!resolution.failedLookupLocations || !resolution.failedLookupLocations.length) { + if (!resolution.refCount) { return; } resolution.refCount--; @@ -78157,22 +85062,17 @@ var ts; // Do not close the watcher yet since it might be needed by other failed lookup locations. dirWatcher.refCount--; } - function createDirectoryWatcher(directory, dirPath) { + function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } - // If the files are added to project root or node_modules directory, always run through the invalidation process - // Otherwise run through invalidation only if adding to the immediate directory - if (!allFilesHaveInvalidatedResolution && - dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { - if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { - resolutionHost.onInvalidatedResolution(); - } + if (!allFilesHaveInvalidatedResolution && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); } - }, 1 /* Recursive */); + }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } function removeResolutionsOfFileFromCache(cache, filePath) { // Deleted file, stop watching failed lookups for all the resolutions in the file @@ -78228,9 +85128,13 @@ var ts; // Resolution is invalidated if the resulting file name is same as the deleted file path function (resolution, getResolutionWithResolvedFileName) { var result = getResolutionWithResolvedFileName(resolution); - return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + return !!result && resolutionHost.toPath(result.resolvedFileName) === filePath; // TODO: GH#18217 }); } + function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) { + ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined); + filesWithInvalidatedNonRelativeUnresolvedImports = filesMap; + } function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { var isChangedFailedLookupLocation; if (isCreatingWatchedDirectory) { @@ -78280,14 +85184,14 @@ var ts; return rootPath; } var _a = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath), dirPath = _a.dirPath, ignore = _a.ignore; - return !ignore && directoryWatchesOfFailedLookups.has(dirPath) && dirPath; + return !ignore && directoryWatchesOfFailedLookups.has(dirPath) ? dirPath : undefined; } function createTypeRootsWatch(typeRootPath, typeRoot) { // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); if (cachedDirectoryStructureHost) { - // Since the file existance changed, update the sourceFiles cache + // Since the file existence changed, update the sourceFiles cache cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile @@ -78340,9 +85244,369 @@ var ts; } ts.createResolutionCache = createResolutionCache; })(ts || (ts = {})); -/// -/// -/// +// Used by importFixes to synthesize import module specifiers. +/* @internal */ +var ts; +(function (ts) { + var moduleSpecifiers; + (function (moduleSpecifiers) { + // Note: importingSourceFile is just for usesJsExtensionOnImports + function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, files, preferences) { + if (preferences === void 0) { preferences = {}; } + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host); + var modulePaths = getAllModulePaths(files, toFileName, info.getCanonicalFileName, host); + return ts.firstDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }) || + ts.first(getLocalModuleSpecifiers(toFileName, info, compilerOptions, preferences)); + } + moduleSpecifiers.getModuleSpecifier = getModuleSpecifier; + // For each symlink/original for a module, returns a list of ways to import that file. + function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, files, preferences) { + var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol); + if (ambient) + return [[ambient]]; + var info = getInfo(compilerOptions, importingSourceFile, importingSourceFile.path, host); + if (!files) { + return ts.Debug.fail("Files list must be present to resolve symlinks in specifier resolution"); + } + var modulePaths = getAllModulePaths(files, ts.getSourceFileOfNode(moduleSymbol.valueDeclaration).fileName, info.getCanonicalFileName, host); + var global = ts.mapDefined(modulePaths, function (moduleFileName) { return getGlobalModuleSpecifier(moduleFileName, info, host, compilerOptions); }); + return global.length ? global.map(function (g) { return [g]; }) : modulePaths.map(function (moduleFileName) { + return getLocalModuleSpecifiers(moduleFileName, info, compilerOptions, preferences); + }); + } + moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers; + // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path + function getInfo(compilerOptions, importingSourceFile, importingSourceFileName, host) { + var moduleResolutionKind = ts.getEmitModuleResolutionKind(compilerOptions); + var addJsExtension = usesJsExtensionOnImports(importingSourceFile); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true); + var sourceDirectory = ts.getDirectoryPath(importingSourceFileName); + return { moduleResolutionKind: moduleResolutionKind, addJsExtension: addJsExtension, getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory }; + } + function getGlobalModuleSpecifier(moduleFileName, _a, host, compilerOptions) { + var addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + return tryGetModuleNameFromTypeRoots(compilerOptions, host, getCanonicalFileName, moduleFileName, addJsExtension) + || tryGetModuleNameAsNodeModule(compilerOptions, moduleFileName, host, getCanonicalFileName, sourceDirectory); + } + function getLocalModuleSpecifiers(moduleFileName, _a, compilerOptions, preferences) { + var moduleResolutionKind = _a.moduleResolutionKind, addJsExtension = _a.addJsExtension, getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory; + var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs; + var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) || + removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), moduleResolutionKind, addJsExtension); + if (!baseUrl || preferences.importModuleSpecifierPreference === "relative") { + return [relativePath]; + } + var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); + if (!relativeToBaseUrl) { + return [relativePath]; + } + var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, moduleResolutionKind, addJsExtension); + if (paths) { + var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); + if (fromPaths) { + return [fromPaths]; + } + } + if (preferences.importModuleSpecifierPreference === "non-relative") { + return [importRelativeToBaseUrl]; + } + if (preferences.importModuleSpecifierPreference !== undefined) + ts.Debug.assertNever(preferences.importModuleSpecifierPreference); + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } + /* + Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/a/b + moduleFileName = /base/foo/bar + Then: + relativePath = ../../foo/bar + getRelativePathNParents(relativePath) = 2 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 2 < 2 = false + In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". + + Suppose we have: + baseUrl = /base + sourceDirectory = /base/foo/a + moduleFileName = /base/foo/bar + Then: + relativePath = ../a + getRelativePathNParents(relativePath) = 1 + pathFromSourceToBaseUrl = ../../ + getRelativePathNParents(pathFromSourceToBaseUrl) = 2 + 1 < 2 = true + In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". + */ + var pathFromSourceToBaseUrl = ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, baseUrl, getCanonicalFileName)); + var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); + return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; + } + function usesJsExtensionOnImports(_a) { + var imports = _a.imports; + return ts.firstDefined(imports, function (_a) { + var text = _a.text; + return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; + }) || false; + } + function discoverProbableSymlinks(files, getCanonicalFileName, host) { + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined; + }); + }); + var result = ts.createMap(); + if (symlinks) { + var currentDirectory = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) { + var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1]; + var resolvedParts = ts.getPathComponents(ts.toPath(resolvedPath, currentDirectory, getCanonicalFileName)); + var originalParts = ts.getPathComponents(ts.toPath(originalPath, currentDirectory, getCanonicalFileName)); + while (compareStrings(resolvedParts[resolvedParts.length - 1], originalParts[originalParts.length - 1]) === 0 /* EqualTo */) { + resolvedParts.pop(); + originalParts.pop(); + } + result.set(ts.getPathFromPathComponents(originalParts), ts.getPathFromPathComponents(resolvedParts)); + } + } + return result; + } + function getAllModulePathsUsingIndirectSymlinks(files, target, getCanonicalFileName, host) { + var links = discoverProbableSymlinks(files, getCanonicalFileName, host); + var paths = ts.arrayFrom(links.keys()); + var options; + var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive; + for (var _i = 0, paths_2 = paths; _i < paths_2.length; _i++) { + var path = paths_2[_i]; + var resolved = links.get(path); + if (compareStrings(target.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */) { + var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); + var option = ts.resolvePath(path, relative); + if (!host.fileExists || host.fileExists(option)) { + if (!options) + options = []; + options.push(option); + } + } + } + if (options) { + options.push(target); // Since these are speculative, we also include the original resolved name as a possibility + return options; + } + return [target]; + } + /** + * Looks for existing imports that use symlinks to this module. + * Only if no symlink is available, the real path will be used. + */ + function getAllModulePaths(files, importedFileName, getCanonicalFileName, host) { + var symlinks = ts.mapDefined(files, function (sf) { + return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { + return res && res.resolvedFileName === importedFileName ? res.originalPath : undefined; + }); + }); + var cwd = host.getCurrentDirectory ? host.getCurrentDirectory() : ""; + var baseOptions = getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, cwd), getCanonicalFileName, host); + if (symlinks.length === 0) { + return baseOptions; + } + return ts.deduplicate(ts.concatenate(baseOptions, ts.flatMap(symlinks, function (importedFileName) { return getAllModulePathsUsingIndirectSymlinks(files, ts.getNormalizedAbsolutePath(importedFileName, cwd), getCanonicalFileName, host); }))); + } + function getRelativePathNParents(relativePath) { + var components = ts.getPathComponents(relativePath); + if (components[0] || components.length === 1) + return 0; + for (var i = 1; i < components.length; i++) { + if (components[i] !== "..") + return i - 1; + } + return components.length - 1; + } + function tryGetModuleNameFromAmbientModule(moduleSymbol) { + var decl = moduleSymbol.valueDeclaration; + if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { + return decl.name.text; + } + } + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { + for (var key in paths) { + for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); + var indexOfStar = pattern.indexOf("*"); + if (indexOfStar === 0 && pattern.length === 1) { + continue; + } + else if (indexOfStar !== -1) { + var prefix = pattern.substr(0, indexOfStar); + var suffix = pattern.substr(indexOfStar + 1); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); + } + } + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { + return key; + } + } + } + } + function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { + var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); + if (normalizedTargetPath === undefined) { + return undefined; + } + var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); + var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath; + return ts.removeFileExtension(relativePath); + } + function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { + var roots = ts.getEffectiveTypeRoots(options, host); + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { + var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); + if (ts.startsWith(moduleFileName, typeRoot)) { + // For a type definition, we can strip `/index` even with classic resolution. + return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), ts.ModuleResolutionKind.NodeJs, addJsExtension); + } + }); + } + function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { + if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { + // nothing to do here + return undefined; + } + var parts = getNodeModulePathParts(moduleFileName); + if (!parts) { + return undefined; + } + // Simplify the full file path to something that can be resolved by Node. + // If the module could be imported by a directory name, use that directory's name + var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); + // Get a path that's relative to node_modules or the importing file's path + // if node_modules folder is in this folder or any of its parent folders, no need to keep it. + if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + return undefined; + // If the module was found in @types, get the actual Node package name + return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + function getDirectoryOrExtensionlessFileName(path) { + // If the file is the main module, it can be imported by the package name + var packageRootPath = path.substring(0, parts.packageRootIndex); + var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); + if (host.fileExists(packageJsonPath)) { // TODO: GH#18217 + var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); + if (packageJsonContent) { + var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; + } + } + } + } + // We still have a file name - remove the extension + var fullModulePathWithoutExtension = ts.removeFileExtension(path); + // If the file is /index, it can be imported by its directory name + // IFF there is not _also_ a file by the same name + if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) { + return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); + } + return fullModulePathWithoutExtension; + } + } + function tryGetAnyFileFromPath(host, path) { + // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory + var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]); + for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) { + var e = extensions_3[_i]; + var fullPath = path + e; + if (host.fileExists(fullPath)) { // TODO: GH#18217 + return fullPath; + } + } + } + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // 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; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf("/node_modules/", partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); + } + function removeExtensionAndIndexPostFix(fileName, moduleResolutionKind, addJsExtension) { + var noExtension = ts.removeFileExtension(fileName); + return addJsExtension + ? noExtension + ".js" + : moduleResolutionKind === ts.ModuleResolutionKind.NodeJs + ? ts.removeSuffix(noExtension, "/index") + : noExtension; + } + function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); + } + })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {})); +})(ts || (ts = {})); /*@internal*/ var ts; (function (ts) { @@ -78350,7 +85614,7 @@ var ts; getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) - } : undefined; + } : undefined; // TODO: GH#18217 /** * Create a function that reports error by writing to the system and handles the formating of the diagnostic */ @@ -78367,18 +85631,38 @@ var ts; return function (diagnostic) { diagnostics[0] = diagnostic; system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); - diagnostics[0] = undefined; + diagnostics[0] = undefined; // TODO: GH#18217 }; } ts.createDiagnosticReporter = createDiagnosticReporter; + /** @internal */ + ts.nonClearingMessageCodes = [ + ts.Diagnostics.Found_1_error_Watching_for_file_changes.code, + ts.Diagnostics.Found_0_errors_Watching_for_file_changes.code + ]; + /** + * @returns Whether the screen was cleared. + */ function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) { if (system.clearScreen && !options.preserveWatchOutput && - diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code && !options.extendedDiagnostics && - !options.diagnostics) { + !options.diagnostics && + !ts.contains(ts.nonClearingMessageCodes, diagnostic.code)) { system.clearScreen(); + return true; } + return false; + } + /** @internal */ + ts.screenStartingMessageCodes = [ + ts.Diagnostics.Starting_compilation_in_watch_mode.code, + ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, + ]; + function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) { + return ts.contains(ts.screenStartingMessageCodes, diagnostic.code) + ? newLine + newLine + : newLine; } /** * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic @@ -78388,13 +85672,16 @@ var ts; function (diagnostic, newLine, options) { clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine); system.write(output); } : function (diagnostic, newLine, options) { - clearScreenIfNotWatchingForFileChanges(system, diagnostic, options); - var output = new Date().toLocaleTimeString() + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + var output = ""; + if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) { + output += newLine; + } + output += new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine); system.write(output); }; } @@ -78402,53 +85689,27 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onConfigFileDiagnostic = reportDiagnostic; host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; - var result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); - host.onConfigFileDiagnostic = undefined; - host.onUnRecoverableConfigFileDiagnostic = undefined; + var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); + host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; } ts.parseConfigFileWithSystem = parseConfigFileWithSystem; - /** - * Reads the config file, reports errors if any and exits if the config file cannot be found - */ - function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host) { - var configFileText; - try { - configFileText = host.readFile(configFileName); - } - catch (e) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - if (!configFileText) { - var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - host.onUnRecoverableConfigFileDiagnostic(error); - return undefined; - } - var result = ts.parseJsonText(configFileName, configFileText); - result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); - var cwd = host.getCurrentDirectory(); - var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); - return configParseResult; - } - ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile; /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary) { // First get and report any syntactic errors. - var diagnostics = program.getSyntacticDiagnostics().slice(); + var diagnostics = program.getConfigFileParsingDiagnostics().slice(); + var configFileParsingDiagnosticsLength = diagnostics.length; + ts.addRange(diagnostics, program.getSyntacticDiagnostics()); var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { + if (diagnostics.length === configFileParsingDiagnosticsLength) { reportSemanticDiagnostics = true; } } @@ -78471,6 +85732,9 @@ var ts; }); } } + if (reportSummary) { + reportSummary(diagnostics.filter(function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }).length); + } if (emitSkipped && diagnostics.length > 0) { // If the emitter didn't emit anything, then pass that value along. return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -78495,6 +85759,7 @@ var ts; var host = system; var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; var writeFileName = function (s) { return system.write(s + system.newLine); }; + var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { useCaseSensitiveFileNames: useCaseSensitiveFileNames, getNewLine: function () { return system.newLine; }, @@ -78515,12 +85780,12 @@ var ts; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); var _a; + return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); }) : ts.noop, clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop, trace: function (s) { return system.write(s); }, - onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + onWatchStatusChange: onWatchStatusChange, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, @@ -78532,7 +85797,17 @@ var ts; return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); } function emitFilesAndReportErrorUsingBuilder(builderProgram) { - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + var compilerOptions = builderProgram.getCompilerOptions(); + var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); + var reportSummary = function (errorCount) { + if (errorCount === 1) { + onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_1_error_Watching_for_file_changes, errorCount), newLine, compilerOptions); + } + else { + onWatchStatusChange(ts.createCompilerDiagnostic(ts.Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount, errorCount), newLine, compilerOptions); + } + }; + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, reportSummary); } } /** @@ -78546,10 +85821,9 @@ var ts; * Creates the watch compiler host from system for config file in watch mode */ function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); - var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); - host.onConfigFileDiagnostic = reportDiagnostic; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus); + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); }; host.configFileName = configFileName; host.optionsToExtend = optionsToExtend; return host; @@ -78569,7 +85843,7 @@ var ts; (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { if (ts.isArray(rootFilesOrConfigFileName)) { - return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 } else { return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -78592,8 +85866,11 @@ var ts; var getCurrentDirectory = function () { return currentDirectory; }; var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; - var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; - var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + var rootFileNames = host.rootFiles, compilerOptions = host.options; + var configFileSpecs; + var configFileParsingDiagnostics; + var hasChangedConfigFileParsingErrors = false; + var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } @@ -78604,23 +85881,30 @@ var ts; fileExists: function (path) { return host.fileExists(path); }, readFile: readFile, getCurrentDirectory: getCurrentDirectory, - onConfigFileDiagnostic: host.onConfigFileDiagnostic, onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic }; // From tsc we want to get already parsed result and hence check for rootFileNames - if (configFileName && !rootFileNames) { + var newLine = updateNewLine(); + if (configFileName && host.configFileParsingResult) { + setConfigFileParsingResult(host.configFileParsingResult); + newLine = updateNewLine(); + } + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + if (configFileName && !host.configFileParsingResult) { + newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); }); + ts.Debug.assert(!rootFileNames); parseConfigFile(); + newLine = updateNewLine(); } var trace = host.trace && (function (s) { host.trace(s + newLine); }); var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostis ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectoryWorker = _b.watchDirectory; + compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 + var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var newLine = updateNewLine(); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); } var compilerHost = { // Members for CompilerHost @@ -78637,7 +85921,7 @@ var ts; readFile: readFile, trace: trace, directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), realpath: host.realpath && (function (s) { return host.realpath(s); }), getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, @@ -78645,8 +85929,8 @@ var ts; // Members for ResolutionCacheHost toPath: toPath, getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: watchDirectory, - watchTypeRootsDirectory: watchDirectory, + watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, + watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, onInvalidatedResolution: scheduleProgramUpdate, onChangedAutomaticTypeDirectiveNames: function () { @@ -78670,7 +85954,6 @@ var ts; (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; - reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); @@ -78695,8 +85978,20 @@ var ts; // All resolutions are invalid if user provided resolutions var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { - return builderProgram; + if (hasChangedConfigFileParsingErrors) { + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + hasChangedConfigFileParsingErrors = false; + } } + else { + createNewProgram(program, hasInvalidatedResolution); + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + return builderProgram; + } + function createNewProgram(program, hasInvalidatedResolution) { // Compile the program if (watchLogLevel !== ts.WatchLogLevel.None) { writeLog("CreatingProgramWith::"); @@ -78705,10 +86000,11 @@ var ts; } var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; + hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); @@ -78729,11 +86025,6 @@ var ts; } missingFilePathsRequestedForRelease = undefined; } - if (host.afterProgramCreate) { - host.afterProgramCreate(builderProgram); - } - reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); - return builderProgram; } function updateRootFileNames(files) { ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); @@ -78741,7 +86032,7 @@ var ts; scheduleProgramUpdate(); } function updateNewLine() { - return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); }); } function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); @@ -78779,7 +86070,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); } } else { @@ -78793,7 +86084,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -78857,7 +86148,7 @@ var ts; } function reportWatchDiagnostic(message) { if (host.onWatchStatusChange) { - host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions); + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile); } } // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch @@ -78870,6 +86161,7 @@ var ts; if (timerToUpdateProgram) { host.clearTimeout(timerToUpdateProgram); } + writeLog("Scheduling update"); timerToUpdateProgram = host.setTimeout(updateProgram, 250); } function scheduleProgramReload() { @@ -78891,9 +86183,15 @@ var ts; } } function reloadFileNamesFromConfigFile() { + writeLog("Reloading new file names and options"); var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); - if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { - host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + if (result.fileNames.length) { + configFileParsingDiagnostics = ts.filter(configFileParsingDiagnostics, function (error) { return !ts.isErrorNoInputFiles(error); }); + hasChangedConfigFileParsingErrors = true; + } + else if (!configFileSpecs.filesSpecs && !ts.some(configFileParsingDiagnostics, ts.isErrorNoInputFiles)) { + configFileParsingDiagnostics = configFileParsingDiagnostics.concat(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + hasChangedConfigFileParsingErrors = true; } rootFileNames = result.fileNames; // Update the program @@ -78912,11 +86210,14 @@ var ts; watchConfigFileWildCardDirectories(); } function parseConfigFile() { - var configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); - rootFileNames = configParseResult.fileNames; - compilerOptions = configParseResult.options; - configFileSpecs = configParseResult.configFileSpecs; - configFileWildCardDirectories = configParseResult.wildcardDirectories; + setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost)); // TODO: GH#18217 + } + function setConfigFileParsingResult(configFileParseResult) { + rootFileNames = configFileParseResult.fileNames; + compilerOptions = configFileParseResult.options; + configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217 + configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult); + hasChangedConfigFileParsingErrors = true; } function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); @@ -78933,11 +86234,8 @@ var ts; cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } } - function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(host, directory, cb, flags); - } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -78951,15 +86249,15 @@ var ts; } } function watchConfigFileWildCardDirectories() { - if (configFileWildCardDirectories) { - ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + if (configFileSpecs) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory); } else if (watchedWildcardDirectories) { ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); } } function watchWildcardDirectory(directory, flags) { - return watchDirectory(directory, function (fileOrDirectory) { + return watchDirectory(host, directory, function (fileOrDirectory) { ts.Debug.assert(!!configFileName); var fileOrDirectoryPath = toPath(fileOrDirectory); // Since the file existance changed, update the sourceFiles cache @@ -78979,7 +86277,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags); + }, flags, "Wild card directories"); } function ensureDirectoriesExist(directoryPath) { if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { @@ -79005,2042 +86303,1421 @@ var ts; } ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); -/// -/// -/// -/// -/// var ts; (function (ts) { - /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; - /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + var minimumDate = new Date(-8640000000000000); + var maximumDate = new Date(8640000000000000); + var BuildResultFlags; + (function (BuildResultFlags) { + BuildResultFlags[BuildResultFlags["None"] = 0] = "None"; + /** + * No errors of any kind occurred during build + */ + BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success"; + /** + * None of the .d.ts files emitted by this build were + * different from the existing files on disk + */ + BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged"; + BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors"; + BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors"; + BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors"; + BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors"; + BuildResultFlags[BuildResultFlags["AnyErrors"] = 60] = "AnyErrors"; + })(BuildResultFlags || (BuildResultFlags = {})); + var UpToDateStatusType; + (function (UpToDateStatusType) { + UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable"; + UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate"; + /** + * The project appears out of date because its upstream inputs are newer than its outputs, + * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs. + * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project. + */ + UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes"; + UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 3] = "OutputMissing"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 4] = "OutOfDateWithSelf"; + UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 5] = "OutOfDateWithUpstream"; + UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 6] = "UpstreamOutOfDate"; + UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 7] = "UpstreamBlocked"; + /** + * Projects with no outputs (i.e. "solution" files) + */ + UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 8] = "ContainerOnly"; + })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {})); + /** + * A FileMap maintains a normalized-key to value relationship + */ + function createFileMap() { + // tslint:disable-next-line:no-null-keyword + var lookup = ts.createMap(); + return { + setValue: setValue, + getValue: getValue, + getValueOrUndefined: getValueOrUndefined, + removeKey: removeKey, + getKeys: getKeys, + hasKey: hasKey + }; + function getKeys() { + return Object.keys(lookup); + } + function hasKey(fileName) { + return lookup.has(ts.normalizePath(fileName)); + } + function removeKey(fileName) { + lookup.delete(ts.normalizePath(fileName)); + } + function setValue(fileName, value) { + lookup.set(ts.normalizePath(fileName), value); + } + function getValue(fileName) { + var f = ts.normalizePath(fileName); + if (lookup.has(f)) { + return lookup.get(f); + } + else { + throw new Error("No value corresponding to " + fileName + " exists in this map"); + } + } + function getValueOrUndefined(fileName) { + var f = ts.normalizePath(fileName); + return lookup.get(f); + } + } + function createDependencyMapper() { + var childToParents = createFileMap(); + var parentToChildren = createFileMap(); + var allKeys = createFileMap(); + function addReference(childConfigFileName, parentConfigFileName) { + addEntry(childToParents, childConfigFileName, parentConfigFileName); + addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + } + function getReferencesTo(parentConfigFileName) { + return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + } + function getReferencesOf(childConfigFileName) { + return childToParents.getValueOrUndefined(childConfigFileName) || []; + } + function getKeys() { + return allKeys.getKeys(); + } + function addEntry(mapToAddTo, key, element) { + key = ts.normalizePath(key); + element = ts.normalizePath(element); + var arr = mapToAddTo.getValueOrUndefined(key); + if (arr === undefined) { + mapToAddTo.setValue(key, arr = []); + } + if (arr.indexOf(element) < 0) { + arr.push(element); + } + allKeys.setValue(key, true); + allKeys.setValue(element, true); + } + return { + addReference: addReference, + getReferencesTo: getReferencesTo, + getReferencesOf: getReferencesOf, + getKeys: getKeys + }; + } + function getOutputDeclarationFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.declarationDir || configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + return ts.changeExtension(outputPath, ".d.ts" /* Dts */); + } + function getOutputJavaScriptFileName(inputFileName, configFile) { + var relativePath = ts.getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath), inputFileName, /*ignoreCase*/ true); + var outputPath = ts.resolvePath(configFile.options.outDir || ts.getDirectoryPath(configFile.options.configFilePath), relativePath); + var newExtension = ts.fileExtensionIs(inputFileName, ".json" /* Json */) ? ".json" /* Json */ : + ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */; + return ts.changeExtension(outputPath, newExtension); + } + function getOutputFileNames(inputFileName, configFile) { + // outFile is handled elsewhere; .d.ts files don't generate outputs + if (configFile.options.outFile || configFile.options.out || ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */)) { + return ts.emptyArray; + } + var outputs = []; + outputs.push(getOutputJavaScriptFileName(inputFileName, configFile)); + if (ts.getEmitDeclarations(configFile.options) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */)) { + var dts = getOutputDeclarationFileName(inputFileName, configFile); + outputs.push(dts); + if (configFile.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function getOutFileOutputs(project) { + if (!project.options.outFile) { + return ts.Debug.fail("outFile must be set"); + } + var outputs = []; + outputs.push(project.options.outFile); + if (ts.getEmitDeclarations(project.options)) { + var dts = ts.changeExtension(project.options.outFile, ".d.ts" /* Dts */); + outputs.push(dts); + if (project.options.declarationMap) { + outputs.push(dts + ".map"); + } + } + return outputs; + } + function rootDirOfOptions(opts, configFileName) { + return opts.rootDir || ts.getDirectoryPath(configFileName); + } + function createConfigFileCache(host) { + var cache = createFileMap(); + var configParseHost = ts.parseConfigHostFromCompilerHost(host); + function parseConfigFile(configFilePath) { + var sourceFile = host.getSourceFile(configFilePath, 100 /* JSON */); + if (sourceFile === undefined) { + return undefined; + } + var parsed = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, ts.getDirectoryPath(configFilePath)); + parsed.options.configFilePath = configFilePath; + cache.setValue(configFilePath, parsed); + return parsed; + } + function removeKey(configFilePath) { + cache.removeKey(configFilePath); + } + return { + parseConfigFile: parseConfigFile, + removeKey: removeKey + }; + } + function newer(date1, date2) { + return date2 > date1 ? date2 : date1; + } + function isDeclarationFile(fileName) { + return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */); + } + function createBuildContext(options) { + var invalidatedProjects = createFileMap(); + var queuedProjects = createFileMap(); + var missingRoots = ts.createMap(); + return { + options: options, + projectStatus: createFileMap(), + unchangedOutputs: createFileMap(), + invalidatedProjects: invalidatedProjects, + missingRoots: missingRoots, + queuedProjects: queuedProjects + }; + } + ts.createBuildContext = createBuildContext; + var buildOpts = [ { - name: "help", - shortName: "h", - type: "boolean", - showInSimplifiedHelpView: true, + name: "verbose", + shortName: "v", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Print_this_message, - }, - { - name: "help", - shortName: "?", + description: ts.Diagnostics.Enable_verbose_logging, type: "boolean" }, { - name: "all", - type: "boolean", - showInSimplifiedHelpView: true, + name: "dry", + shortName: "d", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Show_all_compiler_options, + description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, + type: "boolean" }, { - name: "version", - shortName: "v", - type: "boolean", - showInSimplifiedHelpView: true, + name: "force", + shortName: "f", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Print_the_compiler_s_version, + description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, + type: "boolean" }, { - name: "init", - type: "boolean", - showInSimplifiedHelpView: true, + name: "clean", category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, - }, - { - name: "project", - shortName: "p", - type: "string", - isFilePath: true, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - paramType: ts.Diagnostics.FILE_OR_DIRECTORY, - description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json, - }, - { - name: "pretty", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental - }, - { - name: "preserveWatchOutput", - type: "boolean", - showInSimplifiedHelpView: false, - category: ts.Diagnostics.Command_line_Options, - description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, + description: ts.Diagnostics.Delete_the_outputs_of_all_projects, + type: "boolean" }, { name: "watch", - shortName: "w", - type: "boolean", - showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, - }, - // Basic - { - name: "target", - shortName: "t", - type: ts.createMapFromTemplate({ - es3: 0 /* ES3 */, - es5: 1 /* ES5 */, - es6: 2 /* ES2015 */, - es2015: 2 /* ES2015 */, - es2016: 3 /* ES2016 */, - es2017: 4 /* ES2017 */, - es2018: 5 /* ES2018 */, - esnext: 6 /* ESNext */, - }), - paramType: ts.Diagnostics.VERSION, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, - }, - { - name: "module", - shortName: "m", - type: ts.createMapFromTemplate({ - none: ts.ModuleKind.None, - commonjs: ts.ModuleKind.CommonJS, - amd: ts.ModuleKind.AMD, - system: ts.ModuleKind.System, - umd: ts.ModuleKind.UMD, - es6: ts.ModuleKind.ES2015, - es2015: ts.ModuleKind.ES2015, - esnext: ts.ModuleKind.ESNext - }), - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_or_ESNext, - }, - { - name: "lib", - type: "list", - element: { - name: "lib", - type: ts.createMapFromTemplate({ - // JavaScript only - "es5": "lib.es5.d.ts", - "es6": "lib.es2015.d.ts", - "es2015": "lib.es2015.d.ts", - "es7": "lib.es2016.d.ts", - "es2016": "lib.es2016.d.ts", - "es2017": "lib.es2017.d.ts", - "es2018": "lib.es2018.d.ts", - "esnext": "lib.esnext.d.ts", - // Host only - "dom": "lib.dom.d.ts", - "dom.iterable": "lib.dom.iterable.d.ts", - "webworker": "lib.webworker.d.ts", - "scripthost": "lib.scripthost.d.ts", - // ES2015 Or ESNext By-feature options - "es2015.core": "lib.es2015.core.d.ts", - "es2015.collection": "lib.es2015.collection.d.ts", - "es2015.generator": "lib.es2015.generator.d.ts", - "es2015.iterable": "lib.es2015.iterable.d.ts", - "es2015.promise": "lib.es2015.promise.d.ts", - "es2015.proxy": "lib.es2015.proxy.d.ts", - "es2015.reflect": "lib.es2015.reflect.d.ts", - "es2015.symbol": "lib.es2015.symbol.d.ts", - "es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts", - "es2016.array.include": "lib.es2016.array.include.d.ts", - "es2017.object": "lib.es2017.object.d.ts", - "es2017.sharedmemory": "lib.es2017.sharedmemory.d.ts", - "es2017.string": "lib.es2017.string.d.ts", - "es2017.intl": "lib.es2017.intl.d.ts", - "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", - "es2018.promise": "lib.es2018.promise.d.ts", - "es2018.regexp": "lib.es2018.regexp.d.ts", - "esnext.array": "lib.esnext.array.d.ts", - "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", - }), - }, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation - }, - { - name: "allowJs", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Allow_javascript_files_to_be_compiled - }, - { - name: "checkJs", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Report_errors_in_js_files - }, - { - name: "jsx", - type: ts.createMapFromTemplate({ - "preserve": 1 /* Preserve */, - "react-native": 3 /* ReactNative */, - "react": 2 /* React */ - }), - paramType: ts.Diagnostics.KIND, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react, - }, - { - name: "declaration", - shortName: "d", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Generates_corresponding_d_ts_file, - }, - { - name: "emitDeclarationOnly", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Only_emit_d_ts_declaration_files, - }, - { - name: "sourceMap", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Generates_corresponding_map_file, - }, - { - name: "outFile", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.FILE, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file, - }, - { - name: "outDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Redirect_output_structure_to_the_directory, - }, - { - name: "rootDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir, - }, - { - name: "removeComments", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Do_not_emit_comments_to_output, - }, - { - name: "noEmit", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Do_not_emit_outputs, - }, - { - name: "importHelpers", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Import_emit_helpers_from_tslib - }, - { - name: "downlevelIteration", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3 - }, - { - name: "isolatedModules", - type: "boolean", - category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule - }, - // Strict Type Checks - { - name: "strict", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_all_strict_type_checking_options - }, - { - name: "noImplicitAny", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type, - }, - { - name: "strictNullChecks", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_null_checks - }, - { - name: "strictFunctionTypes", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_checking_of_function_types - }, - { - name: "strictPropertyInitialization", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes - }, - { - name: "noImplicitThis", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type, - }, - { - name: "alwaysStrict", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Strict_Type_Checking_Options, - description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file - }, - // Additional Checks - { - name: "noUnusedLocals", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_on_unused_locals, - }, - { - name: "noUnusedParameters", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_on_unused_parameters, - }, - { - name: "noImplicitReturns", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value - }, - { - name: "noFallthroughCasesInSwitch", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Additional_Checks, - description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement - }, - // Module Resolution - { - name: "moduleResolution", - type: ts.createMapFromTemplate({ - node: ts.ModuleResolutionKind.NodeJs, - classic: ts.ModuleResolutionKind.Classic, - }), - paramType: ts.Diagnostics.STRATEGY, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, - }, - { - name: "baseUrl", - type: "string", - isFilePath: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is - name: "paths", - type: "object", - isTSConfigOnly: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl - }, - { - // this option can only be specified in tsconfig.json - // use type = object to copy the value as-is - name: "rootDirs", - type: "list", - isTSConfigOnly: true, - element: { - name: "rootDirs", - type: "string", - isFilePath: true - }, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime - }, - { - name: "typeRoots", - type: "list", - element: { - name: "typeRoots", - type: "string", - isFilePath: true - }, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from - }, - { - name: "types", - type: "list", - element: { - name: "types", - type: "string" - }, - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation - }, - { - name: "allowSyntheticDefaultImports", - type: "boolean", - 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: "esModuleInterop", - type: "boolean", - showInSimplifiedHelpView: true, - category: ts.Diagnostics.Module_Resolution_Options, - description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports - }, - { - 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", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, - }, - { - name: "mapRoot", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.LOCATION, - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, - }, - { - name: "inlineSourceMap", - type: "boolean", - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file - }, - { - name: "inlineSources", - type: "boolean", - category: ts.Diagnostics.Source_Map_Options, - description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set - }, - // Experimental - { - name: "experimentalDecorators", - type: "boolean", - category: ts.Diagnostics.Experimental_Options, - description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators - }, - { - name: "emitDecoratorMetadata", - type: "boolean", - category: ts.Diagnostics.Experimental_Options, - description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators - }, - // Advanced - { - name: "jsxFactory", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h - }, - { - name: "diagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_diagnostic_information - }, - { - name: "extendedDiagnostics", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Show_verbose_diagnostic_information - }, - { - name: "traceResolution", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process - }, - { - name: "listFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, - { - name: "out", - type: "string", - isFilePath: false, - // for correct behaviour, please use outFile - category: ts.Diagnostics.Advanced_Options, - paramType: ts.Diagnostics.FILE, - description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file, - }, - { - name: "reactNamespace", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit - }, - { - name: "skipDefaultLibCheck", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files - }, - { - name: "charset", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_character_set_of_the_input_files - }, - { - name: "emitBOM", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files - }, - { - name: "locale", - type: "string", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us - }, - { - name: "newLine", - type: ts.createMapFromTemplate({ - crlf: 0 /* CarriageReturnLineFeed */, - lf: 1 /* LineFeed */ - }), - paramType: ts.Diagnostics.NEWLINE, - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, - }, - { - name: "noErrorTruncation", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_truncate_error_messages - }, - { - name: "noLib", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts - }, - { - name: "noResolve", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files - }, - { - name: "stripInternal", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation, - }, - { - name: "disableSizeLimit", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects - }, - { - name: "noImplicitUseStrict", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output - }, - { - name: "noEmitHelpers", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output - }, - { - name: "noEmitOnError", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported, - }, - { - name: "preserveConstEnums", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code - }, - { - name: "declarationDir", - type: "string", - isFilePath: true, - paramType: ts.Diagnostics.DIRECTORY, - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Output_directory_for_generated_declaration_files - }, - { - name: "skipLibCheck", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Skip_type_checking_of_declaration_files, - }, - { - name: "allowUnusedLabels", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_report_errors_on_unused_labels - }, - { - name: "allowUnreachableCode", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code - }, - { - name: "suppressExcessPropertyErrors", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals, - }, - { - name: "suppressImplicitAnyIndexErrors", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures, - }, - { - name: "forceConsistentCasingInFileNames", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, - { - name: "maxNodeModuleJsDepth", - type: "number", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files - }, - { - name: "noStrictGenericChecks", - type: "boolean", - category: ts.Diagnostics.Advanced_Options, - description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, - }, - { - // A list of plugins to load in the language service - name: "plugins", - type: "list", - isTSConfigOnly: true, - element: { - name: "plugin", - type: "object" - }, - description: ts.Diagnostics.List_of_language_service_plugins + type: "boolean" } ]; - /* @internal */ - ts.typeAcquisitionDeclarations = [ - { - /* @deprecated typingOptions.enableAutoDiscovery - * Use typeAcquisition.enable instead. - */ - name: "enableAutoDiscovery", - type: "boolean", - }, - { - name: "enable", - type: "boolean", - }, - { - name: "include", - type: "list", - element: { - name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" + function performBuild(args, compilerHost, buildHost, system) { + var verbose = false; + var dry = false; + var force = false; + var clean = false; + var watch = false; + var projects = []; + for (var _i = 0, args_6 = args; _i < args_6.length; _i++) { + var arg = args_6[_i]; + switch (arg.toLowerCase()) { + case "-v": + case "--verbose": + verbose = true; + continue; + case "-d": + case "--dry": + dry = true; + continue; + case "-f": + case "--force": + force = true; + continue; + case "--clean": + clean = true; + continue; + case "--watch": + case "-w": + watch = true; + continue; + case "--?": + case "-?": + case "--help": + ts.printHelp(buildOpts, "--build "); + return ts.ExitStatus.Success; } + // Not a flag, parse as filename + addProject(arg); } - ]; - /* @internal */ - ts.defaultInitCompilerOptions = { - module: ts.ModuleKind.CommonJS, - target: 1 /* ES5 */, - strict: true, - esModuleInterop: true - }; - var optionNameMapCache; - /* @internal */ - function convertEnableAutoDiscoveryToEnable(typeAcquisition) { - // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable - if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) { - return { - enable: typeAcquisition.enableAutoDiscovery, - include: typeAcquisition.include || [], - exclude: typeAcquisition.exclude || [] - }; + // Nonsensical combinations + if (clean && force) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } - return typeAcquisition; - } - ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable; - function getOptionNameMap() { - if (optionNameMapCache) { - return optionNameMapCache; + if (clean && verbose) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } - var optionNameMap = ts.createMap(); - var shortOptionNames = ts.createMap(); - ts.forEach(ts.optionDeclarations, function (option) { - optionNameMap.set(option.name.toLowerCase(), option); - if (option.shortName) { - shortOptionNames.set(option.shortName, option.name); - } - }); - optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; - return optionNameMapCache; - } - /* @internal */ - function createCompilerDiagnosticForInvalidCustomType(opt) { - return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic); - } - ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType; - function createDiagnosticForInvalidCustomType(opt, createDiagnostic) { - var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", "); - return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType); - } - /* @internal */ - function parseCustomTypeOption(opt, value, errors) { - return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors); - } - ts.parseCustomTypeOption = parseCustomTypeOption; - /* @internal */ - function parseListTypeOption(opt, value, errors) { - if (value === void 0) { value = ""; } - value = trimString(value); - if (ts.startsWith(value, "-")) { + if (clean && watch) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (watch && dry) { + buildHost.error(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (projects.length === 0) { + // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." + addProject("."); + } + var builder = createSolutionBuilder(compilerHost, buildHost, projects, { dry: dry, force: force, verbose: verbose }, system); + if (clean) { + return builder.cleanAllProjects(); + } + if (watch) { + builder.buildAllProjects(); + builder.startWatching(); return undefined; } - if (value === "") { - return []; - } - var values = value.split(","); - switch (opt.element.type) { - case "number": - return ts.map(values, parseInt); - case "string": - return ts.map(values, function (v) { return v || ""; }); - default: - return ts.filter(ts.map(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); }), function (v) { return !!v; }); + return builder.buildAllProjects(); + function addProject(projectSpecification) { + var fileName = ts.resolvePath(compilerHost.getCurrentDirectory(), projectSpecification); + var refPath = ts.resolveProjectReferencePath(compilerHost, { path: fileName }); + if (!compilerHost.fileExists(refPath)) { + return buildHost.error(ts.Diagnostics.File_0_does_not_exist, fileName); + } + projects.push(refPath); } } - ts.parseListTypeOption = parseListTypeOption; - function parseCommandLine(commandLine, readFile) { - var options = {}; - var fileNames = []; - var errors = []; - parseStrings(commandLine); - return { - options: options, - fileNames: fileNames, - errors: errors - }; - function parseStrings(args) { - var i = 0; - while (i < args.length) { - var s = args[i]; - i++; - if (s.charCodeAt(0) === 64 /* at */) { - parseResponseFile(s.slice(1)); - } - else if (s.charCodeAt(0) === 45 /* minus */) { - var opt = getOptionFromName(s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1), /*allowShort*/ true); - if (opt) { - if (opt.isTSConfigOnly) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); - } - else { - // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). - if (!args[i] && opt.type !== "boolean") { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); - } - switch (opt.type) { - case "number": - options[opt.name] = parseInt(args[i]); - i++; - break; - case "boolean": - // boolean flag has optional value true, false, others - var optValue = args[i]; - options[opt.name] = optValue !== "false"; - // consume next argument as boolean flag value - if (optValue === "false" || optValue === "true") { - i++; - } - break; - case "string": - options[opt.name] = args[i] || ""; - i++; - break; - case "list": - var result = parseListTypeOption(opt, args[i], errors); - options[opt.name] = result || []; - if (result) { - i++; - } - break; - // If not a primitive, the possible types are specified in what is effectively a map of options. - default: - options[opt.name] = parseCustomTypeOption(opt, args[i], errors); - i++; - break; - } - } - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); - } - } - else { - fileNames.push(s); - } - } + ts.performBuild = performBuild; + /** + * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but + * can dynamically add/remove other projects based on changes on the rootNames' references + */ + function createSolutionBuilder(compilerHost, buildHost, rootNames, defaultOptions, system) { + if (!compilerHost.getModifiedTime || !compilerHost.setModifiedTime) { + throw new Error("Host must support timestamp APIs"); } - function parseResponseFile(fileName) { - var text = readFile ? readFile(fileName) : ts.sys.readFile(fileName); - if (!text) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName)); + var configFileCache = createConfigFileCache(compilerHost); + var context = createBuildContext(defaultOptions); + var existingWatchersForWildcards = ts.createMap(); + var upToDateHost = { + fileExists: function (fileName) { return compilerHost.fileExists(fileName); }, + getModifiedTime: function (fileName) { return compilerHost.getModifiedTime(fileName); }, + getUnchangedTime: function (fileName) { return context.unchangedOutputs.getValueOrUndefined(fileName); }, + getLastStatus: function (fileName) { return context.projectStatus.getValueOrUndefined(fileName); }, + setLastStatus: function (fileName, status) { return context.projectStatus.setValue(fileName, status); }, + parseConfigFile: function (configFilePath) { return configFileCache.parseConfigFile(configFilePath); } + }; + return { + buildAllProjects: buildAllProjects, + getUpToDateStatus: getUpToDateStatus, + getUpToDateStatusOfFile: getUpToDateStatusOfFile, + cleanAllProjects: cleanAllProjects, + resetBuildContext: resetBuildContext, + getBuildGraph: getBuildGraph, + invalidateProject: invalidateProject, + buildInvalidatedProjects: buildInvalidatedProjects, + buildDependentInvalidatedProjects: buildDependentInvalidatedProjects, + resolveProjectName: resolveProjectName, + startWatching: startWatching + }; + function startWatching() { + if (!system) + throw new Error("System host must be provided if using --watch"); + if (!system.watchFile || !system.watchDirectory || !system.setTimeout) + throw new Error("System host must support watchFile / watchDirectory / setTimeout if using --watch"); + var graph = getGlobalDependencyGraph(); + if (!graph.buildQueue) { + // Everything is broken - we don't even know what to watch. Give up. return; } - var args = []; - var pos = 0; - while (true) { - while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) - pos++; - if (pos >= text.length) - break; - var start = pos; - if (text.charCodeAt(start) === 34 /* doubleQuote */) { - pos++; - while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) - pos++; - if (pos < text.length) { - args.push(text.substring(start + 1, pos)); - pos++; - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); - } - } - else { - while (text.charCodeAt(pos) > 32 /* space */) - pos++; - args.push(text.substring(start, pos)); - } - } - parseStrings(args); - } - } - ts.parseCommandLine = parseCommandLine; - function getOptionFromName(optionName, allowShort) { - if (allowShort === void 0) { allowShort = false; } - optionName = optionName.toLowerCase(); - var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; - // Try to translate short option names to their full equivalents. - if (allowShort) { - var short = shortOptionNames.get(optionName); - if (short !== undefined) { - optionName = short; - } - } - return optionNameMap.get(optionName); - } - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readConfigFile(fileName, readFile) { - var textOrDiagnostic = tryReadFile(fileName, readFile); - return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic }; - } - ts.readConfigFile = readConfigFile; - /** - * Parse the text of the tsconfig.json file - * @param fileName The path to the config file - * @param jsonText The text of the config file - */ - function parseConfigFileTextToJson(fileName, jsonText) { - var jsonSourceFile = ts.parseJsonText(fileName, jsonText); - return { - config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics), - error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined - }; - } - ts.parseConfigFileTextToJson = parseConfigFileTextToJson; - /** - * Read tsconfig.json file - * @param fileName The path to the config file - */ - function readJsonConfigFile(fileName, readFile) { - var textOrDiagnostic = tryReadFile(fileName, readFile); - return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] }; - } - ts.readJsonConfigFile = readJsonConfigFile; - function tryReadFile(fileName, readFile) { - var text; - try { - text = readFile(fileName); - } - catch (e) { - return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message); - } - return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, fileName) : text; - } - function commandLineOptionsToMap(options) { - return ts.arrayToMap(options, function (option) { return option.name; }); - } - var _tsconfigRootOptions; - function getTsconfigRootOptionsMap() { - if (_tsconfigRootOptions === undefined) { - _tsconfigRootOptions = commandLineOptionsToMap([ - { - name: "compilerOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.optionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_compiler_option_0 - }, - { - name: "typingOptions", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "typeAcquisition", - type: "object", - elementOptions: commandLineOptionsToMap(ts.typeAcquisitionDeclarations), - extraKeyDiagnosticMessage: ts.Diagnostics.Unknown_type_acquisition_option_0 - }, - { - name: "extends", - type: "string" - }, - { - name: "files", - type: "list", - element: { - name: "files", - type: "string" - } - }, - { - name: "include", - type: "list", - element: { - name: "include", - type: "string" - } - }, - { - name: "exclude", - type: "list", - element: { - name: "exclude", - type: "string" - } - }, - ts.compileOnSaveCommandLineOption - ]); - } - return _tsconfigRootOptions; - } - /** - * Convert the json syntax tree into the json value - */ - function convertToObject(sourceFile, errors) { - return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - } - ts.convertToObject = convertToObject; - /** - * Convert the json syntax tree into the json value - */ - function convertToObjectWorker(sourceFile, errors, knownRootOptions, jsonConversionNotifier) { - if (!sourceFile.jsonObject) { - return {}; - } - return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions, - /*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined); - function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnosticMessage, parentOption) { - var result = {}; - for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { - var element = _a[_i]; - if (element.kind !== 268 /* PropertyAssignment */) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected)); - continue; - } - if (element.questionToken) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics._0_can_only_be_used_in_a_ts_file, "?")); - } - if (!isDoubleQuotedString(element.name)) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected)); - } - var keyText = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(element.name)); - var option = knownOptions ? knownOptions.get(keyText) : undefined; - if (extraKeyDiagnosticMessage && !option) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnosticMessage, keyText)); - } - var value = convertPropertyValueToJson(element.initializer, option); - if (typeof keyText !== "undefined") { - result[keyText] = value; - // Notify key value set, if user asked for it - if (jsonConversionNotifier && - // Current callbacks are only on known parent option or if we are setting values in the root - (parentOption || knownOptions === knownRootOptions)) { - var isValidOptionValue = isCompilerOptionsValue(option, value); - if (parentOption) { - if (isValidOptionValue) { - // Notify option set in the parent if its a valid option value - jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value); - } - } - else if (knownOptions === knownRootOptions) { - if (isValidOptionValue) { - // Notify about the valid root key value being set - jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer); - } - else if (!option) { - // Notify about the unknown root key value being set - jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer); - } - } - } - } - } - return result; - } - function convertArrayLiteralExpressionToJson(elements, elementOption) { - return elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }); - } - function convertPropertyValueToJson(valueExpression, option) { - switch (valueExpression.kind) { - case 101 /* TrueKeyword */: - reportInvalidOptionValue(option && option.type !== "boolean"); - return true; - case 86 /* FalseKeyword */: - reportInvalidOptionValue(option && option.type !== "boolean"); - return false; - case 95 /* NullKeyword */: - reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for - return null; // tslint:disable-line:no-null-keyword - case 9 /* StringLiteral */: - if (!isDoubleQuotedString(valueExpression)) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected)); - } - reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string")); - var text = valueExpression.text; - if (option && !ts.isString(option.type)) { - var customOption = option; - // Validate custom option type - if (!customOption.type.has(text.toLowerCase())) { - errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); })); - } - } - return text; - case 8 /* NumericLiteral */: - reportInvalidOptionValue(option && option.type !== "number"); - return Number(valueExpression.text); - case 196 /* PrefixUnaryExpression */: - if (valueExpression.operator !== 38 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) { - break; // not valid JSON syntax - } - reportInvalidOptionValue(option && option.type !== "number"); - return -Number(valueExpression.operand.text); - case 182 /* ObjectLiteralExpression */: - reportInvalidOptionValue(option && option.type !== "object"); - var objectLiteralExpression = valueExpression; - // Currently having element option declaration in the tsconfig with type "object" - // determines if it needs onSetValidOptionKeyValueInParent callback or not - // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions" - // that satifies it and need it to modify options set in them (for normalizing file paths) - // vs what we set in the json - // If need arises, we can modify this interface and callbacks as needed - if (option) { - var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnosticMessage = _a.extraKeyDiagnosticMessage, optionName = _a.name; - return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnosticMessage, optionName); - } - else { - return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, - /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined); - } - case 181 /* ArrayLiteralExpression */: - reportInvalidOptionValue(option && option.type !== "list"); - return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element); - } - // Not in expected format - if (option) { - reportInvalidOptionValue(/*isError*/ true); - } - else { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_literal)); - } - return undefined; - function reportInvalidOptionValue(isError) { - if (isError) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option))); - } - } - } - function isDoubleQuotedString(node) { - return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile); - } - } - function getCompilerOptionValueTypeString(option) { - return option.type === "list" ? - "Array" : - ts.isString(option.type) ? option.type : "string"; - } - function isCompilerOptionsValue(option, value) { - if (option) { - if (isNullOrUndefined(value)) - return true; // All options are undefinable/nullable - if (option.type === "list") { - return ts.isArray(value); - } - var expectedType = ts.isString(option.type) ? option.type : "string"; - return typeof value === expectedType; - } - } - /** - * Generate tsconfig configuration when running command line "--init" - * @param options commandlineOptions to be generated into tsconfig.json - * @param fileNames array of filenames to be generated into tsconfig.json - */ - /* @internal */ - function generateTSConfig(options, fileNames, newLine) { - var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); - var compilerOptionsMap = serializeCompilerOptions(compilerOptions); - return writeConfigurations(); - function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { - // this is of a type CommandLineOptionOfPrimitiveType - return undefined; - } - else if (optionDefinition.type === "list") { - return getCustomTypeMapOfCommandLineOption(optionDefinition.element); - } - else { - return optionDefinition.type; - } - } - function getNameOfCompilerOptionValue(value, customTypeMap) { - // There is a typeMap associated with this command-line option so use it to map value back to its name - return ts.forEachEntry(customTypeMap, function (mapValue, key) { - if (mapValue === value) { - return key; - } - }); - } - function serializeCompilerOptions(options) { - var result = ts.createMap(); - var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_6 = function (name) { - if (ts.hasProperty(options, name)) { - // tsconfig only options cannot be specified via command line, - // so we can assume that only types that can appear here string | number | boolean - if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { - return "continue"; - } - var value = options[name]; - var optionDefinition = optionsNameMap.get(name.toLowerCase()); - if (optionDefinition) { - var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition); - if (!customTypeMap_1) { - // There is no map associated with this compiler option then use the value as-is - // This is the case if the value is expect to be string, number, boolean or list of string - result.set(name, value); - } - else { - if (optionDefinition.type === "list") { - result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); - } - else { - // There is a typeMap associated with this command-line option so use it to map value back to its name - result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1)); - } - } - } - } - }; - for (var name in options) { - _loop_6(name); - } - return result; - } - function getDefaultValueForOption(option) { - switch (option.type) { - case "number": - return 1; - case "boolean": - return true; - case "string": - return option.isFilePath ? "./" : ""; - case "list": - return []; - case "object": - return {}; - default: - return option.type.keys().next().value; - } - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - function writeConfigurations() { - // Filter applicable options to place in the file - var categorizedOptions = ts.createMultiMap(); - for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) { - var option = optionDeclarations_1[_i]; - var category = option.category; - if (category !== undefined && category !== ts.Diagnostics.Command_line_Options && category !== ts.Diagnostics.Advanced_Options) { - categorizedOptions.add(ts.getLocaleSpecificMessage(category), option); - } - } - // Serialize all options and their descriptions - var marginLength = 0; - var seenKnownKeys = 0; - var nameColumn = []; - var descriptionColumn = []; - categorizedOptions.forEach(function (options, category) { - if (nameColumn.length !== 0) { - nameColumn.push(""); - descriptionColumn.push(""); - } - nameColumn.push("/* " + category + " */"); - descriptionColumn.push(""); - for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { - var option = options_1[_i]; - var optionName = void 0; - if (compilerOptionsMap.has(option.name)) { - optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ","); - } - else { - optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ","; - } - nameColumn.push(optionName); - descriptionColumn.push("/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"); - marginLength = Math.max(optionName.length, marginLength); - } - }); - // Write the output - var tab = makePadding(2); - var result = []; - result.push("{"); - result.push(tab + "\"compilerOptions\": {"); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < nameColumn.length; i++) { - var optionName = nameColumn[i]; - var description = descriptionColumn[i]; - result.push(optionName && "" + tab + tab + optionName + (description && (makePadding(marginLength - optionName.length + 2) + description))); - } - if (fileNames.length) { - result.push(tab + "},"); - result.push(tab + "\"files\": ["); - for (var i = 0; i < fileNames.length; i++) { - result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ",")); - } - result.push(tab + "]"); - } - else { - result.push(tab + "}"); - } - result.push("}"); - return result.join(newLine); - } - } - ts.generateTSConfig = generateTSConfig; - /** - * Parse the contents of a config file (tsconfig.json). - * @param json The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); - } - ts.parseJsonConfigFileContent = parseJsonConfigFileContent; - /** - * Parse the contents of a config file (tsconfig.json). - * @param jsonNode The contents of the config file to parse - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - */ - function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions); - } - ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent; - /*@internal*/ - function setConfigFileInOptions(options, configFile) { - if (configFile) { - Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile }); - } - } - ts.setConfigFileInOptions = setConfigFileInOptions; - function isNullOrUndefined(x) { - // tslint:disable-next-line:no-null-keyword - return x === undefined || x === null; - } - function directoryOfCombinedPath(fileName, basePath) { - // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical - // until consistient casing errors are reported - return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath)); - } - /** - * Parse the contents of a config file from json or json source file (tsconfig.json). - * @param json The contents of the config file to parse - * @param sourceFile sourceFile corresponding to the Json - * @param host Instance of ParseConfigHost used to enumerate files in folder. - * @param basePath A root directory to resolve relative path entries in the config - * file to. e.g. outDir - * @param resolutionStack Only present for backwards-compatibility. Should be empty. - */ - function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions) { - if (existingOptions === void 0) { existingOptions = {}; } - if (resolutionStack === void 0) { resolutionStack = []; } - if (extraFileExtensions === void 0) { extraFileExtensions = []; } - ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined)); - var errors = []; - var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors); - var raw = parsedConfig.raw; - var options = ts.extend(existingOptions, parsedConfig.options || {}); - options.configFilePath = configFileName; - setConfigFileInOptions(options, sourceFile); - var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec; - return { - options: options, - fileNames: fileNames, - typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(), - raw: raw, - errors: errors, - wildcardDirectories: wildcardDirectories, - compileOnSave: !!raw.compileOnSave, - configFileSpecs: spec - }; - function getFileNames() { - var filesSpecs; - if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { - if (ts.isArray(raw.files)) { - filesSpecs = raw.files; - if (filesSpecs.length === 0) { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); - } - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"); - } - } - var includeSpecs; - if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) { - if (ts.isArray(raw.include)) { - includeSpecs = raw.include; - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array"); - } - } - var excludeSpecs; - if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) { - if (ts.isArray(raw.exclude)) { - excludeSpecs = raw.exclude; - } - else { - createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array"); - } - } - else { - var outDir = raw.compilerOptions && raw.compilerOptions.outDir; - if (outDir) { - excludeSpecs = [outDir]; - } - } - if (filesSpecs === undefined && includeSpecs === undefined) { - includeSpecs = ["**/*"]; - } - var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile); - if (result.fileNames.length === 0 && !ts.hasProperty(raw, "files") && resolutionStack.length === 0) { - errors.push(getErrorForNoInputFiles(result.spec, configFileName)); - } - return result; - } - function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) { - if (!sourceFile) { - errors.push(ts.createCompilerDiagnostic(message, arg0, arg1)); - } - } - } - /*@internal*/ - function isErrorNoInputFiles(error) { - return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code; - } - ts.isErrorNoInputFiles = isErrorNoInputFiles; - /*@internal*/ - function getErrorForNoInputFiles(_a, configFileName) { - var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs; - return ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, configFileName || "tsconfig.json", JSON.stringify(includeSpecs || []), JSON.stringify(excludeSpecs || [])); - } - ts.getErrorForNoInputFiles = getErrorForNoInputFiles; - function isSuccessfulParsedTsconfig(value) { - return !!value.options; - } - /** - * This *just* extracts options/include/exclude/files out of a config file. - * It does *not* resolve the included files. - */ - function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors) { - basePath = ts.normalizeSlashes(basePath); - var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath); - if (resolutionStack.indexOf(resolvedPath) >= 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, resolutionStack.concat([resolvedPath]).join(" -> "))); - return { raw: json || convertToObject(sourceFile, errors) }; - } - var ownConfig = json ? - parseOwnConfigOfJson(json, host, basePath, configFileName, errors) : - parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors); - if (ownConfig.extendedConfigPath) { - // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios. - resolutionStack = resolutionStack.concat([resolvedPath]); - var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors); - if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) { - var baseRaw_1 = extendedConfig.raw; - var raw_1 = ownConfig.raw; - var setPropertyInRawIfNotUndefined = function (propertyName) { - var value = raw_1[propertyName] || baseRaw_1[propertyName]; - if (value) { - raw_1[propertyName] = value; - } - }; - setPropertyInRawIfNotUndefined("include"); - setPropertyInRawIfNotUndefined("exclude"); - setPropertyInRawIfNotUndefined("files"); - if (raw_1.compileOnSave === undefined) { - raw_1.compileOnSave = baseRaw_1.compileOnSave; - } - ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options); - // TODO extend type typeAcquisition - } - } - return ownConfig; - } - function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { - if (ts.hasProperty(json, "excludes")) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); - } - var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName); - // typingOptions has been deprecated and is only supported for backward compatibility purposes. - // It should be removed in future releases - use typeAcquisition instead. - var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName); - json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); - var extendedConfigPath; - if (json.extends) { - if (!ts.isString(json.extends)) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string")); - } - else { - var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic); - } - } - return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; - } - function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) { - var options = getDefaultCompilerOptions(configFileName); - var typeAcquisition, typingOptionstypeAcquisition; - var extendedConfigPath; - var optionsIterator = { - onSetValidOptionKeyValueInParent: function (parentOption, option, value) { - ts.Debug.assert(parentOption === "compilerOptions" || parentOption === "typeAcquisition" || parentOption === "typingOptions"); - var currentOption = parentOption === "compilerOptions" ? - options : - parentOption === "typeAcquisition" ? - (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName))) : - (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName))); - currentOption[option.name] = normalizeOptionValue(option, basePath, value); - }, - onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) { - switch (key) { - case "extends": - var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath; - extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) { - return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0); + var _loop_12 = function (resolved) { + var cfg = configFileCache.parseConfigFile(resolved); + if (cfg) { + // Watch this file + system.watchFile(resolved, function () { + configFileCache.removeKey(resolved); + invalidateProjectAndScheduleBuilds(resolved); + }); + // Update watchers for wildcard directories + if (cfg.configFileSpecs) { + ts.updateWatchingWildcardDirectories(existingWatchersForWildcards, ts.createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), function (dir, flags) { + return system.watchDirectory(dir, function () { + invalidateProjectAndScheduleBuilds(resolved); + }, !!(flags & 1 /* Recursive */)); }); - return; - case "files": - if (value.length === 0) { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; - } - }, - onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) { - if (key === "excludes") { - errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude)); + } + // Watch input files + for (var _i = 0, _a = cfg.fileNames; _i < _a.length; _i++) { + var input = _a[_i]; + system.watchFile(input, function () { + invalidateProjectAndScheduleBuilds(resolved); + }); + } } + }; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var resolved = _a[_i]; + _loop_12(resolved); } - }; - var json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator); - if (!typeAcquisition) { - if (typingOptionstypeAcquisition) { - typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? - { - enable: typingOptionstypeAcquisition.enableAutoDiscovery, - include: typingOptionstypeAcquisition.include, - exclude: typingOptionstypeAcquisition.exclude - } : - typingOptionstypeAcquisition; - } - else { - typeAcquisition = getDefaultTypeAcquisition(configFileName); + function invalidateProjectAndScheduleBuilds(resolved) { + invalidateProject(resolved); + system.setTimeout(buildInvalidatedProjects, 100); + system.setTimeout(buildDependentInvalidatedProjects, 3000); } } - return { raw: json, options: options, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath }; - } - function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) { - extendedConfig = ts.normalizeSlashes(extendedConfig); - // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) - if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../"))) { - errors.push(createDiagnostic(ts.Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig)); - return undefined; + function resetBuildContext(opts) { + if (opts === void 0) { opts = defaultOptions; } + context = createBuildContext(opts); } - var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath); - if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) { - extendedConfigPath = extendedConfigPath + ".json"; - if (!host.fileExists(extendedConfigPath)) { - errors.push(createDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); + function getUpToDateStatusOfFile(configFileName) { + return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + } + function getBuildGraph(configFileNames) { + var resolvedNames = resolveProjectNames(configFileNames); + if (resolvedNames === undefined) + return undefined; + return createDependencyGraph(resolvedNames); + } + function getGlobalDependencyGraph() { + return getBuildGraph(rootNames); + } + function getUpToDateStatus(project) { + return ts.getUpToDateStatus(upToDateHost, project); + } + function invalidateProject(configFileName) { + var resolved = resolveProjectName(configFileName); + if (resolved === undefined) { + // If this was a rootName, we need to track it as missing. + // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, + // if they exist + // TODO: do those things + return; + } + configFileCache.removeKey(resolved); + context.invalidatedProjects.setValue(resolved, true); + context.projectStatus.removeKey(resolved); + var graph = getGlobalDependencyGraph(); + if (graph) { + queueBuildForDownstreamReferences(resolved); + } + // Mark all downstream projects of this one needing to be built "later" + function queueBuildForDownstreamReferences(root) { + var deps = graph.dependencyMap.getReferencesTo(root); + for (var _i = 0, deps_1 = deps; _i < deps_1.length; _i++) { + var ref = deps_1[_i]; + // Can skip circular references + if (!context.queuedProjects.hasKey(ref)) { + context.queuedProjects.setValue(ref, true); + queueBuildForDownstreamReferences(ref); + } + } + } + } + function buildInvalidatedProjects() { + buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); + } + function buildDependentInvalidatedProjects() { + buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); + } + function buildSomeProjects(predicate) { + var resolvedNames = resolveProjectNames(rootNames); + if (resolvedNames === undefined) + return; + var graph = createDependencyGraph(resolvedNames); + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var next = _a[_i]; + if (!predicate(next)) + continue; + var resolved = resolveProjectName(next); + if (!resolved) + continue; // ?? + var proj = configFileCache.parseConfigFile(resolved); + if (!proj) + continue; // ? + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + continue; + } + buildSingleProject(next); + } + } + function createDependencyGraph(roots) { + var temporaryMarks = {}; + var permanentMarks = {}; + var circularityReportStack = []; + var buildOrder = []; + var graph = createDependencyMapper(); + var hadError = false; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + visit(root); + } + if (hadError) { return undefined; } - } - return extendedConfigPath; - } - function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors) { - var extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); }); - if (sourceFile) { - (sourceFile.extendedSourceFiles || (sourceFile.extendedSourceFiles = [])).push(extendedResult.fileName); - } - if (extendedResult.parseDiagnostics.length) { - errors.push.apply(errors, extendedResult.parseDiagnostics); - return undefined; - } - var extendedDirname = ts.getDirectoryPath(extendedConfigPath); - var extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors); - if (sourceFile) { - (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles); - } - if (isSuccessfulParsedTsconfig(extendedConfig)) { - // Update the paths to reflect base path - var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity); - var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); }; - var mapPropertiesInRawIfNotUndefined = function (propertyName) { - if (raw_2[propertyName]) { - raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1); - } + return { + buildQueue: buildOrder, + dependencyMap: graph }; - var raw_2 = extendedConfig.raw; - mapPropertiesInRawIfNotUndefined("include"); - mapPropertiesInRawIfNotUndefined("exclude"); - mapPropertiesInRawIfNotUndefined("files"); - } - return extendedConfig; - var _a; - } - function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { - if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { - return undefined; - } - var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors); - if (typeof result === "boolean" && result) { - return result; - } - return false; - } - function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { - var errors = []; - var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options: options, errors: errors }; - } - ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson; - function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) { - var errors = []; - var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName); - return { options: options, errors: errors }; - } - ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson; - function getDefaultCompilerOptions(configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true } - : {}; - return options; - } - function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = getDefaultCompilerOptions(configFileName); - convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); - return options; - } - function getDefaultTypeAcquisition(configFileName) { - return { enable: ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] }; - } - function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = getDefaultTypeAcquisition(configFileName); - var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions); - convertOptionsFromJson(ts.typeAcquisitionDeclarations, typeAcquisition, basePath, options, ts.Diagnostics.Unknown_type_acquisition_option_0, errors); - return options; - } - function convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, defaultOptions, diagnosticMessage, errors) { - if (!jsonOptions) { - return; - } - var optionNameMap = commandLineOptionsToMap(optionDeclarations); - for (var id in jsonOptions) { - var opt = optionNameMap.get(id); - if (opt) { - defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors); - } - else { - errors.push(ts.createCompilerDiagnostic(diagnosticMessage, id)); + function visit(projPath, inCircularContext) { + if (inCircularContext === void 0) { inCircularContext = false; } + // Already visited + if (permanentMarks[projPath]) + return; + // Circular + if (temporaryMarks[projPath]) { + if (!inCircularContext) { + hadError = true; + buildHost.error(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); + return; + } + } + temporaryMarks[projPath] = true; + circularityReportStack.push(projPath); + var parsed = configFileCache.parseConfigFile(projPath); + if (parsed === undefined) { + hadError = true; + return; + } + if (parsed.projectReferences) { + for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) { + var ref = _a[_i]; + var resolvedRefPath = resolveProjectName(ref.path); + if (resolvedRefPath === undefined) { + hadError = true; + break; + } + visit(resolvedRefPath, inCircularContext || ref.circular); + graph.addReference(projPath, resolvedRefPath); + } + } + circularityReportStack.pop(); + permanentMarks[projPath] = true; + buildOrder.push(projPath); } } - } - function convertJsonOption(opt, value, basePath, errors) { - if (isCompilerOptionsValue(opt, value)) { - var optType = opt.type; - if (optType === "list" && ts.isArray(value)) { - return convertJsonOptionOfListType(opt, value, basePath, errors); + function buildSingleProject(proj) { + if (context.options.dry) { + buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj); + return BuildResultFlags.Success; } - else if (!ts.isString(optType)) { - return convertJsonOptionOfCustomType(opt, value, errors); + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Building_project_0, proj); + var resultFlags = BuildResultFlags.None; + resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; + var configFile = configFileCache.parseConfigFile(proj); + if (!configFile) { + // Failed to read the config file + resultFlags |= BuildResultFlags.ConfigFileErrors; + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + return resultFlags; } - return normalizeNonListOptionValue(opt, basePath, value); - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt))); - } - } - function normalizeOptionValue(option, basePath, value) { - if (isNullOrUndefined(value)) - return undefined; - if (option.type === "list") { - var listOption_1 = option; - if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) { - return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; }); + if (configFile.fileNames.length === 0) { + // Nothing to build - must be a solution file, basically + return BuildResultFlags.None; } - return value; - } - else if (!ts.isString(option.type)) { - return option.type.get(ts.isString(value) ? value.toLowerCase() : value); - } - return normalizeNonListOptionValue(option, basePath, value); - } - function normalizeNonListOptionValue(option, basePath, value) { - if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); - if (value === "") { - value = "."; + var programOptions = { + projectReferences: configFile.projectReferences, + host: compilerHost, + rootNames: configFile.fileNames, + options: configFile.options + }; + var program = ts.createProgram(programOptions); + // Don't emit anything in the presence of syntactic errors or options diagnostics + var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + if (syntaxDiagnostics.length) { + resultFlags |= BuildResultFlags.SyntaxErrors; + for (var _i = 0, syntaxDiagnostics_1 = syntaxDiagnostics; _i < syntaxDiagnostics_1.length; _i++) { + var diag = syntaxDiagnostics_1[_i]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); + return resultFlags; } - } - return value; - } - function convertJsonOptionOfCustomType(opt, value, errors) { - if (isNullOrUndefined(value)) - return undefined; - var key = value.toLowerCase(); - var val = opt.type.get(key); - if (val !== undefined) { - return val; - } - else { - errors.push(createCompilerDiagnosticForInvalidCustomType(opt)); - } - } - function convertJsonOptionOfListType(option, values, basePath, errors) { - return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; }); - } - function trimString(s) { - return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, ""); - } - /** - * Tests for a path that ends in a recursive directory wildcard. - * Matches **, \**, **\, and \**\, but not a**b. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\* # matches the recursive directory wildcard "**". - * \/?$ # matches an optional trailing directory separator at the end of the string. - */ - var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; - /** - * Tests for a path where .. appears after a recursive directory wildcard. - * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\* - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * (^|\/) # matches either the beginning of the string or a directory separator. - * \*\*\/ # matches a recursive directory wildcard "**" followed by a directory separator. - * (.*\/)? # optionally matches any number of characters followed by a directory separator. - * \.\. # matches a parent directory path component ".." - * ($|\/) # matches either the end of the string or a directory separator. - */ - var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/; - /** - * Tests for a path containing a wildcard character in a directory component of the path. - * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * \/ # matches a directory separator. - * [^/]*? # matches any number of characters excluding directory separators (non-greedy). - * [*?] # matches either a wildcard character (* or ?) - * [^/]* # matches any number of characters excluding directory separators (greedy). - * \/ # matches a directory separator. - */ - var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//; - /** - * Matches the portion of a wildcard path that does not contain wildcards. - * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d. - * - * NOTE: used \ in place of / above to avoid issues with multiline comments. - * - * Breakdown: - * ^ # matches the beginning of the string - * [^*?]* # matches any number of non-wildcard characters - * (?=\/[^/]*[*?]) # lookahead that matches a directory separator followed by - * # a path component that contains at least one wildcard character (* or ?). - */ - var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; - /** - * Expands an array of file specifications. - * - * @param filesSpecs The literal file names to include. - * @param includeSpecs The wildcard file specifications to include. - * @param excludeSpecs The wildcard file specifications to exclude. - * @param basePath The base path for any relative file specifications. - * @param options Compiler options. - * @param host The host used to resolve files and directories. - * @param errors An array for diagnostic reporting. - */ - function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) { - basePath = ts.normalizePath(basePath); - var validatedIncludeSpecs, validatedExcludeSpecs; - // The exclude spec list is converted into a regular expression, which allows us to quickly - // test whether a file or directory should be excluded before recursively traversing the - // file system. - if (includeSpecs) { - validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include"); - } - if (excludeSpecs) { - validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude"); - } - // Wildcard directories (provided as part of a wildcard path) are stored in a - // file map that marks whether it was a regular wildcard match (with a `*` or `?` token), - // or a recursive directory. This information is used by filesystem watchers to monitor for - // new entries in these paths. - var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories }; - return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); - } - /** - * Gets the file names from the provided config file specs that contain, files, include, exclude and - * other properties needed to resolve the file names - * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details - * @param basePath The base path for any relative file specifications. - * @param options Compiler options. - * @param host The host used to resolve files and directories. - * @param extraFileExtensions optionaly file extra file extension information from host - */ - /* @internal */ - function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) { - if (extraFileExtensions === void 0) { extraFileExtensions = []; } - basePath = ts.normalizePath(basePath); - var keyMapper = host.useCaseSensitiveFileNames ? ts.identity : ts.toLowerCase; - // Literal file names (provided via the "files" array in tsconfig.json) are stored in a - // file map with a possibly case insensitive key. We use this map later when when including - // wildcard paths. - var literalFileMap = ts.createMap(); - // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a - // file map with a possibly case insensitive key. We use this map to store paths matched - // via wildcard, and to handle extension priority. - var wildcardFileMap = ts.createMap(); - var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories; - // Rather than requery this for each file and filespec, we query the supported extensions - // once and store it on the expansion context. - var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions); - // Literal files are always included verbatim. An "include" or "exclude" specification cannot - // remove a literal file. - if (filesSpecs) { - for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) { - var fileName = filesSpecs_1[_i]; - var file = ts.getNormalizedAbsolutePath(fileName, basePath); - literalFileMap.set(keyMapper(file), file); + // Don't emit .d.ts if there are decl file errors + if (ts.getEmitDeclarations(program.getCompilerOptions())) { + var declDiagnostics = program.getDeclarationDiagnostics(); + if (declDiagnostics.length) { + resultFlags |= BuildResultFlags.DeclarationEmitErrors; + for (var _a = 0, declDiagnostics_1 = declDiagnostics; _a < declDiagnostics_1.length; _a++) { + var diag = declDiagnostics_1[_a]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); + return resultFlags; + } } + // Same as above but now for semantic diagnostics + var semanticDiagnostics = program.getSemanticDiagnostics(); + if (semanticDiagnostics.length) { + resultFlags |= BuildResultFlags.TypeErrors; + for (var _b = 0, semanticDiagnostics_1 = semanticDiagnostics; _b < semanticDiagnostics_1.length; _b++) { + var diag = semanticDiagnostics_1[_b]; + buildHost.errorDiagnostic(diag); + } + context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); + return resultFlags; + } + var newestDeclarationFileContentChangedTime = minimumDate; + var anyDtsChanged = false; + program.emit(/*targetSourceFile*/ undefined, function (fileName, content, writeBom, onError) { + var priorChangeTime; + if (!anyDtsChanged && isDeclarationFile(fileName) && compilerHost.fileExists(fileName)) { + if (compilerHost.readFile(fileName) === content) { + // Check for unchanged .d.ts files + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + priorChangeTime = compilerHost.getModifiedTime && compilerHost.getModifiedTime(fileName); + } + else { + anyDtsChanged = true; + } + } + compilerHost.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + if (priorChangeTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); + context.unchangedOutputs.setValue(fileName, priorChangeTime); + } + }); + var status = { + type: UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + }; + context.projectStatus.setValue(proj, status); + return resultFlags; } - if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) { - for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensions, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) { - var file = _b[_a]; - // If we have already included a literal or wildcard path with a - // higher priority extension, we should skip this file. - // - // This handles cases where we may encounter both .ts and - // .d.ts (or .js if "allowJs" is enabled) in the same - // directory when they are compilation outputs. - if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) { + function updateOutputTimestamps(proj) { + if (context.options.dry) { + return buildHost.message(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); + } + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); + var now = new Date(); + var outputs = getAllProjectOutputs(proj); + var priorNewestUpdateTime = minimumDate; + for (var _i = 0, outputs_1 = outputs; _i < outputs_1.length; _i++) { + var file = outputs_1[_i]; + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, compilerHost.getModifiedTime(file)); + } + compilerHost.setModifiedTime(file, now); + } + context.projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); + } + function getFilesToClean(configFileNames) { + var resolvedNames = resolveProjectNames(configFileNames); + if (resolvedNames === undefined) + return undefined; + // Get the same graph for cleaning we'd use for building + var graph = createDependencyGraph(resolvedNames); + if (graph === undefined) + return undefined; + var filesToDelete = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var proj = _a[_i]; + var parsed = configFileCache.parseConfigFile(proj); + if (parsed === undefined) { + // File has gone missing; fine to ignore here continue; } - // We may have included a wildcard path with a lower priority - // extension due to the user-defined order of entries in the - // "include" array. If there is a lower priority extension in the - // same directory, we should remove it. - removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper); - var key = keyMapper(file); - if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) { - wildcardFileMap.set(key, file); + var outputs = getAllProjectOutputs(parsed); + for (var _b = 0, outputs_2 = outputs; _b < outputs_2.length; _b++) { + var output = outputs_2[_b]; + if (compilerHost.fileExists(output)) { + filesToDelete.push(output); + } + } + } + return filesToDelete; + } + function getAllProjectsInScope() { + var resolvedNames = resolveProjectNames(rootNames); + if (resolvedNames === undefined) + return undefined; + var graph = createDependencyGraph(resolvedNames); + if (graph === undefined) + return undefined; + return graph.buildQueue; + } + function cleanAllProjects() { + var resolvedNames = getAllProjectsInScope(); + if (resolvedNames === undefined) { + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + var filesToDelete = getFilesToClean(resolvedNames); + if (filesToDelete === undefined) { + buildHost.message(ts.Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + if (context.options.dry) { + buildHost.message(ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join("")); + return ts.ExitStatus.Success; + } + // Do this check later to allow --clean --dry to function even if the host can't delete files + if (!compilerHost.deleteFile) { + throw new Error("Host does not support deleting files"); + } + for (var _i = 0, filesToDelete_1 = filesToDelete; _i < filesToDelete_1.length; _i++) { + var output = filesToDelete_1[_i]; + compilerHost.deleteFile(output); + } + return ts.ExitStatus.Success; + } + function resolveProjectName(name) { + var fullPath = ts.resolvePath(compilerHost.getCurrentDirectory(), name); + if (compilerHost.fileExists(fullPath)) { + return fullPath; + } + var fullPathWithTsconfig = ts.combinePaths(fullPath, "tsconfig.json"); + if (compilerHost.fileExists(fullPathWithTsconfig)) { + return fullPathWithTsconfig; + } + buildHost.error(ts.Diagnostics.File_0_not_found, relName(fullPath)); + return undefined; + } + function resolveProjectNames(configFileNames) { + var resolvedNames = []; + for (var _i = 0, configFileNames_1 = configFileNames; _i < configFileNames_1.length; _i++) { + var name = configFileNames_1[_i]; + var resolved = resolveProjectName(name); + if (resolved === undefined) { + return undefined; + } + resolvedNames.push(resolved); + } + return resolvedNames; + } + function buildAllProjects() { + var graph = getGlobalDependencyGraph(); + if (graph === undefined) + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + var queue = graph.buildQueue; + reportBuildQueue(graph); + var anyFailed = false; + for (var _i = 0, queue_1 = queue; _i < queue_1.length; _i++) { + var next = queue_1[_i]; + var proj = configFileCache.parseConfigFile(next); + if (proj === undefined) { + anyFailed = true; + break; + } + var status = getUpToDateStatus(proj); + verboseReportProjectStatus(next, status); + var projName = proj.options.configFilePath; + if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + // Up to date, skip + if (defaultOptions.dry) { + // In a dry build, inform the user of this fact + buildHost.message(ts.Diagnostics.Project_0_is_up_to_date, projName); + } + continue; + } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + // Fake build + updateOutputTimestamps(proj); + continue; + } + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + continue; + } + if (status.type === UpToDateStatusType.ContainerOnly) { + // Do nothing + continue; + } + var buildResult = buildSingleProject(next); + anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); + } + return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; + } + /** + * Report the build ordering inferred from the current project graph if we're in verbose mode + */ + function reportBuildQueue(graph) { + if (!context.options.verbose) + return; + var names = []; + for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { + var name = _a[_i]; + names.push(name); + } + if (context.options.verbose) + buildHost.verbose(ts.Diagnostics.Projects_in_this_build_Colon_0, names.map(function (s) { return "\r\n * " + relName(s); }).join("")); + } + function relName(path) { + return ts.convertToRelativePath(path, compilerHost.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); + } + function reportVerbose(message) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + buildHost.verbose.apply(buildHost, [message].concat(args)); + } + /** + * Report the up-to-date status of a project if we're in verbose mode + */ + function verboseReportProjectStatus(configFileName, status) { + if (!context.options.verbose) + return; + return formatUpToDateStatus(configFileName, status, relName, reportVerbose); + } + } + ts.createSolutionBuilder = createSolutionBuilder; + /** + * Gets the UpToDateStatus for a project + */ + function getUpToDateStatus(host, project) { + if (project === undefined) { + return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; + } + var prior = host.getLastStatus ? host.getLastStatus(project.options.configFilePath) : undefined; + if (prior !== undefined) { + return prior; + } + var actual = getUpToDateStatusWorker(host, project); + if (host.setLastStatus) { + host.setLastStatus(project.options.configFilePath, actual); + } + return actual; + } + ts.getUpToDateStatus = getUpToDateStatus; + function getUpToDateStatusWorker(host, project) { + var newestInputFileName = undefined; + var newestInputFileTime = minimumDate; + // Get timestamps of input files + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + if (!host.fileExists(inputFile)) { + return { + type: UpToDateStatusType.Unbuildable, + reason: inputFile + " does not exist" + }; + } + var inputTime = host.getModifiedTime(inputFile); + if (inputTime > newestInputFileTime) { + newestInputFileName = inputFile; + newestInputFileTime = inputTime; + } + } + // Collect the expected outputs of this project + var outputs = getAllProjectOutputs(project); + if (outputs.length === 0) { + return { + type: UpToDateStatusType.ContainerOnly + }; + } + // Now see if all outputs are newer than the newest input + var oldestOutputFileName = "(none)"; + var oldestOutputFileTime = maximumDate; + var newestOutputFileName = "(none)"; + var newestOutputFileTime = minimumDate; + var missingOutputFileName; + var newestDeclarationFileContentChangedTime = minimumDate; + var isOutOfDateWithInputs = false; + for (var _b = 0, outputs_3 = outputs; _b < outputs_3.length; _b++) { + var output = outputs_3[_b]; + // Output is missing; can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (!host.fileExists(output)) { + missingOutputFileName = output; + break; + } + var outputTime = host.getModifiedTime(output); + if (outputTime < oldestOutputFileTime) { + oldestOutputFileTime = outputTime; + oldestOutputFileName = output; + } + // If an output is older than the newest input, we can stop checking + // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status + if (outputTime < newestInputFileTime) { + isOutOfDateWithInputs = true; + break; + } + if (outputTime > newestOutputFileTime) { + newestOutputFileTime = outputTime; + newestOutputFileName = output; + } + // Keep track of when the most recent time a .d.ts file was changed. + // In addition to file timestamps, we also keep track of when a .d.ts file + // had its file touched but not had its contents changed - this allows us + // to skip a downstream typecheck + if (isDeclarationFile(output)) { + var unchangedTime = host.getUnchangedTime ? host.getUnchangedTime(output) : undefined; + if (unchangedTime !== undefined) { + newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); + } + else { + newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, host.getModifiedTime(output)); } } } - var literalFiles = ts.arrayFrom(literalFileMap.values()); - var wildcardFiles = ts.arrayFrom(wildcardFileMap.values()); + var pseudoUpToDate = false; + var usesPrepend = false; + var upstreamChangedProject; + if (project.projectReferences && host.parseConfigFile) { + for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) { + var ref = _d[_c]; + usesPrepend = usesPrepend || !!(ref.prepend); + var resolvedRef = ts.resolveProjectReferencePath(host, ref); + var refStatus = getUpToDateStatus(host, host.parseConfigFile(resolvedRef)); + // An upstream project is blocked + if (refStatus.type === UpToDateStatusType.Unbuildable) { + return { + type: UpToDateStatusType.UpstreamBlocked, + upstreamProjectName: ref.path + }; + } + // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?) + if (refStatus.type !== UpToDateStatusType.UpToDate) { + return { + type: UpToDateStatusType.UpstreamOutOfDate, + upstreamProjectName: ref.path + }; + } + // If the upstream project's newest file is older than our oldest output, we + // can't be out of date because of it + if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { + continue; + } + // If the upstream project has only change .d.ts files, and we've built + // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild + if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) { + pseudoUpToDate = true; + upstreamChangedProject = ref.path; + continue; + } + // We have an output older than an upstream output - we are out of date + ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here"); + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: ref.path + }; + } + } + if (missingOutputFileName !== undefined) { + return { + type: UpToDateStatusType.OutputMissing, + missingOutputFileName: missingOutputFileName + }; + } + if (isOutOfDateWithInputs) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: newestInputFileName + }; + } + if (usesPrepend && pseudoUpToDate) { + return { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: oldestOutputFileName, + newerProjectName: upstreamChangedProject + }; + } + // Up to date return { - fileNames: literalFiles.concat(wildcardFiles), - wildcardDirectories: wildcardDirectories, - spec: spec + type: pseudoUpToDate ? UpToDateStatusType.UpToDateWithUpstreamTypes : UpToDateStatusType.UpToDate, + newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime, + newestInputFileTime: newestInputFileTime, + newestOutputFileTime: newestOutputFileTime, + newestInputFileName: newestInputFileName, + newestOutputFileName: newestOutputFileName, + oldestOutputFileName: oldestOutputFileName }; } - ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs; - function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) { - return specs.filter(function (spec) { - var diag = specToDiagnostic(spec, allowTrailingRecursion); - if (diag !== undefined) { - errors.push(createDiagnostic(diag, spec)); + function getAllProjectOutputs(project) { + if (project.options.outFile) { + return getOutFileOutputs(project); + } + else { + var outputs = []; + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + outputs.push.apply(outputs, getOutputFileNames(inputFile, project)); } - return diag === undefined; - }); - function createDiagnostic(message, spec) { - if (jsonSourceFile && jsonSourceFile.jsonObject) { - for (var _i = 0, _a = ts.getPropertyAssignment(jsonSourceFile.jsonObject, specKey); _i < _a.length; _i++) { - var property = _a[_i]; - if (ts.isArrayLiteralExpression(property.initializer)) { - for (var _b = 0, _c = property.initializer.elements; _b < _c.length; _b++) { - var element = _c[_b]; - if (ts.isStringLiteral(element) && element.text === spec) { - return ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec); - } - } - } + return outputs; + } + } + ts.getAllProjectOutputs = getAllProjectOutputs; + function formatUpToDateStatus(configFileName, status, relName, formatMessage) { + switch (status.type) { + case UpToDateStatusType.OutOfDateWithSelf: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerInputFileName)); + case UpToDateStatusType.OutOfDateWithUpstream: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, relName(configFileName), relName(status.outOfDateOutputFileName), relName(status.newerProjectName)); + case UpToDateStatusType.OutputMissing: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relName(configFileName), relName(status.missingOutputFileName)); + case UpToDateStatusType.UpToDate: + if (status.newestInputFileTime !== undefined) { + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relName(configFileName), relName(status.newestInputFileName || ""), relName(status.oldestOutputFileName || "")); } - } - 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 (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. - */ - function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) { - // We watch a directory recursively if it contains a wildcard anywhere in a directory segment - // of the pattern: - // - // /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively - // /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added - // /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler - // - // We watch a directory without recursion if it contains a wildcard in the file segment of - // the pattern: - // - // /a/b/* - Watch /a/b directly to catch any new file - // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z - var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude"); - var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - var wildcardDirectories = {}; - if (include !== undefined) { - var recursiveKeys = []; - for (var _i = 0, include_1 = include; _i < include_1.length; _i++) { - var file = include_1[_i]; - var spec = ts.normalizePath(ts.combinePaths(path, file)); - if (excludeRegex && excludeRegex.test(spec)) { - continue; - } - var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames); - if (match) { - var key = match.key, flags = match.flags; - var existingFlags = wildcardDirectories[key]; - if (existingFlags === undefined || existingFlags < flags) { - wildcardDirectories[key] = flags; - if (flags === 1 /* Recursive */) { - recursiveKeys.push(key); - } - } - } - } - // Remove any subpaths under an existing recursively watched directory. - for (var key in wildcardDirectories) { - if (ts.hasProperty(wildcardDirectories, key)) { - for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) { - var recursiveKey = recursiveKeys_1[_a]; - if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) { - delete wildcardDirectories[key]; - } - } - } - } - } - return wildcardDirectories; - } - function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) { - var match = wildcardDirectoryPattern.exec(spec); - if (match) { - return { - key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(), - flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */ - }; - } - if (ts.isImplicitGlob(spec)) { - return { key: spec, flags: 1 /* Recursive */ }; - } - return undefined; - } - /** - * Determines whether a literal or wildcard file has already been included that has a higher - * extension priority. - * - * @param file The path to the file. - * @param extensionPriority The priority of the extension. - * @param context The expansion context. - */ - function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { - var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); - for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { - var higherPriorityExtension = extensions[i]; - var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); - if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) { - return true; - } - } - return false; - } - /** - * Removes files included via wildcard expansion with a lower extension priority that have - * already been included. - * - * @param file The path to the file. - * @param extensionPriority The priority of the extension. - * @param context The expansion context. - */ - function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { - var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); - for (var i = nextExtensionPriority; i < extensions.length; i++) { - var lowerPriorityExtension = extensions[i]; - var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); - wildcardFiles.delete(lowerPriorityPath); - } - } - /** - * Produces a cleaned version of compiler options with personally identifiying info (aka, paths) removed. - * Also converts enum values back to strings. - */ - /* @internal */ - function convertCompilerOptionsForTelemetry(opts) { - var out = {}; - for (var key in opts) { - if (opts.hasOwnProperty(key)) { - var type = getOptionFromName(key); - if (type !== undefined) { // Ignore unknown options - out[key] = getOptionValueWithEmptyStrings(opts[key], type); - } - } - } - return out; - } - ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry; - function getOptionValueWithEmptyStrings(value, option) { - switch (option.type) { - case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "". - return ""; - case "string": // Could be any arbitrary string -- use empty string instead. - return ""; - case "number": // Allow numbers, but be sure to check it's actually a number. - return typeof value === "number" ? value : ""; - case "boolean": - return typeof value === "boolean" ? value : ""; - case "list": - var elementType_1 = option.element; - return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : ""; + // Don't report anything for "up to date because it was already built" -- too verbose + break; + case UpToDateStatusType.UpToDateWithUpstreamTypes: + return formatMessage(ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(configFileName)); + case UpToDateStatusType.UpstreamOutOfDate: + return formatMessage(ts.Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.UpstreamBlocked: + return formatMessage(ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(configFileName), relName(status.upstreamProjectName)); + case UpToDateStatusType.Unbuildable: + return formatMessage(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(configFileName), status.reason); + case UpToDateStatusType.ContainerOnly: + // Don't report status on "solution" projects + break; default: - return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) { - if (optionEnumValue === value) { - return optionStringValue; - } - }); + ts.assertTypeIsNever(status); } } + ts.formatUpToDateStatus = formatUpToDateStatus; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var server; + (function (server) { + // tslint:disable variable-name + server.ActionSet = "action::set"; + server.ActionInvalidate = "action::invalidate"; + server.ActionPackageInstalled = "action::packageInstalled"; + server.EventTypesRegistry = "event::typesRegistry"; + server.EventBeginInstallTypes = "event::beginInstallTypes"; + server.EventEndInstallTypes = "event::endInstallTypes"; + server.EventInitializationFailed = "event::initializationFailed"; + var Arguments; + (function (Arguments) { + Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation"; + Arguments.LogFile = "--logFile"; + Arguments.EnableTelemetry = "--enableTelemetry"; + Arguments.TypingSafeListLocation = "--typingSafeListLocation"; + Arguments.TypesMapLocation = "--typesMapLocation"; + /** + * This argument specifies the location of the NPM executable. + * typingsInstaller will run the command with `${npmLocation} install ...`. + */ + Arguments.NpmLocation = "--npmLocation"; + })(Arguments = server.Arguments || (server.Arguments = {})); + function hasArgument(argumentName) { + return ts.sys.args.indexOf(argumentName) >= 0; + } + server.hasArgument = hasArgument; + function findArgument(argumentName) { + var index = ts.sys.args.indexOf(argumentName); + return index >= 0 && index < ts.sys.args.length - 1 + ? ts.sys.args[index + 1] + : undefined; + } + server.findArgument = findArgument; + /*@internal*/ + function nowString() { + // E.g. "12:34:56.789" + var d = new Date(); + return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); + } + server.nowString = nowString; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + /* @internal */ + function isTypingUpToDate(cachedTyping, availableTypingVersions) { + var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); + return !availableVersion.greaterThan(cachedTyping.version); + } + JsTyping.isTypingUpToDate = isTypingUpToDate; + /* @internal */ + JsTyping.nodeCoreModuleList = [ + "assert", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "dns", + "domain", + "events", + "fs", + "http", + "https", + "http2", + "inspector", + "net", + "os", + "path", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "repl", + "stream", + "string_decoder", + "timers", + "tls", + "tty", + "url", + "util", + "v8", + "vm", + "zlib" + ]; + /* @internal */ + JsTyping.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 + * @param projectRootPath is the path to the project root directory + * @param safeListPath is the path used to retrieve the safe list + * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions + * @param typeAcquisition is used to customize the typing acquisition process + * @param compilerOptions are used as a source for typing inference + */ + function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { + if (!typeAcquisition || !typeAcquisition.enable) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + // A typing name to typing file path mapping + var inferredTypings = ts.createMap(); + // Only infer typings for .js and .jsx files + fileNames = ts.mapDefined(fileNames, function (fileName) { + var path = ts.normalizePath(fileName); + if (ts.hasJavaScriptFileExtension(path)) { + return path; + } + }); + var filesToWatch = []; + if (typeAcquisition.include) + addInferredTypings(typeAcquisition.include, "Explicitly included types"); + var exclude = typeAcquisition.exclude || []; + // Directories to search for package.json, bower.json and other typing information + var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); + possibleSearchDirs.set(projectRootPath, true); + possibleSearchDirs.forEach(function (_true, searchDir) { + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); + getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + }); + getTypingNamesFromSourceFileNames(fileNames); + // add typings for unresolved imports + if (unresolvedImports) { + var module_1 = ts.deduplicate(unresolvedImports.map(function (moduleId) { return JsTyping.nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + addInferredTypings(module_1, "Inferred typings from unresolved imports"); + } + // Add the cached typing locations for inferred typings that are already installed + packageNameToTypingLocation.forEach(function (typing, name) { + var registryEntry = typesRegistry.get(name); + if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) { + inferredTypings.set(name, typing.typingLocation); + } + }); + // Remove typings that the user has added to the exclude list + for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { + var excludeTypingName = exclude_1[_i]; + var didDelete = inferredTypings.delete(excludeTypingName); + if (didDelete && log) + log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); + } + var newTypingNames = []; + var cachedTypingPaths = []; + inferredTypings.forEach(function (inferred, typing) { + if (inferred !== undefined) { + cachedTypingPaths.push(inferred); + } + else { + newTypingNames.push(typing); + } + }); + var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + if (log) + log("Result: " + JSON.stringify(result)); + return result; + function addInferredTyping(typingName) { + if (!inferredTypings.has(typingName)) { + inferredTypings.set(typingName, undefined); // TODO: GH#18217 + } + } + function addInferredTypings(typingNames, message) { + if (log) + log(message + ": " + JSON.stringify(typingNames)); + ts.forEach(typingNames, addInferredTyping); + } + /** + * Get the typing info from common package manager json files like package.json or bower.json + */ + function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (!host.fileExists(jsonPath)) { + return; + } + filesToWatch.push(jsonPath); + var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; + var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); + addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); + } + /** + * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" + * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred + * to the 'angular-route' typing name. + * @param fileNames are the names for source files in the project + */ + function getTypingNamesFromSourceFileNames(fileNames) { + var fromFileNames = ts.mapDefined(fileNames, function (j) { + if (!ts.hasJavaScriptFileExtension(j)) + return undefined; + var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); + var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); + return safeList.get(cleanedTypingName); + }); + if (fromFileNames.length) { + addInferredTypings(fromFileNames, "Inferred typings from file names"); + } + var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); + if (hasJsxFile) { + if (log) + log("Inferred 'react' typings due to presence of '.jsx' extension"); + addInferredTyping("react"); + } + } + /** + * Infer typing names from packages folder (ex: node_module, bower_components) + * @param packagesFolderPath is the path to the packages folder + */ + function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { + filesToWatch.push(packagesFolderPath); + // Todo: add support for ModuleResolutionHost too + if (!host.directoryExists(packagesFolderPath)) { + return; + } + // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` + var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + if (log) + log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); + var packageNames = []; + for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { + var fileName = fileNames_1[_i]; + var normalizedFileName = ts.normalizePath(fileName); + var baseFileName = ts.getBaseFileName(normalizedFileName); + if (baseFileName !== "package.json" && baseFileName !== "bower.json") { + continue; + } + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; + // npm 3's package.json contains a "_requiredBy" field + // we should include all the top level module names for npm 2, and only module names whose + // "_requiredBy" field starts with "#" or equals "/" for npm 3. + if (baseFileName === "package.json" && packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!packageJson.name) { + continue; + } + var ownTypes = packageJson.types || packageJson.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (log) + log(" Package '" + packageJson.name + "' provides its own types."); + inferredTypings.set(packageJson.name, absolutePath); + } + else { + packageNames.push(packageJson.name); + } + } + addInferredTypings(packageNames, " Found package names"); + } + } + JsTyping.discoverTypings = discoverTypings; + var PackageNameValidationResult; + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; + })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); + var maxPackageNameLength = 214; + /** + * Validates package name using rules defined at https://docs.npmjs.com/files/package.json + */ + function validatePackageName(packageName) { + if (!packageName) { + return 2 /* EmptyName */; + } + if (packageName.length > maxPackageNameLength) { + return 3 /* NameTooLong */; + } + if (packageName.charCodeAt(0) === 46 /* dot */) { + return 4 /* NameStartsWithDot */; + } + if (packageName.charCodeAt(0) === 95 /* _ */) { + return 5 /* NameStartsWithUnderscore */; + } + // check if name is scope package like: starts with @ and has one '/' in the middle + // scoped packages are not currently supported + // TODO: when support will be added we'll need to split and check both scope and package name + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return 1 /* ScopedPackagesNotSupported */; + } + if (encodeURIComponent(packageName) !== packageName) { + return 6 /* NameContainsNonURISafeCharacters */; + } + return 0 /* Ok */; + } + JsTyping.validatePackageName = validatePackageName; + function renderPackageNameValidationFailure(result, typing) { + switch (result) { + case 2 /* EmptyName */: + return "Package name '" + typing + "' cannot be empty"; + case 3 /* NameTooLong */: + return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; + case 4 /* NameStartsWithDot */: + return "Package name '" + typing + "' cannot start with '.'"; + case 5 /* NameStartsWithUnderscore */: + return "Package name '" + typing + "' cannot start with '_'"; + case 1 /* ScopedPackagesNotSupported */: + return "Package '" + typing + "' is scoped and currently is not supported"; + case 6 /* NameContainsNonURISafeCharacters */: + return "Package name '" + typing + "' contains non URI safe characters"; + case 0 /* Ok */: + return ts.Debug.fail(); // Shouldn't have called this. + default: + throw ts.Debug.assertNever(result); + } + } + JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function stringToInt(str) { + var n = parseInt(str, 10); + if (isNaN(n)) { + throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); + } + return n; + } + var isPrereleaseRegex = /^(.*)-next.\d+/; + var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; + var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; + var Semver = /** @class */ (function () { + function Semver(major, minor, patch, + /** + * If true, this is `major.minor.0-next.patch`. + * If false, this is `major.minor.patch`. + */ + isPrerelease) { + this.major = major; + this.minor = minor; + this.patch = patch; + this.isPrerelease = isPrerelease; + } + Semver.parse = function (semver) { + var isPrerelease = isPrereleaseRegex.test(semver); + var result = Semver.tryParse(semver, isPrerelease); + if (!result) { + throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); + } + return result; + }; + Semver.fromRaw = function (_a) { + var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; + return new Semver(major, minor, patch, isPrerelease); + }; + // This must parse the output of `versionString`. + Semver.tryParse = function (semver, isPrerelease) { + // Per the semver spec : + // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." + var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; + var match = rgx.exec(semver); + return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; + }; + Object.defineProperty(Semver.prototype, "versionString", { + get: function () { + return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; + }, + enumerable: true, + configurable: true + }); + Semver.prototype.equals = function (sem) { + return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; + }; + Semver.prototype.greaterThan = function (sem) { + return this.major > sem.major || this.major === sem.major + && (this.minor > sem.minor || this.minor === sem.minor + && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease + && this.patch > sem.patch)); + }; + return Semver; + }()); + ts.Semver = Semver; })(ts || (ts = {})); var ts; (function (ts) { @@ -81070,6 +87747,8 @@ var ts; } ScriptSnapshot.fromString = fromString; })(ScriptSnapshot = ts.ScriptSnapshot || (ts.ScriptSnapshot = {})); + /* @internal */ + ts.emptyOptions = {}; var TextChange = /** @class */ (function () { function TextChange() { } @@ -81114,6 +87793,17 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["functionName"] = 20] = "functionName"; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(SymbolDisplayPartKind = ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); + var OutliningSpanKind; + (function (OutliningSpanKind) { + /** Single or multi-line comments */ + OutliningSpanKind["Comment"] = "comment"; + /** Sections marked by '// #region' and '// #endregion' comments */ + OutliningSpanKind["Region"] = "region"; + /** Declarations and expressions */ + OutliningSpanKind["Code"] = "code"; + /** Contiguous blocks of import declarations */ + OutliningSpanKind["Imports"] = "imports"; + })(OutliningSpanKind = ts.OutliningSpanKind || (ts.OutliningSpanKind = {})); var OutputFileType; (function (OutputFileType) { OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; @@ -81209,6 +87899,8 @@ var ts; * */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; + /** String literal */ + ScriptElementKind["string"] = "string"; })(ScriptElementKind = ts.ScriptElementKind || (ts.ScriptElementKind = {})); var ScriptElementKindModifier; (function (ScriptElementKindModifier) { @@ -81291,36 +87983,36 @@ var ts; })(SemanticMeaning = ts.SemanticMeaning || (ts.SemanticMeaning = {})); function getMeaningFromDeclaration(node) { switch (node.kind) { - case 148 /* Parameter */: - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 268 /* PropertyAssignment */: - case 269 /* ShorthandPropertyAssignment */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 267 /* CatchClause */: - case 260 /* JsxAttribute */: + case 149 /* Parameter */: + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 273 /* PropertyAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 272 /* CatchClause */: + case 265 /* JsxAttribute */: return 1 /* Value */; - case 147 /* TypeParameter */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 165 /* TypeLiteral */: + case 148 /* TypeParameter */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 166 /* TypeLiteral */: return 2 /* Type */; - case 291 /* JSDocTypedefTag */: + case 301 /* JSDocTypedefTag */: // If it has no name node, it shares the name with the value declaration below it. return node.name === undefined ? 1 /* Value */ | 2 /* Type */ : 2 /* Type */; - case 271 /* EnumMember */: - case 233 /* ClassDeclaration */: + case 276 /* EnumMember */: + case 238 /* ClassDeclaration */: return 1 /* Value */ | 2 /* Type */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.isAmbientModule(node)) { return 4 /* Namespace */ | 1 /* Value */; } @@ -81330,26 +88022,26 @@ var ts; else { return 4 /* Namespace */; } - case 236 /* EnumDeclaration */: - case 245 /* NamedImports */: - case 246 /* ImportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - case 242 /* ImportDeclaration */: - case 247 /* ExportAssignment */: - case 248 /* ExportDeclaration */: + case 241 /* EnumDeclaration */: + case 250 /* NamedImports */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 247 /* ImportDeclaration */: + case 252 /* ExportAssignment */: + case 253 /* ExportDeclaration */: return 7 /* All */; // An external module can be a Value - case 272 /* SourceFile */: + case 277 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } return 7 /* All */; } ts.getMeaningFromDeclaration = getMeaningFromDeclaration; function getMeaningFromLocation(node) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return 1 /* Value */; } - else if (node.parent.kind === 247 /* ExportAssignment */) { + else if (node.parent.kind === 252 /* ExportAssignment */) { return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -81368,6 +88060,10 @@ var ts; ts.Debug.assert(ts.isJSDocTemplateTag(node.parent.parent)); // Else would be handled by isDeclarationName return 2 /* Type */; } + else if (ts.isLiteralTypeNode(node.parent)) { + // This might be T["name"], which is actually referencing a property and not a type. So allow both meanings. + return 2 /* Type */ | 1 /* Value */; + } else { return 1 /* Value */; } @@ -81377,11 +88073,11 @@ var ts; // import a = |b|; // Namespace // import a = |b.c|; // Value, type, namespace // import a = |b.c|.d; // Namespace - var name = node.kind === 145 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; - return name && name.parent.kind === 241 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; + var name = node.kind === 146 /* QualifiedName */ ? node : ts.isQualifiedName(node.parent) && node.parent.right === node ? node.parent : undefined; + return name && name.parent.kind === 246 /* ImportEqualsDeclaration */ ? 7 /* All */ : 4 /* Namespace */; } function isInRightSideOfInternalImportEqualsDeclaration(node) { - while (node.parent.kind === 145 /* QualifiedName */) { + while (node.parent.kind === 146 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; @@ -81393,27 +88089,27 @@ var ts; function isQualifiedNameNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 145 /* QualifiedName */) { - while (root.parent && root.parent.kind === 145 /* QualifiedName */) { + if (root.parent.kind === 146 /* QualifiedName */) { + while (root.parent && root.parent.kind === 146 /* QualifiedName */) { root = root.parent; } isLastClause = root.right === node; } - return root.parent.kind === 161 /* TypeReference */ && !isLastClause; + return root.parent.kind === 162 /* TypeReference */ && !isLastClause; } function isPropertyAccessNamespaceReference(node) { var root = node; var isLastClause = true; - if (root.parent.kind === 183 /* PropertyAccessExpression */) { - while (root.parent && root.parent.kind === 183 /* PropertyAccessExpression */) { + if (root.parent.kind === 187 /* PropertyAccessExpression */) { + while (root.parent && root.parent.kind === 187 /* PropertyAccessExpression */) { root = root.parent; } isLastClause = root.name === node; } - if (!isLastClause && root.parent.kind === 205 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 266 /* HeritageClause */) { + if (!isLastClause && root.parent.kind === 209 /* ExpressionWithTypeArguments */ && root.parent.parent.kind === 271 /* HeritageClause */) { var decl = root.parent.parent.parent; - return (decl.kind === 233 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || - (decl.kind === 234 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); + return (decl.kind === 238 /* ClassDeclaration */ && root.parent.parent.token === 108 /* ImplementsKeyword */) || + (decl.kind === 239 /* InterfaceDeclaration */ && root.parent.parent.token === 85 /* ExtendsKeyword */); } return false; } @@ -81424,28 +88120,30 @@ var ts; switch (node.kind) { case 99 /* ThisKeyword */: return !ts.isExpressionNode(node); - case 173 /* ThisType */: + case 176 /* ThisType */: return true; } switch (node.parent.kind) { - case 161 /* TypeReference */: + case 162 /* TypeReference */: return true; - case 205 /* ExpressionWithTypeArguments */: + case 181 /* ImportType */: + return !node.parent.isTypeOf; + case 209 /* ExpressionWithTypeArguments */: return !ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent); } return false; } function isCallExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 185 /* CallExpression */); + return isCallOrNewExpressionTarget(node, 189 /* CallExpression */); } ts.isCallExpressionTarget = isCallExpressionTarget; function isNewExpressionTarget(node) { - return isCallOrNewExpressionTarget(node, 186 /* NewExpression */); + return isCallOrNewExpressionTarget(node, 190 /* NewExpression */); } ts.isNewExpressionTarget = isNewExpressionTarget; function isCallOrNewExpressionTarget(node, kind) { var target = climbPastPropertyAccess(node); - return target && target.parent && target.parent.kind === kind && target.parent.expression === target; + return !!target && !!target.parent && target.parent.kind === kind && target.parent.expression === target; } function climbPastPropertyAccess(node) { return isRightSideOfPropertyAccess(node) ? node.parent : node; @@ -81453,7 +88151,7 @@ var ts; ts.climbPastPropertyAccess = climbPastPropertyAccess; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 226 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { + if (referenceNode.kind === 231 /* LabeledStatement */ && referenceNode.label.escapedText === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -81474,15 +88172,15 @@ var ts; } ts.isLabelName = isLabelName; function isRightSideOfQualifiedName(node) { - return node.parent.kind === 145 /* QualifiedName */ && node.parent.right === node; + return node.parent.kind === 146 /* QualifiedName */ && node.parent.right === node; } ts.isRightSideOfQualifiedName = isRightSideOfQualifiedName; function isRightSideOfPropertyAccess(node) { - return node && node.parent && node.parent.kind === 183 /* PropertyAccessExpression */ && node.parent.name === node; + return node && node.parent && node.parent.kind === 187 /* PropertyAccessExpression */ && node.parent.name === node; } ts.isRightSideOfPropertyAccess = isRightSideOfPropertyAccess; function isNameOfModuleDeclaration(node) { - return node.parent.kind === 237 /* ModuleDeclaration */ && node.parent.name === node; + return node.parent.kind === 242 /* ModuleDeclaration */ && node.parent.name === node; } ts.isNameOfModuleDeclaration = isNameOfModuleDeclaration; function isNameOfFunctionDeclaration(node) { @@ -81492,22 +88190,24 @@ var ts; ts.isNameOfFunctionDeclaration = isNameOfFunctionDeclaration; function isLiteralNameOfPropertyDeclarationOrIndexAccess(node) { switch (node.parent.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 268 /* PropertyAssignment */: - case 271 /* EnumMember */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 237 /* ModuleDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 273 /* PropertyAssignment */: + case 276 /* EnumMember */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 242 /* ModuleDeclaration */: return ts.getNameOfDeclaration(node.parent) === node; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: return node.parent.argumentExpression === node; - case 146 /* ComputedPropertyName */: + case 147 /* ComputedPropertyName */: return true; - case 177 /* LiteralType */: - return node.parent.parent.kind === 175 /* IndexedAccessType */; + case 180 /* LiteralType */: + return node.parent.parent.kind === 178 /* IndexedAccessType */; + default: + return false; } } ts.isLiteralNameOfPropertyDeclarationOrIndexAccess = isLiteralNameOfPropertyDeclarationOrIndexAccess; @@ -81517,7 +88217,7 @@ var ts; } ts.isExpressionOfExternalModuleImportEqualsDeclaration = isExpressionOfExternalModuleImportEqualsDeclaration; function getContainerNode(node) { - if (node.kind === 291 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. // Then we get parent again in the loop. @@ -81529,17 +88229,17 @@ var ts; return undefined; } switch (node.kind) { - case 272 /* SourceFile */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: + case 277 /* SourceFile */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: return node; } } @@ -81547,48 +88247,48 @@ var ts; ts.getContainerNode = getContainerNode; function getNodeKind(node) { switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: return ts.isExternalModule(node) ? "module" /* moduleElement */ : "script" /* scriptElement */; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return "module" /* moduleElement */; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: return "class" /* classElement */; - case 234 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; - case 235 /* TypeAliasDeclaration */: return "type" /* typeElement */; - case 236 /* EnumDeclaration */: return "enum" /* enumElement */; - case 230 /* VariableDeclaration */: - return getKindOfVariableDeclaration(node); - case 180 /* BindingElement */: - return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - return "function" /* functionElement */; - case 155 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; - case 156 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return "method" /* memberFunctionElement */; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - return "property" /* memberVariableElement */; - case 159 /* IndexSignature */: return "index" /* indexSignatureElement */; - case 158 /* ConstructSignature */: return "construct" /* constructSignatureElement */; - case 157 /* CallSignature */: return "call" /* callSignatureElement */; - case 154 /* Constructor */: return "constructor" /* constructorImplementationElement */; - case 147 /* TypeParameter */: return "type parameter" /* typeParameterElement */; - case 271 /* EnumMember */: return "enum member" /* enumMemberElement */; - case 148 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; - case 241 /* ImportEqualsDeclaration */: - case 246 /* ImportSpecifier */: - case 243 /* ImportClause */: - case 250 /* ExportSpecifier */: - case 244 /* NamespaceImport */: - return "alias" /* alias */; - case 291 /* JSDocTypedefTag */: + case 239 /* InterfaceDeclaration */: return "interface" /* interfaceElement */; + case 240 /* TypeAliasDeclaration */: + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: return "type" /* typeElement */; - case 198 /* BinaryExpression */: + case 241 /* EnumDeclaration */: return "enum" /* enumElement */; + case 235 /* VariableDeclaration */: + return getKindOfVariableDeclaration(node); + case 184 /* BindingElement */: + return getKindOfVariableDeclaration(ts.getRootDeclaration(node)); + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + return "function" /* functionElement */; + case 156 /* GetAccessor */: return "getter" /* memberGetAccessorElement */; + case 157 /* SetAccessor */: return "setter" /* memberSetAccessorElement */; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + return "method" /* memberFunctionElement */; + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + return "property" /* memberVariableElement */; + case 160 /* IndexSignature */: return "index" /* indexSignatureElement */; + case 159 /* ConstructSignature */: return "construct" /* constructSignatureElement */; + case 158 /* CallSignature */: return "call" /* callSignatureElement */; + case 155 /* Constructor */: return "constructor" /* constructorImplementationElement */; + case 148 /* TypeParameter */: return "type parameter" /* typeParameterElement */; + case 276 /* EnumMember */: return "enum member" /* enumMemberElement */; + case 149 /* Parameter */: return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) ? "property" /* memberVariableElement */ : "parameter" /* parameterElement */; + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: + case 249 /* NamespaceImport */: + return "alias" /* alias */; + case 202 /* BinaryExpression */: var kind = ts.getSpecialPropertyAssignmentKind(node); var right = node.right; switch (kind) { @@ -81612,11 +88312,13 @@ var ts; return "" /* unknown */; } } + case 71 /* Identifier */: + return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; } function getKindOfVariableDeclaration(v) { - return ts.isConst(v) + return ts.isVarConst(v) ? "const" /* constElement */ : ts.isLet(v) ? "let" /* letElement */ @@ -81631,7 +88333,7 @@ var ts; return true; case 71 /* Identifier */: // 'this' as a parameter - return ts.identifierIsThisKeyword(node) && node.parent.kind === 148 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 149 /* Parameter */; default: return false; } @@ -81649,6 +88351,18 @@ var ts; return startEndContainsRange(r1.pos, r1.end, r2); } ts.rangeContainsRange = rangeContainsRange; + function rangeContainsRangeExclusive(r1, r2) { + return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end); + } + ts.rangeContainsRangeExclusive = rangeContainsRangeExclusive; + function rangeContainsPosition(r, pos) { + return r.pos <= pos && pos <= r.end; + } + ts.rangeContainsPosition = rangeContainsPosition; + function rangeContainsPositionExclusive(r, pos) { + return r.pos < pos && pos < r.end; + } + ts.rangeContainsPositionExclusive = rangeContainsPositionExclusive; function startEndContainsRange(start, end, range) { return start <= range.pos && end >= range.end; } @@ -81661,6 +88375,10 @@ var ts; return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); } ts.rangeOverlapsWithStartEnd = rangeOverlapsWithStartEnd; + function nodeOverlapsWithStartEnd(node, sourceFile, start, end) { + return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); + } + ts.nodeOverlapsWithStartEnd = nodeOverlapsWithStartEnd; function startEndOverlapsWithStartEnd(start1, end1, start2, end2) { var start = Math.max(start1, start2); var end = Math.min(end1, end2); @@ -81676,46 +88394,46 @@ var ts; } ts.positionBelongsToNode = positionBelongsToNode; function isCompletedNode(n, sourceFile) { - if (ts.nodeIsMissing(n)) { + if (n === undefined || ts.nodeIsMissing(n)) { return false; } switch (n.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 182 /* ObjectLiteralExpression */: - case 178 /* ObjectBindingPattern */: - case 165 /* TypeLiteral */: - case 211 /* Block */: - case 238 /* ModuleBlock */: - case 239 /* CaseBlock */: - case 245 /* NamedImports */: - case 249 /* NamedExports */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 186 /* ObjectLiteralExpression */: + case 182 /* ObjectBindingPattern */: + case 166 /* TypeLiteral */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 244 /* CaseBlock */: + case 250 /* NamedImports */: + case 254 /* NamedExports */: return nodeEndsWith(n, 18 /* CloseBraceToken */, sourceFile); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return isCompletedNode(n.block, sourceFile); - case 186 /* NewExpression */: + case 190 /* NewExpression */: if (!n.arguments) { return true; } // falls through - case 185 /* CallExpression */: - case 189 /* ParenthesizedExpression */: - case 172 /* ParenthesizedType */: + case 189 /* CallExpression */: + case 193 /* ParenthesizedExpression */: + case 175 /* ParenthesizedType */: return nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile); - case 162 /* FunctionType */: - case 163 /* ConstructorType */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: return isCompletedNode(n.type, sourceFile); - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 158 /* ConstructSignature */: - case 157 /* CallSignature */: - case 191 /* ArrowFunction */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 159 /* ConstructSignature */: + case 158 /* CallSignature */: + case 195 /* ArrowFunction */: if (n.body) { return isCompletedNode(n.body, sourceFile); } @@ -81725,65 +88443,65 @@ var ts; // Even though type parameters can be unclosed, we can get away with // having at least a closing paren. return hasChildOfKind(n, 20 /* CloseParenToken */, sourceFile); - case 237 /* ModuleDeclaration */: - return n.body && isCompletedNode(n.body, sourceFile); - case 215 /* IfStatement */: + case 242 /* ModuleDeclaration */: + return !!n.body && isCompletedNode(n.body, sourceFile); + case 220 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile) || hasChildOfKind(n, 25 /* SemicolonToken */, sourceFile); - case 181 /* ArrayLiteralExpression */: - case 179 /* ArrayBindingPattern */: - case 184 /* ElementAccessExpression */: - case 146 /* ComputedPropertyName */: - case 167 /* TupleType */: + case 185 /* ArrayLiteralExpression */: + case 183 /* ArrayBindingPattern */: + case 188 /* ElementAccessExpression */: + case 147 /* ComputedPropertyName */: + case 168 /* TupleType */: return nodeEndsWith(n, 22 /* CloseBracketToken */, sourceFile); - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: if (n.type) { return isCompletedNode(n.type, sourceFile); } return hasChildOfKind(n, 22 /* CloseBracketToken */, sourceFile); - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // there is no such thing as terminator token for CaseClause/DefaultClause so for simplicity always consider them non-completed return false; - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 216 /* DoStatement */: + case 221 /* DoStatement */: // rough approximation: if DoStatement has While keyword - then if node is completed is checking the presence of ')'; return hasChildOfKind(n, 106 /* WhileKeyword */, sourceFile) ? nodeEndsWith(n, 20 /* CloseParenToken */, sourceFile) : isCompletedNode(n.statement, sourceFile); - case 164 /* TypeQuery */: + case 165 /* TypeQuery */: return isCompletedNode(n.exprName, sourceFile); - case 193 /* TypeOfExpression */: - case 192 /* DeleteExpression */: - case 194 /* VoidExpression */: - case 201 /* YieldExpression */: - case 202 /* SpreadElement */: + case 197 /* TypeOfExpression */: + case 196 /* DeleteExpression */: + case 198 /* VoidExpression */: + case 205 /* YieldExpression */: + case 206 /* SpreadElement */: var unaryWordExpression = n; return isCompletedNode(unaryWordExpression.expression, sourceFile); - case 187 /* TaggedTemplateExpression */: + case 191 /* TaggedTemplateExpression */: return isCompletedNode(n.template, sourceFile); - case 200 /* TemplateExpression */: + case 204 /* TemplateExpression */: var lastSpan = ts.lastOrUndefined(n.templateSpans); return isCompletedNode(lastSpan, sourceFile); - case 209 /* TemplateSpan */: + case 214 /* TemplateSpan */: return ts.nodeIsPresent(n.literal); - case 248 /* ExportDeclaration */: - case 242 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: return ts.nodeIsPresent(n.moduleSpecifier); - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: return isCompletedNode(n.operand, sourceFile); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: return isCompletedNode(n.right, sourceFile); - case 199 /* ConditionalExpression */: + case 203 /* ConditionalExpression */: return isCompletedNode(n.whenFalse, sourceFile); default: return true; @@ -81796,11 +88514,11 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last_2 = ts.lastOrUndefined(children); - if (last_2.kind === expectedLastToken) { + var lastChild = ts.last(children); + if (lastChild.kind === expectedLastToken) { return true; } - else if (last_2.kind === 25 /* SemicolonToken */ && children.length !== 1) { + else if (lastChild.kind === 25 /* SemicolonToken */ && children.length !== 1) { return children[children.length - 2].kind === expectedLastToken; } } @@ -81842,48 +88560,35 @@ var ts; return syntaxList; } ts.findContainingList = findContainingList; - /* Gets the token whose text has range [start, end) and - * position >= start and (position < end or (position === end && token is keyword or identifier)) + /** + * Gets the token whose text has range [start, end) and + * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) */ - function getTouchingWord(sourceFile, position, includeJsDocComment) { - return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isWord(n.kind); }); - } - ts.getTouchingWord = getTouchingWord; - /* Gets the token whose text has range [start, end) and position >= start - * and (position < end or (position === end && token is keyword or identifier or numeric/string literal)) - */ - function getTouchingPropertyName(sourceFile, position, includeJsDocComment) { - return getTouchingToken(sourceFile, position, includeJsDocComment, function (n) { return isPropertyName(n.kind); }); + function getTouchingPropertyName(sourceFile, position) { + return getTouchingToken(sourceFile, position, function (n) { return ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind); }); } ts.getTouchingPropertyName = getTouchingPropertyName; /** * Returns the token if position is in [start, end). * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true */ - function getTouchingToken(sourceFile, position, includeJsDocComment, includePrecedingTokenAtEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false, includeJsDocComment); + function getTouchingToken(sourceFile, position, includePrecedingTokenAtEndPosition) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); } ts.getTouchingToken = getTouchingToken; /** Returns a token if position is in [start-of-leading-trivia, end) */ - function getTokenAtPosition(sourceFile, position, includeJsDocComment, includeEndPosition) { - return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, includeEndPosition, includeJsDocComment); + function getTokenAtPosition(sourceFile, position) { + return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); } ts.getTokenAtPosition = getTokenAtPosition; /** Get the token whose text contains the position */ - function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition, includeJsDocComment) { + function getTokenAtPositionWorker(sourceFile, position, allowPositionInLeadingTrivia, includePrecedingTokenAtEndPosition, includeEndPosition) { var current = sourceFile; outer: while (true) { - if (ts.isToken(current)) { - // exit early - return current; - } // find the child that contains 'position' - for (var _i = 0, _a = current.getChildren(); _i < _a.length; _i++) { + for (var _i = 0, _a = current.getChildren(sourceFile); _i < _a.length; _i++) { var child = _a[_i]; - if (!includeJsDocComment && ts.isJSDocNode(child)) { - continue; - } - var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, includeJsDocComment); + var start = allowPositionInLeadingTrivia ? child.getFullStart() : child.getStart(sourceFile, /*includeJsDoc*/ true); if (start > position) { // If this child begins after position, then all subsequent children will as well. break; @@ -81914,33 +88619,28 @@ var ts; function findTokenOnLeftOfPosition(file, position) { // Ideally, getTokenAtPosition should return a token. However, it is currently // broken, so we do a check to make sure the result was indeed a token. - var tokenAtPosition = getTokenAtPosition(file, position, /*includeJsDocComment*/ false); + var tokenAtPosition = getTokenAtPosition(file, position); if (ts.isToken(tokenAtPosition) && position > tokenAtPosition.getStart(file) && position < tokenAtPosition.getEnd()) { return tokenAtPosition; } return findPrecedingToken(position, file); } ts.findTokenOnLeftOfPosition = findTokenOnLeftOfPosition; - function findNextToken(previousToken, parent) { + function findNextToken(previousToken, parent, sourceFile) { return find(parent); function find(n) { if (ts.isToken(n) && n.pos === previousToken.end) { // this is token that starts at the end of previous token - return it return n; } - var children = n.getChildren(); - for (var _i = 0, children_3 = children; _i < children_3.length; _i++) { - var child = children_3[_i]; + return ts.firstDefined(n.getChildren(), function (child) { var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || // previous token ends exactly at the beginning of child (child.pos === previousToken.end); - if (shouldDiveInChildNode && nodeHasTokens(child)) { - return find(child); - } - } - return undefined; + return shouldDiveInChildNode && nodeHasTokens(child, sourceFile) ? find(child) : undefined; + }); } } ts.findNextToken = findNextToken; @@ -81948,7 +88648,7 @@ var ts; * Finds the rightmost token satisfying `token.end <= position`, * excluding `JsxText` tokens containing only whitespace. */ - function findPrecedingToken(position, sourceFile, startNode, includeJsDoc) { + function findPrecedingToken(position, sourceFile, startNode, excludeJsdoc) { var result = find(startNode || sourceFile); ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); return result; @@ -81965,13 +88665,13 @@ var ts; // 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 start = child.getStart(sourceFile, /*includeJsDoc*/ !excludeJsdoc); var lookInPreviousChild = (start >= position) || // cursor in the leading trivia - !nodeHasTokens(child) || + !nodeHasTokens(child, sourceFile) || 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); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } else { @@ -81980,13 +88680,13 @@ var ts; } } } - ts.Debug.assert(startNode !== undefined || n.kind === 272 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); + ts.Debug.assert(startNode !== undefined || n.kind === 277 /* SourceFile */ || ts.isJSDocCommentContainingNode(n)); // Here we know that none of child token nodes embrace the position, // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' if (children.length) { - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -82000,19 +88700,19 @@ var ts; return n; } var children = n.getChildren(sourceFile); - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); return candidate && findRightmostToken(candidate, sourceFile); } /** * 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) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { for (var i = exclusiveStartPosition - 1; i >= 0; 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])) { + else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; } } @@ -82020,7 +88720,7 @@ var ts; function isInString(sourceFile, position, previousToken) { if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { - var start = previousToken.getStart(); + var start = previousToken.getStart(sourceFile); var end = previousToken.getEnd(); // To be "in" one of these literals, the position has to be: // 1. entirely within the token text. @@ -82040,7 +88740,7 @@ var ts; * returns true if the position is in between the open and close elements of an JSX expression. */ function isInsideJsxElementOrAttribute(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); if (!token) { return false; } @@ -82052,17 +88752,17 @@ var ts; return true; } //
{ |
or
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 263 /* JsxExpression */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
{ // | // } < /div> - if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 263 /* JsxExpression */) { + if (token && token.kind === 18 /* CloseBraceToken */ && token.parent.kind === 268 /* JsxExpression */) { return true; } //
|
- if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 256 /* JsxClosingElement */) { + if (token.kind === 27 /* LessThanToken */ && token.parent.kind === 261 /* JsxClosingElement */) { return true; } return false; @@ -82072,7 +88772,7 @@ var ts; return ts.isJsxText(node) && node.containsOnlyWhiteSpaces; } function isInTemplateString(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = getTokenAtPosition(sourceFile, position); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } ts.isInTemplateString = isInTemplateString; @@ -82080,10 +88780,11 @@ var ts; var tokenKind = token.kind; var remainingMatchingTokens = 0; while (true) { - token = findPrecedingToken(token.getFullStart(), sourceFile); - if (!token) { + var preceding = findPrecedingToken(token.getFullStart(), sourceFile); + if (!preceding) { return undefined; } + token = preceding; if (token.kind === matchingTokenKind) { if (remainingMatchingTokens === 0) { return token; @@ -82096,21 +88797,38 @@ var ts; } } ts.findPrecedingMatchingToken = findPrecedingMatchingToken; - function isPossiblyTypeArgumentPosition(token, sourceFile) { + function isPossiblyTypeArgumentPosition(token, sourceFile, checker) { + var info = getPossibleTypeArgumentsInfo(token, sourceFile); + return info !== undefined && (ts.isPartOfTypeNode(info.called) || + getPossibleGenericSignatures(info.called, info.nTypeArguments, checker).length !== 0 || + isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); + } + ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + function getPossibleGenericSignatures(called, typeArgumentCount, checker) { + var type = checker.getTypeAtLocation(called); + var signatures = ts.isNewExpression(called.parent) ? type.getConstructSignatures() : type.getCallSignatures(); + return signatures.filter(function (candidate) { return !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount; }); + } + ts.getPossibleGenericSignatures = getPossibleGenericSignatures; + // Get info for an expression like `f <` that may be the start of type arguments. + function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { + var token = tokenIn; // This function determines if the node could be type argument position // Since during editing, when type argument list is not complete, // the tree could be of any shape depending on the tokens parsed before current node, // scanning of the previous identifier followed by "<" before current node would give us better result // Note that we also balance out the already provided type arguments, arrays, object literals while doing so var remainingLessThanTokens = 0; + var nTypeArguments = 0; while (token) { switch (token.kind) { case 27 /* LessThanToken */: // Found the beginning of the generic argument expression token = findPrecedingToken(token.getFullStart(), sourceFile); - var tokenIsIdentifier = token && ts.isIdentifier(token); - if (!remainingLessThanTokens || !tokenIsIdentifier) { - return tokenIsIdentifier; + if (!token || !ts.isIdentifier(token)) + return undefined; + if (!remainingLessThanTokens) { + return ts.isDeclarationName(token) ? undefined : { called: token, nTypeArguments: nTypeArguments }; } remainingLessThanTokens--; break; @@ -82124,28 +88842,30 @@ var ts; remainingLessThanTokens++; break; case 18 /* CloseBraceToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 17 /* OpenBraceToken */, sourceFile); if (!token) - return false; + return undefined; break; case 20 /* CloseParenToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 19 /* OpenParenToken */, sourceFile); if (!token) - return false; + return undefined; break; case 22 /* CloseBracketToken */: - // This can be object type, skip untill we find the matching open brace token - // Skip untill the matching open brace token + // This can be object type, skip until we find the matching open brace token + // Skip until the matching open brace token token = findPrecedingMatchingToken(token, 21 /* OpenBracketToken */, sourceFile); if (!token) - return false; + return undefined; break; // Valid tokens in a type name. Skip. case 26 /* CommaToken */: + nTypeArguments++; + break; case 36 /* EqualsGreaterThanToken */: case 71 /* Identifier */: case 9 /* StringLiteral */: @@ -82165,41 +88885,35 @@ var ts; break; } // Invalid token in type - return false; + return undefined; } token = findPrecedingToken(token.getFullStart(), sourceFile); } - return false; + return undefined; } - ts.isPossiblyTypeArgumentPosition = isPossiblyTypeArgumentPosition; + ts.getPossibleTypeArgumentsInfo = getPossibleTypeArgumentsInfo; /** * Returns true if the cursor at position in sourceFile is within a comment. * * @param tokenAtPosition Must equal `getTokenAtPosition(sourceFile, position) * @param predicate Additional predicate to test on the comment range. */ - function isInComment(sourceFile, position, tokenAtPosition, predicate) { - return !!ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*onlyMultiLine*/ false, /*precedingToken*/ undefined, tokenAtPosition, predicate); + function isInComment(sourceFile, position, tokenAtPosition) { + return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); } ts.isInComment = isInComment; function hasDocComment(sourceFile, position) { - var token = getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - // First, we have to see if this position actually landed in a comment. - var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); - return ts.forEach(commentRanges, jsDocPrefix); - function jsDocPrefix(c) { - var text = sourceFile.text; - return text.length >= c.pos + 3 && text[c.pos] === "/" && text[c.pos + 1] === "*" && text[c.pos + 2] === "*"; - } + var token = getTokenAtPosition(sourceFile, position); + return !!ts.findAncestor(token, ts.isJSDoc); } ts.hasDocComment = hasDocComment; - function nodeHasTokens(n) { + function nodeHasTokens(n, sourceFile) { // If we have a token or node that has a non-zero width, it must have tokens. // Note: getWidth() does not take trivia into account. - return n.getWidth() !== 0; + return n.getWidth(sourceFile) !== 0; } function getNodeModifiers(node) { - var flags = ts.getCombinedModifierFlags(node); + var flags = ts.isDeclaration(node) ? ts.getCombinedModifierFlags(node) : 0 /* None */; var result = []; if (flags & 8 /* Private */) result.push("private" /* privateMemberModifier */); @@ -82213,28 +88927,21 @@ var ts; result.push("abstract" /* abstractModifier */); if (flags & 1 /* Export */) result.push("export" /* exportedModifier */); - if (node.flags & 2097152 /* Ambient */) + if (node.flags & 4194304 /* Ambient */) result.push("declare" /* ambientModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } ts.getNodeModifiers = getNodeModifiers; function getTypeArgumentOrTypeParameterList(node) { - if (node.kind === 161 /* TypeReference */ || node.kind === 185 /* CallExpression */) { + if (node.kind === 162 /* TypeReference */ || node.kind === 189 /* CallExpression */) { return node.typeArguments; } - if (ts.isFunctionLike(node) || node.kind === 233 /* ClassDeclaration */ || node.kind === 234 /* InterfaceDeclaration */) { + if (ts.isFunctionLike(node) || node.kind === 238 /* ClassDeclaration */ || node.kind === 239 /* InterfaceDeclaration */) { return node.typeParameters; } return undefined; } ts.getTypeArgumentOrTypeParameterList = getTypeArgumentOrTypeParameterList; - function isWord(kind) { - return kind === 71 /* Identifier */ || ts.isKeyword(kind); - } - ts.isWord = isWord; - function isPropertyName(kind) { - return kind === 9 /* StringLiteral */ || kind === 8 /* NumericLiteral */ || isWord(kind); - } function isComment(kind) { return kind === 2 /* SingleLineCommentTrivia */ || kind === 3 /* MultiLineCommentTrivia */; } @@ -82252,9 +88959,9 @@ var ts; return 17 /* FirstPunctuation */ <= kind && kind <= 70 /* LastPunctuation */; } ts.isPunctuation = isPunctuation; - function isInsideTemplateLiteral(node, position) { + function isInsideTemplateLiteral(node, position, sourceFile) { return ts.isTemplateLiteralKind(node.kind) - && (node.getStart() < position && position < node.getEnd()) || (!!node.isUnterminated && position === node.getEnd()); + && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); } ts.isInsideTemplateLiteral = isInsideTemplateLiteral; function isAccessibilityModifier(kind) { @@ -82274,18 +88981,18 @@ var ts; } ts.cloneCompilerOptions = cloneCompilerOptions; function isArrayLiteralOrObjectLiteralDestructuringPattern(node) { - if (node.kind === 181 /* ArrayLiteralExpression */ || - node.kind === 182 /* ObjectLiteralExpression */) { + if (node.kind === 185 /* ArrayLiteralExpression */ || + node.kind === 186 /* ObjectLiteralExpression */) { // [a,b,c] from: // [a, b, c] = someExpression; - if (node.parent.kind === 198 /* BinaryExpression */ && + if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.left === node && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return true; } // [a, b, c] from: // for([a, b, c] of expression) - if (node.parent.kind === 220 /* ForOfStatement */ && + if (node.parent.kind === 225 /* ForOfStatement */ && node.parent.initializer === node) { return true; } @@ -82293,40 +89000,41 @@ var ts; // [x, [a, b, c] ] = someExpression // or // {x, a: {a, b, c} } = someExpression - if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 268 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { + if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.kind === 273 /* PropertyAssignment */ ? node.parent.parent : node.parent)) { return true; } } return false; } ts.isArrayLiteralOrObjectLiteralDestructuringPattern = isArrayLiteralOrObjectLiteralDestructuringPattern; - function hasTrailingDirectorySeparator(path) { - var lastCharacter = path.charAt(path.length - 1); - return lastCharacter === "/" || lastCharacter === "\\"; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; function isInReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); } ts.isInReferenceComment = isInReferenceComment; function isInNonReferenceComment(sourceFile, position) { - return isInComment(sourceFile, position, /*tokenAtPosition*/ undefined, function (c) { - var commentText = sourceFile.text.substring(c.pos, c.end); - return !tripleSlashDirectivePrefixRegex.test(commentText); - }); + return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); } ts.isInNonReferenceComment = isInNonReferenceComment; + function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { + var range = isInComment(sourceFile, position, /*tokenAtPosition*/ undefined); + return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); + } function createTextSpanFromNode(node, sourceFile) { return ts.createTextSpanFromBounds(node.getStart(sourceFile), node.getEnd()); } ts.createTextSpanFromNode = createTextSpanFromNode; + function createTextRangeFromNode(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile), node.end); + } + ts.createTextRangeFromNode = createTextRangeFromNode; function createTextSpanFromRange(range) { return ts.createTextSpanFromBounds(range.pos, range.end); } ts.createTextSpanFromRange = createTextSpanFromRange; + function createTextRangeFromSpan(span) { + return ts.createTextRange(span.start, span.start + span.length); + } + ts.createTextRangeFromSpan = createTextRangeFromSpan; function createTextChangeFromStartLength(start, length, newText) { return createTextChange(ts.createTextSpan(start, length), newText); } @@ -82348,6 +89056,7 @@ var ts; 105 /* VoidKeyword */, 140 /* UndefinedKeyword */, 141 /* UniqueKeyword */, + 142 /* UnknownKeyword */, ]; function isTypeKeyword(kind) { return ts.contains(ts.typeKeywords, kind); @@ -82355,11 +89064,9 @@ var ts; ts.isTypeKeyword = isTypeKeyword; /** True if the symbol is for an external module, as opposed to a namespace. */ function isExternalModuleSymbol(moduleSymbol) { - ts.Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); - return moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; + return !!(moduleSymbol.flags & 1536 /* Module */) && moduleSymbol.name.charCodeAt(0) === 34 /* doubleQuote */; } ts.isExternalModuleSymbol = isExternalModuleSymbol; - /** Returns `true` the first time it encounters a node and `false` afterwards. */ function nodeSeenTracker() { var seen = []; return function (node) { @@ -82368,16 +89075,6 @@ var ts; }; } ts.nodeSeenTracker = nodeSeenTracker; - /** Add a value to a set, and return true if it wasn't already present. */ - function addToSeen(seen, key) { - key = String(key); - if (seen.has(key)) { - return false; - } - seen.set(key, true); - return true; - } - ts.addToSeen = addToSeen; function getSnapshotText(snap) { return snap.getText(0, snap.getLength()); } @@ -82390,23 +89087,241 @@ var ts; return result; } ts.repeatString = repeatString; + function skipConstraint(type) { + return type.isTypeParameter() ? type.getConstraint() : type; // TODO: GH#18217 + } + ts.skipConstraint = skipConstraint; + function getNameFromPropertyName(name) { + return name.kind === 147 /* ComputedPropertyName */ + // treat computed property names where expression is string/numeric literal as just string/numeric literal + ? ts.isStringOrNumericLiteral(name.expression) ? name.expression.text : undefined + : ts.getTextOfIdentifierOrLiteral(name); + } + ts.getNameFromPropertyName = getNameFromPropertyName; + function programContainsEs6Modules(program) { + return program.getSourceFiles().some(function (s) { return !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator; }); + } + ts.programContainsEs6Modules = programContainsEs6Modules; + function compilerOptionsIndicateEs6Modules(compilerOptions) { + return !!compilerOptions.module || compilerOptions.target >= 2 /* ES2015 */ || !!compilerOptions.noEmit; + } + ts.compilerOptionsIndicateEs6Modules = compilerOptionsIndicateEs6Modules; + function hostUsesCaseSensitiveFileNames(host) { + return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; + } + ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames; + function hostGetCanonicalFileName(host) { + return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); + } + ts.hostGetCanonicalFileName = hostGetCanonicalFileName; + function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; + } + ts.makeImportIfNecessary = makeImportIfNecessary; + function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) { + return ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, defaultImport || namedImports + ? ts.createImportClause(defaultImport, namedImports && namedImports.length ? ts.createNamedImports(namedImports) : undefined) + : undefined, typeof moduleSpecifier === "string" ? makeStringLiteral(moduleSpecifier, quotePreference) : moduleSpecifier); + } + ts.makeImport = makeImport; + function makeStringLiteral(text, quotePreference) { + return ts.createLiteral(text, quotePreference === 0 /* Single */); + } + ts.makeStringLiteral = makeStringLiteral; + var QuotePreference; + (function (QuotePreference) { + QuotePreference[QuotePreference["Single"] = 0] = "Single"; + QuotePreference[QuotePreference["Double"] = 1] = "Double"; + })(QuotePreference = ts.QuotePreference || (ts.QuotePreference = {})); + function quotePreferenceFromString(str, sourceFile) { + return ts.isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; + } + ts.quotePreferenceFromString = quotePreferenceFromString; + function getQuotePreference(sourceFile, preferences) { + if (preferences.quotePreference) { + return preferences.quotePreference === "single" ? 0 /* Single */ : 1 /* Double */; + } + else { + var firstModuleSpecifier = sourceFile.imports && ts.find(sourceFile.imports, ts.isStringLiteral); + return firstModuleSpecifier ? quotePreferenceFromString(firstModuleSpecifier, sourceFile) : 1 /* Double */; + } + } + ts.getQuotePreference = getQuotePreference; + function symbolNameNoDefault(symbol) { + var escaped = symbolEscapedNameNoDefault(symbol); + return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); + } + ts.symbolNameNoDefault = symbolNameNoDefault; + function symbolEscapedNameNoDefault(symbol) { + if (symbol.escapedName !== "default" /* Default */) { + return symbol.escapedName; + } + return ts.firstDefined(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); + return name && name.kind === 71 /* Identifier */ ? name.escapedText : undefined; + }); + } + ts.symbolEscapedNameNoDefault = symbolEscapedNameNoDefault; + function getPropertySymbolFromBindingElement(checker, bindingElement) { + var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); + var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); + if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { + // See GH#16922 + ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); + return propSymbol.target; + } + return propSymbol; + } + ts.getPropertySymbolFromBindingElement = getPropertySymbolFromBindingElement; + /** + * Find symbol of the given property-name and add the symbol to the given result array + * @param symbol a symbol to start searching for the given propertyName + * @param propertyName a name of property to search for + * @param result an array of symbol of found property symbols + * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. + * The value of previousIterationSymbol is undefined when the function is first called. + */ + function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { + var seen = ts.createMap(); + return recur(symbol); + function recur(symbol) { + // Use `addToSeen` to ensure we don't infinitely recurse in this situation: + // interface C extends C { + // /*findRef*/propName: string; + // } + if (!(symbol.flags & (32 /* Class */ | 64 /* Interface */)) || !ts.addToSeen(seen, ts.getSymbolId(symbol))) + return; + return ts.firstDefined(symbol.declarations, function (declaration) { return ts.firstDefined(ts.getAllSuperTypeNodes(declaration), function (typeReference) { + var type = checker.getTypeAtLocation(typeReference); + var propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); + // Visit the typeReference as well to see if it directly or indirectly uses that property + return type && propertySymbol && (ts.firstDefined(checker.getRootSymbols(propertySymbol), cb) || recur(type.symbol)); + }); }); + } + } + ts.getPropertySymbolsFromBaseTypes = getPropertySymbolsFromBaseTypes; + function isMemberSymbolInBaseType(memberSymbol, checker) { + return getPropertySymbolsFromBaseTypes(memberSymbol.parent, memberSymbol.name, checker, function (_) { return true; }) || false; + } + ts.isMemberSymbolInBaseType = isMemberSymbolInBaseType; + var NodeSet = /** @class */ (function () { + function NodeSet() { + this.map = ts.createMap(); + } + NodeSet.prototype.add = function (node) { + this.map.set(String(ts.getNodeId(node)), node); + }; + NodeSet.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + NodeSet.prototype.some = function (pred) { + return ts.forEachEntry(this.map, pred) || false; + }; + return NodeSet; + }()); + ts.NodeSet = NodeSet; + var NodeMap = /** @class */ (function () { + function NodeMap() { + this.map = ts.createMap(); + } + NodeMap.prototype.get = function (node) { + var res = this.map.get(String(ts.getNodeId(node))); + return res && res.value; + }; + NodeMap.prototype.getOrUpdate = function (node, setValue) { + var res = this.get(node); + if (res) + return res; + var value = setValue(); + this.set(node, value); + return value; + }; + NodeMap.prototype.set = function (node, value) { + this.map.set(String(ts.getNodeId(node)), { node: node, value: value }); + }; + NodeMap.prototype.has = function (node) { + return this.map.has(String(ts.getNodeId(node))); + }; + NodeMap.prototype.forEach = function (cb) { + this.map.forEach(function (_a) { + var node = _a.node, value = _a.value; + return cb(value, node); + }); + }; + return NodeMap; + }()); + ts.NodeMap = NodeMap; + 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; + } + } + ts.getParentNodeInSpan = getParentNodeInSpan; + function spanContainsNode(span, node, file) { + return ts.textSpanContainsPosition(span, node.getStart(file)) && + node.getEnd() <= ts.textSpanEnd(span); + } + function findModifier(node, kind) { + return node.modifiers && ts.find(node.modifiers, function (m) { return m.kind === kind; }); + } + ts.findModifier = findModifier; + /* @internal */ + function insertImport(changes, sourceFile, importDecl) { + var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); + if (lastImportDeclaration) { + changes.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); + } + else { + changes.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); + } + } + ts.insertImport = insertImport; + function textSpansEqual(a, b) { + return !!a && !!b && a.start === b.start && a.length === b.length; + } + ts.textSpansEqual = textSpansEqual; + function documentSpansEqual(a, b) { + return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); + } + ts.documentSpansEqual = documentSpansEqual; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { - return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 148 /* Parameter */; + return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 149 /* Parameter */; } ts.isFirstDeclarationOfSymbolParameter = isFirstDeclarationOfSymbolParameter; var displayPartWriter = getDisplayPartWriter(); function getDisplayPartWriter() { + var absoluteMaximumLength = ts.defaultMaximumTruncationLength * 10; // A hard cutoff to avoid overloading the messaging channel in worst-case scenarios var displayParts; var lineStart; var indent; + var length; resetWriter(); var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { - displayParts: function () { return displayParts; }, + displayParts: function () { + var finalText = displayParts.length && displayParts[displayParts.length - 1].text; + if (length > absoluteMaximumLength && finalText && finalText !== "...") { + if (!ts.isWhiteSpaceLike(finalText.charCodeAt(finalText.length - 1))) { + displayParts.push(displayPart(" ", ts.SymbolDisplayPartKind.space)); + } + displayParts.push(displayPart("...", ts.SymbolDisplayPartKind.punctuation)); + } + return displayParts; + }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, writeOperator: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.operator); }, writePunctuation: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.punctuation); }, @@ -82435,23 +89350,35 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; function writeIndent() { + if (length > absoluteMaximumLength) + return; if (lineStart) { var indentString = ts.getIndentString(indent); if (indentString) { + length += indentString.length; displayParts.push(displayPart(indentString, ts.SymbolDisplayPartKind.space)); } lineStart = false; } } function writeKind(text, kind) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { + if (length > absoluteMaximumLength) + return; writeIndent(); + length += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { + if (length > absoluteMaximumLength) + return; + length += 1; displayParts.push(lineBreakPart()); lineStart = true; } @@ -82459,6 +89386,7 @@ var ts; displayParts = []; lineStart = true; indent = 0; + length = 0; } } function symbolPart(text, symbol) { @@ -82568,18 +89496,21 @@ var ts; } ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { - typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { + if (flags === void 0) { flags = 0 /* None */; } return mapToDisplayParts(function (writer) { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | 8 /* UseAliasDefinedOutsideCurrentScope */, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { + if (flags === void 0) { flags = 0 /* None */; } flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); @@ -82587,8 +89518,8 @@ var ts; } ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { - return location.parent && - (location.parent.kind === 246 /* ImportSpecifier */ || location.parent.kind === 250 /* ExportSpecifier */) && + return !!location.parent && + (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -82615,7 +89546,7 @@ var ts; scriptKinds[_i - 2] = arguments[_i]; } var scriptKind = getScriptKind(fileName, host); - return ts.forEach(scriptKinds, function (k) { return k === scriptKind; }); + return ts.some(scriptKinds, function (k) { return k === scriptKind; }); } ts.scriptKindIs = scriptKindIs; function getScriptKind(fileName, host) { @@ -82641,10 +89572,15 @@ var ts; * WARNING: This is an expensive operation and is only intended to be used in refactorings * and code fixes (because those are triggered by explicit user actions). */ - function getSynthesizedDeepClone(node) { - if (node === undefined) { - return undefined; - } + function getSynthesizedDeepClone(node, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + var clone = node && getSynthesizedDeepCloneWorker(node); + if (clone && !includeTrivia) + suppressLeadingAndTrailingTrivia(clone); + return clone; + } + ts.getSynthesizedDeepClone = getSynthesizedDeepClone; + function getSynthesizedDeepCloneWorker(node) { var visited = ts.visitEachChild(node, getSynthesizedDeepClone, ts.nullTransformationContext); if (visited === node) { // This only happens for leaf nodes - internal nodes always see their children change. @@ -82655,9 +89591,7 @@ var ts; else if (ts.isNumericLiteral(clone_7)) { clone_7.numericLiteralFlags = node.numericLiteralFlags; } - clone_7.pos = node.pos; - clone_7.end = node.end; - return clone_7; + return ts.setTextRange(clone_7, node); } // PERF: As an optimization, rather than calling getSynthesizedClone, we'll update // the new node created by visitEachChild with the extra changes getSynthesizedClone @@ -82665,9 +89599,9 @@ var ts; visited.parent = undefined; return visited; } - ts.getSynthesizedDeepClone = getSynthesizedDeepClone; - function getSynthesizedDeepClones(nodes) { - return nodes && ts.createNodeArray(nodes.map(getSynthesizedDeepClone), nodes.hasTrailingComma); + function getSynthesizedDeepClones(nodes, includeTrivia) { + if (includeTrivia === void 0) { includeTrivia = true; } + return nodes && ts.createNodeArray(nodes.map(function (n) { return getSynthesizedDeepClone(n, includeTrivia); }), nodes.hasTrailingComma); } ts.getSynthesizedDeepClones = getSynthesizedDeepClones; /** @@ -82675,29 +89609,102 @@ var ts; */ /* @internal */ function suppressLeadingAndTrailingTrivia(node) { - ts.Debug.assertDefined(node); - suppress(node, 512 /* NoLeadingComments */, getFirstChild); - suppress(node, 1024 /* NoTrailingComments */, getLastChild); - function suppress(node, flag, getChild) { - ts.addEmitFlags(node, flag); - var child = getChild(node); - if (child) - suppress(child, flag, getChild); - } + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } ts.suppressLeadingAndTrailingTrivia = suppressLeadingAndTrailingTrivia; + /** + * Sets EmitFlags to suppress leading trivia on the node. + */ + /* @internal */ + function suppressLeadingTrivia(node) { + addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); + } + ts.suppressLeadingTrivia = suppressLeadingTrivia; + /** + * Sets EmitFlags to suppress trailing trivia on the node. + */ + /* @internal */ + function suppressTrailingTrivia(node) { + addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); + } + ts.suppressTrailingTrivia = suppressTrailingTrivia; + function addEmitFlagsRecursively(node, flag, getChild) { + ts.addEmitFlags(node, flag); + var child = getChild(node); + if (child) + addEmitFlagsRecursively(child, flag, getChild); + } function getFirstChild(node) { return node.forEachChild(function (child) { return child; }); } - function getLastChild(node) { - var lastChild; - node.forEachChild(function (child) { lastChild = child; }, function (children) { - // As an optimization, jump straight to the end of the list. - if (children.length) { - lastChild = ts.last(children); + /* @internal */ + function getUniqueName(baseName, sourceFile) { + var nameText = baseName; + for (var i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { + nameText = baseName + "_" + i; + } + return nameText; + } + ts.getUniqueName = getUniqueName; + /** + * @return The index of the (only) reference to the extracted symbol. We want the cursor + * to be on the reference, rather than the declaration, because it's closer to where the + * user was before extracting it. + */ + /* @internal */ + function getRenameLocation(edits, renameFilename, name, preferLastLocation) { + var delta = 0; + var lastPos = -1; + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; + ts.Debug.assert(fileName === renameFilename); + for (var _b = 0, textChanges_1 = textChanges_2; _b < textChanges_1.length; _b++) { + var change = textChanges_1[_b]; + var span = change.span, newText = change.newText; + var index = indexInTextChange(newText, name); + if (index !== -1) { + lastPos = span.start + delta + index; + // If the reference comes first, return immediately. + if (!preferLastLocation) { + return lastPos; + } + } + delta += newText.length - span.length; } + } + // If the declaration comes first, return the position of the last occurrence. + ts.Debug.assert(preferLastLocation); + ts.Debug.assert(lastPos >= 0); + return lastPos; + } + ts.getRenameLocation = getRenameLocation; + function copyComments(sourceNode, targetNode, sourceFile, commentKind, hasTrailingNewLine) { + 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, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); }); - return lastChild; + } + ts.copyComments = copyComments; + function indexInTextChange(change, name) { + if (ts.startsWith(change, name)) + return 0; + // Add a " " to avoid references inside words + var idx = change.indexOf(" " + name); + if (idx === -1) + idx = change.indexOf("." + name); + if (idx === -1) + idx = change.indexOf('"' + name); + return idx === -1 ? -1 : idx + 1; } })(ts || (ts = {})); var ts; @@ -82941,7 +89948,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_5 = dense[i + 1]; + var length_6 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -82950,8 +89957,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_5, classification: convertClassification(type) }); - lastEnd = start + length_5; + entries.push({ length: length_6, classification: convertClassification(type) }); + lastEnd = start + length_6; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -82978,6 +89985,8 @@ var ts; case 9 /* text */: case 17 /* parameterName */: return ts.TokenClass.Identifier; + default: + return undefined; // TODO: GH#18217 Debug.assertNever(type); } } /** Returns true if 'keyword2' can legally follow 'keyword1' in any language construct. */ @@ -83128,10 +90137,10 @@ var ts; // That means we're calling back into the host around every 1.2k of the file we process. // Lib.d.ts has similar numbers. switch (kind) { - case 237 /* ModuleDeclaration */: - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: + case 242 /* ModuleDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: cancellationToken.throwIfCancellationRequested(); } } @@ -83225,6 +90234,7 @@ var ts; case 22 /* jsxAttribute */: return "jsx attribute" /* jsxAttribute */; case 23 /* jsxText */: return "jsx text" /* jsxText */; case 24 /* jsxAttributeStringLiteralValue */: return "jsx attribute string literal value" /* jsxAttributeStringLiteralValue */; + default: return undefined; // TODO: GH#18217 throw Debug.assertNever(type); } } function convertClassificationsToSpans(classifications) { @@ -83342,20 +90352,22 @@ var ts; pushClassification(tag.tagName.pos, tag.tagName.end - tag.tagName.pos, 18 /* docCommentTagName */); // e.g. "param" pos = tag.tagName.end; switch (tag.kind) { - case 287 /* JSDocParameterTag */: + case 296 /* JSDocParameterTag */: processJSDocParameterTag(tag); break; - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: processJSDocTemplateTag(tag); + pos = tag.end; break; - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: processElement(tag.typeExpression); + pos = tag.end; break; - case 288 /* JSDocReturnTag */: + case 297 /* JSDocReturnTag */: processElement(tag.typeExpression); + pos = tag.end; break; } - pos = tag.end; } } if (pos !== docComment.end) { @@ -83438,22 +90450,22 @@ var ts; } function tryClassifyJsxElementName(token) { switch (token.parent && token.parent.kind) { - case 255 /* JsxOpeningElement */: + case 260 /* JsxOpeningElement */: if (token.parent.tagName === token) { return 19 /* jsxOpenTagName */; } break; - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (token.parent.tagName === token) { return 20 /* jsxCloseTagName */; } break; - case 254 /* JsxSelfClosingElement */: + case 259 /* JsxSelfClosingElement */: if (token.parent.tagName === token) { return 21 /* jsxSelfClosingTagName */; } break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: if (token.parent.name === token) { return 22 /* jsxAttribute */; } @@ -83479,19 +90491,20 @@ var ts; } if (ts.isPunctuation(tokenKind)) { if (token) { + var parent = token.parent; if (tokenKind === 58 /* EqualsToken */) { // the '=' in a variable declaration is special cased here. - if (token.parent.kind === 230 /* VariableDeclaration */ || - token.parent.kind === 151 /* PropertyDeclaration */ || - token.parent.kind === 148 /* Parameter */ || - token.parent.kind === 260 /* JsxAttribute */) { + if (parent.kind === 235 /* VariableDeclaration */ || + parent.kind === 152 /* PropertyDeclaration */ || + parent.kind === 149 /* Parameter */ || + parent.kind === 265 /* JsxAttribute */) { return 5 /* operator */; } } - if (token.parent.kind === 198 /* BinaryExpression */ || - token.parent.kind === 196 /* PrefixUnaryExpression */ || - token.parent.kind === 197 /* PostfixUnaryExpression */ || - token.parent.kind === 199 /* ConditionalExpression */) { + if (parent.kind === 202 /* BinaryExpression */ || + parent.kind === 200 /* PrefixUnaryExpression */ || + parent.kind === 201 /* PostfixUnaryExpression */ || + parent.kind === 203 /* ConditionalExpression */) { return 5 /* operator */; } } @@ -83501,7 +90514,8 @@ var ts; return 4 /* numericLiteral */; } else if (tokenKind === 9 /* StringLiteral */) { - return token.parent.kind === 260 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + // TODO: GH#18217 + return token.parent.kind === 265 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 12 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -83517,32 +90531,32 @@ var ts; else if (tokenKind === 71 /* Identifier */) { if (token) { switch (token.parent.kind) { - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: if (token.parent.name === token) { return 11 /* className */; } return; - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: if (token.parent.name === token) { return 15 /* typeParameterName */; } return; - case 234 /* InterfaceDeclaration */: + case 239 /* InterfaceDeclaration */: if (token.parent.name === token) { return 13 /* interfaceName */; } return; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: if (token.parent.name === token) { return 12 /* enumName */; } return; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (token.parent.name === token) { return 14 /* moduleName */; } return; - case 148 /* Parameter */: + case 149 /* Parameter */: if (token.parent.name === token) { return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } @@ -83578,29 +90592,43 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function createPathCompletion(name, kind, span) { - return { name: name, kind: kind, span: span }; + function nameAndKind(name, kind) { + return { name: name, kind: kind }; + } + function addReplacementSpans(text, textStart, names) { + var span = getDirectoryFragmentTextSpan(text, textStart); + return names.map(function (_a) { + var name = _a.name, kind = _a.kind; + return ({ name: name, kind: kind, span: span }); + }); } function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { + return addReplacementSpans(node.text, node.getStart(sourceFile) + 1, getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker)); + } + PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); - var scriptPath = node.getSourceFile().path; + var scriptPath = sourceFile.path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { - var extensions = ts.getSupportedExtensions(compilerOptions); + var extensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (compilerOptions.rootDirs) { - return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, compilerOptions, host, scriptPath); + return getCompletionEntriesForDirectoryFragmentWithRootDirs(compilerOptions.rootDirs, literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, compilerOptions, host, scriptPath); } else { - return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, span, host, scriptPath); + return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensions, /*includeExtensions*/ false, host, scriptPath); } } else { - // Check for node modules - return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span, compilerOptions, host, typeChecker); + return getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker); } } - PathCompletions.getStringLiteralCompletionsFromModuleNames = getStringLiteralCompletionsFromModuleNames; + function getSupportedExtensionsForModuleResolution(compilerOptions) { + var extensions = ts.getSupportedExtensions(compilerOptions); + return compilerOptions.resolveJsonModule && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs ? + extensions.concat(".json" /* Json */) : + extensions; + } /** * Takes a script path and returns paths for all potential folders that could be merged with its * containing folder via the "rootDirs" compiler option @@ -83611,25 +90639,25 @@ var ts; // Determine the path to the directory containing the script relative to the root directory it is contained within var relativeDirectory = ts.firstDefined(rootDirs, function (rootDirectory) { return ts.containsPath(rootDirectory, scriptPath, basePath, ignoreCase) ? scriptPath.substr(rootDirectory.length) : undefined; - }); + }); // TODO: GH#18217 // Now find a path for each potential directory that is to be merged with the one containing the script return ts.deduplicate(rootDirs.map(function (rootDirectory) { return ts.combinePaths(rootDirectory, relativeDirectory); }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, span, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { var basePath = compilerOptions.project || host.getCurrentDirectory(); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); var baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptPath, ignoreCase); var result = []; for (var _i = 0, baseDirectories_1 = baseDirectories; _i < baseDirectories_1.length; _i++) { var baseDirectory = baseDirectories_1[_i]; - getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, span, host, exclude, result); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensions, includeExtensions, host, exclude, result); } return result; } /** * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. */ - function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, host, exclude, result) { + function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, host, exclude, result) { if (result === void 0) { result = []; } if (fragment === undefined) { fragment = ""; @@ -83639,13 +90667,16 @@ var ts; * Remove the basename from the path. Note that we don't use the basename to filter completions; * the client is responsible for refining completions. */ - fragment = ts.getDirectoryPath(fragment); + if (!ts.hasTrailingDirectorySeparator(fragment)) { + fragment = ts.getDirectoryPath(fragment); + } if (fragment === "") { fragment = "." + ts.directorySeparator; } fragment = ts.ensureTrailingDirectorySeparator(fragment); - var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); - var baseDirectory = ts.getDirectoryPath(absolutePath); + // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths + var absolutePath = ts.resolvePath(scriptPath, fragment); + var baseDirectory = ts.hasTrailingDirectorySeparator(absolutePath) ? absolutePath : ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { // Enumerate the available files if possible @@ -83658,19 +90689,19 @@ var ts; * both foo.ts and foo.tsx become foo */ var foundFiles = ts.createMap(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var filePath = files_2[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var filePath = files_3[_i]; filePath = ts.normalizePath(filePath); if (exclude && ts.comparePaths(filePath, exclude, scriptPath, ignoreCase) === 0 /* EqualTo */) { continue; } - var foundFileName = includeExtensions ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); + var foundFileName = includeExtensions || ts.fileExtensionIs(filePath, ".json" /* Json */) ? ts.getBaseFileName(filePath) : ts.removeFileExtension(ts.getBaseFileName(filePath)); if (!foundFiles.has(foundFileName)) { foundFiles.set(foundFileName, true); } } ts.forEachKey(foundFiles, function (foundFile) { - result.push(createPathCompletion(foundFile, "script" /* scriptElement */, span)); + result.push(nameAndKind(foundFile, "script" /* scriptElement */)); }); } // If possible, get folder completion as well @@ -83679,7 +90710,9 @@ var ts; for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { var directory = directories_1[_a]; var directoryName = ts.getBaseFileName(ts.normalizePath(directory)); - result.push(createPathCompletion(directoryName, "directory" /* directory */, span)); + if (directoryName !== "@types") { + result.push(nameAndKind(directoryName, "directory" /* directory */)); + } } } } @@ -83692,56 +90725,76 @@ var ts; * Modules from node_modules (i.e. those listed in package.json) * This includes all files that are found in node_modules/moduleName/ with acceptable file extensions */ - function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, span, compilerOptions, host, typeChecker) { + function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, compilerOptions, host, typeChecker) { var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths; var result = []; - var fileExtensions = ts.getSupportedExtensions(compilerOptions); + var fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); + getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); for (var path in paths) { var patterns = paths[path]; if (paths.hasOwnProperty(path) && patterns) { - var _loop_7 = function (name, kind) { + var _loop_13 = function (name, kind) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { - result.push(createPathCompletion(name, kind, span)); + result.push(nameAndKind(name, kind)); } }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind; - _loop_7(name, kind); + _loop_13(name, kind); } } } } - if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { - ts.forEachAncestorDirectory(scriptPath, function (ancestor) { - var nodeModules = ts.combinePaths(ancestor, "node_modules"); - if (host.directoryExists(nodeModules)) { - getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - } - }); + var fragmentDirectory = containsSlash(fragment) ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; + for (var _c = 0, _d = getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker); _c < _d.length; _c++) { + var ambientName = _d[_c]; + result.push(nameAndKind(ambientName, "external module name" /* externalModuleName */)); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _c = 0, _d = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _c < _d.length; _c++) { - var moduleName = _d[_c]; - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, result); + if (ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs) { + // If looking for a global package name, don't just include everything in `node_modules` because that includes dependencies' own dependencies. + // (But do if we didn't find anything, e.g. 'package.json' missing.) + var foundGlobal = false; + if (fragmentDirectory === undefined) { + var _loop_14 = function (moduleName) { + if (!result.some(function (entry) { return entry.name === moduleName; })) { + foundGlobal = true; + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); + } + }; + for (var _e = 0, _f = enumerateNodeModulesVisibleToScript(host, scriptPath); _e < _f.length; _e++) { + var moduleName = _f[_e]; + _loop_14(moduleName); + } + } + if (!foundGlobal) { + ts.forEachAncestorDirectory(scriptPath, function (ancestor) { + var nodeModules = ts.combinePaths(ancestor, "node_modules"); + if (tryDirectoryExists(host, nodeModules)) { + getCompletionEntriesForDirectoryFragment(fragment, nodeModules, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + } + }); + } } return result; } function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { if (!ts.endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [{ name: path, kind: "directory" /* directory */ }] : ts.emptyArray; + return !ts.stringContains(path, "*") ? justPathMappingName(path) : ts.emptyArray; } var pathPrefix = path.slice(0, path.length - 1); - if (!ts.startsWith(fragment, pathPrefix)) { - return [{ name: pathPrefix, kind: "directory" /* directory */ }]; + var remainingFragment = ts.tryRemovePrefix(fragment, pathPrefix); + return remainingFragment === undefined ? justPathMappingName(pathPrefix) : ts.flatMap(patterns, function (pattern) { + return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); + }); + function justPathMappingName(name) { + return ts.startsWith(name, fragment) ? [{ name: name, kind: "directory" /* directory */ }] : ts.emptyArray; } - var remainingFragment = fragment.slice(pathPrefix.length); - return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); } function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { if (!host.readDirectory) { @@ -83753,12 +90806,13 @@ var ts; } // The prefix has two effective parts: the directory path and the base component after the filepath that is not a // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + var normalizedPrefix = ts.resolvePath(parsed.prefix); + var normalizedPrefixDirectory = ts.hasTrailingDirectorySeparator(parsed.prefix) ? normalizedPrefix : ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.hasTrailingDirectorySeparator(parsed.prefix) ? "" : ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = containsSlash(fragment); + var fragmentDirectory = fragmentHasPath ? ts.hasTrailingDirectorySeparator(fragment) ? fragment : ts.getDirectoryPath(fragment) : undefined; // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; var normalizedSuffix = ts.normalizePath(parsed.suffix); // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); @@ -83783,45 +90837,21 @@ var ts; function removeLeadingDirectorySeparator(path) { return path[0] === ts.directorySeparator ? path.slice(1) : path; } - function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { - // Check If this is a nested module - var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); - var moduleNameFragment = isNestedModule ? fragment.substr(0, fragment.lastIndexOf(ts.directorySeparator)) : undefined; + function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { // Get modules that the type checker picked up - var ambientModules = ts.map(typeChecker.getAmbientModules(), function (sym) { return ts.stripQuotes(sym.name); }); - var nonRelativeModuleNames = ts.filter(ambientModules, function (moduleName) { return ts.startsWith(moduleName, fragment); }); + var ambientModules = checker.getAmbientModules().map(function (sym) { return ts.stripQuotes(sym.name); }); + var nonRelativeModuleNames = ambientModules.filter(function (moduleName) { return ts.startsWith(moduleName, fragment); }); // Nested modules of the form "module-name/sub" need to be adjusted to only return the string // after the last '/' that appears in the fragment because that's where the replacement span // starts - if (isNestedModule) { - var moduleNameWithSeperator_1 = ts.ensureTrailingDirectorySeparator(moduleNameFragment); - nonRelativeModuleNames = ts.map(nonRelativeModuleNames, function (nonRelativeModuleName) { - return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeperator_1); - }); + if (fragmentDirectory !== undefined) { + var moduleNameWithSeparator_1 = ts.ensureTrailingDirectorySeparator(fragmentDirectory); + return nonRelativeModuleNames.map(function (nonRelativeModuleName) { return ts.removePrefix(nonRelativeModuleName, moduleNameWithSeparator_1); }); } - if (!options.moduleResolution || options.moduleResolution === ts.ModuleResolutionKind.NodeJs) { - for (var _i = 0, _a = enumerateNodeModulesVisibleToScript(host, scriptPath); _i < _a.length; _i++) { - var visibleModule = _a[_i]; - if (!isNestedModule) { - nonRelativeModuleNames.push(visibleModule.moduleName); - } - else if (ts.startsWith(visibleModule.moduleName, moduleNameFragment)) { - var nestedFiles = tryReadDirectory(host, visibleModule.moduleDir, ts.supportedTypeScriptExtensions, /*exclude*/ undefined, /*include*/ ["./*"]); - if (nestedFiles) { - for (var _b = 0, nestedFiles_1 = nestedFiles; _b < nestedFiles_1.length; _b++) { - var f = nestedFiles_1[_b]; - f = ts.normalizePath(f); - var nestedModule = ts.removeFileExtension(ts.getBaseFileName(f)); - nonRelativeModuleNames.push(nestedModule); - } - } - } - } - } - return ts.deduplicate(nonRelativeModuleNames, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); + return nonRelativeModuleNames; } function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { - var token = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, position); var commentRanges = ts.getLeadingCommentRanges(sourceFile.text, token.pos); var range = commentRanges && ts.find(commentRanges, function (commentRange) { return position >= commentRange.pos && position <= commentRange.end; }); if (!range) { @@ -83834,23 +90864,13 @@ var ts; } var prefix = match[1], kind = match[2], toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - switch (kind) { - case "path": { - // Give completions for a relative path - var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - return getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, host, sourceFile.path); - } - case "types": { - // Give completions based on the typings available - var span_11 = ts.createTextSpan(range.pos + prefix.length, match[0].length - prefix.length); - return getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); - } - default: - return undefined; - } + var names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, host, sourceFile.path) + : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath) + : undefined; + return names && addReplacementSpans(toComplete, range.pos + prefix.length, names); } PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; - function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { + function getCompletionEntriesFromTypings(host, options, scriptPath, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options var seen = ts.createMap(); @@ -83898,7 +90918,7 @@ var ts; } function pushResult(moduleName) { if (!seen.has(moduleName)) { - result.push(createPathCompletion(moduleName, "external module name" /* externalModuleName */, span)); + result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */)); seen.set(moduleName, true); } } @@ -83915,43 +90935,18 @@ var ts; return paths; } function enumerateNodeModulesVisibleToScript(host, scriptPath) { + if (!host.readFile || !host.fileExists) + return ts.emptyArray; var result = []; - if (host.readFile && host.fileExists) { - for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { - var packageJson = _a[_i]; - var contents = tryReadingPackageJson(packageJson); - if (!contents) { - return; - } - var nodeModulesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules"); - var foundModuleNames = []; - // Provide completions for all non @types dependencies - for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { - var key = nodeModulesDependencyKeys_1[_b]; - addPotentialPackageNames(contents[key], foundModuleNames); - } - for (var _c = 0, foundModuleNames_1 = foundModuleNames; _c < foundModuleNames_1.length; _c++) { - var moduleName = foundModuleNames_1[_c]; - var moduleDir = ts.combinePaths(nodeModulesDir, moduleName); - result.push({ - moduleName: moduleName, - moduleDir: moduleDir - }); - } - } - } - return result; - function tryReadingPackageJson(filePath) { - try { - var fileText = tryReadFile(host, filePath); - return fileText ? JSON.parse(fileText) : undefined; - } - catch (e) { - return undefined; - } - } - function addPotentialPackageNames(dependencies, result) { - if (dependencies) { + for (var _i = 0, _a = findPackageJsons(scriptPath, host); _i < _a.length; _i++) { + var packageJson = _a[_i]; + var contents = ts.readJson(packageJson, host); // Cast to assert that readFile is defined + // Provide completions for all non @types dependencies + for (var _b = 0, nodeModulesDependencyKeys_1 = nodeModulesDependencyKeys; _b < nodeModulesDependencyKeys_1.length; _b++) { + var key = nodeModulesDependencyKeys_1[_b]; + var dependencies = contents[key]; + if (!dependencies) + continue; for (var dep in dependencies) { if (dependencies.hasOwnProperty(dep) && !ts.startsWith(dep, "@types/")) { result.push(dep); @@ -83959,12 +90954,15 @@ var ts; } } } + return result; } - // Replace everything after the last directory seperator that appears + // Replace everything after the last directory separator that appears function getDirectoryFragmentTextSpan(text, textStart) { - var index = text.lastIndexOf(ts.directorySeparator); + var index = Math.max(text.lastIndexOf(ts.directorySeparator), text.lastIndexOf("\\")); var offset = index !== -1 ? index + 1 : 0; - return { start: textStart + offset, length: text.length - offset }; + // If the range is an identifier, span is unnecessary. + var length = text.length - offset; + return length === 0 || ts.isIdentifierText(text.substr(offset, length), 6 /* ESNext */) ? undefined : ts.createTextSpan(textStart + offset, length); } // Returns true if the path is explicitly relative to the script (i.e. relative to . or ..) function isPathRelativeToScript(path) { @@ -83975,15 +90973,6 @@ var ts; } return false; } - function normalizeAndPreserveTrailingSlash(path) { - if (ts.normalizeSlashes(path) === "./") { - // normalizePath turns "./" into "". "" + "/" would then be a rooted path instead of a relative one, so avoid this particular case. - // There is no problem for adding "/" to a non-empty string -- it's only a problem at the beginning. - return ""; - } - var norm = ts.normalizePath(path); - return ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(norm) : norm; - } /** * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment @@ -84004,9 +90993,6 @@ var ts; function tryReadDirectory(host, path, extensions, exclude, include) { return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray; } - function tryReadFile(host, path) { - return tryIOAndConsumeErrors(host, host.readFile, path); - } function tryFileExists(host, path) { return tryIOAndConsumeErrors(host, host.fileExists, path); } @@ -84015,7 +91001,7 @@ var ts; return ts.directoryProbablyExists(path, host); } catch ( /*ignore*/_a) { /*ignore*/ } - return undefined; + return false; } function tryIOAndConsumeErrors(host, toApply) { var args = []; @@ -84028,45 +91014,71 @@ var ts; catch ( /*ignore*/_a) { /*ignore*/ } return undefined; } + function containsSlash(fragment) { + return ts.stringContains(fragment, ts.directorySeparator); + } })(PathCompletions = Completions.PathCompletions || (Completions.PathCompletions = {})); })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var Completions; (function (Completions) { + var SymbolOriginInfoKind; + (function (SymbolOriginInfoKind) { + SymbolOriginInfoKind[SymbolOriginInfoKind["ThisType"] = 0] = "ThisType"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 1] = "SymbolMemberNoExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 2] = "SymbolMemberExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["Export"] = 3] = "Export"; + })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); + function originIsSymbolMember(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 1 /* SymbolMemberNoExport */; + } + function originIsExport(origin) { + return origin.kind === 2 /* SymbolMemberExport */ || origin.kind === 3 /* Export */; + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; - KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 4] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["InterfaceElementKeywords"] = 2] = "InterfaceElementKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 3] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 4] = "FunctionLikeBodyKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 5] = "TypeKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); - function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { + var GlobalsSearch; + (function (GlobalsSearch) { + GlobalsSearch[GlobalsSearch["Continue"] = 0] = "Continue"; + GlobalsSearch[GlobalsSearch["Success"] = 1] = "Success"; + GlobalsSearch[GlobalsSearch["Fail"] = 2] = "Fail"; + })(GlobalsSearch || (GlobalsSearch = {})); + function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter) { + var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && convertPathCompletions(entries); } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (triggerCharacter && !isValidTrigger(sourceFile, triggerCharacter, contextToken, position)) + return undefined; // TODO: GH#18217 if (ts.isInString(sourceFile, position, contextToken)) { return !contextToken || !ts.isStringLiteralLike(contextToken) ? undefined - : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log); + : convertStringLiteralCompletions(getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host), sourceFile, typeChecker, log, preferences); } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); } - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, compilerOptions.target); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, preferences, /*detailsEntryId*/ undefined); if (!completionData) { return undefined; } switch (completionData.kind) { case 0 /* Data */: - return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences); case 1 /* JsDocTagName */: // If the current position is a jsDoc tag name, only tag names should be provided for completion return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); @@ -84080,7 +91092,7 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; - function convertStringLiteralCompletions(completion, sourceFile, checker, log) { + function convertStringLiteralCompletions(completion, sourceFile, checker, log, preferences) { if (completion === undefined) { return undefined; } @@ -84089,12 +91101,12 @@ var ts; return convertPathCompletions(completion.paths); case 1 /* Properties */: { var entries = []; - getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */); // Target will not be used, so arbitrary - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + getCompletionEntriesFromSymbols(completion.symbols, entries, sourceFile, sourceFile, checker, 6 /* ESNext */, log, 4 /* String */, preferences); // Target will not be used, so arbitrary + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, entries: entries }; } case 2 /* Types */: { - var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "var" /* variableElement */, sortText: "0" }); }); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + var entries = completion.types.map(function (type) { return ({ name: type.value, kindModifiers: "" /* none */, kind: "string" /* string */, sortText: "0" }); }); + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, entries: entries }; } default: return ts.Debug.assertNever(completion); @@ -84112,33 +91124,35 @@ var ts; function jsdocCompletionInfo(entries) { return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } - function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; - if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
- // The completion list at "1" will contain "div" with type any + // var x =
" with type any + // And at `
` (with a closing `>`), the completion list will contain "div". var tagName = location.parent.parent.openingElement.tagName; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, - entries: [{ - name: tagName.getFullText(), - kind: "class" /* classElement */, - kindModifiers: undefined, - sortText: "0", - }] }; + var hasClosingAngleBracket = !!ts.findChildOfKind(location.parent, 29 /* GreaterThanToken */, sourceFile); + var entry = { + name: tagName.getFullText(sourceFile) + (hasClosingAngleBracket ? "" : ">"), + kind: "class" /* classElement */, + kindModifiers: undefined, + sortText: "0", + }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [entry] }; } var entries = []; - if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); + if (isUncheckedFile(sourceFile, compilerOptions)) { + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if @@ -84148,8 +91162,15 @@ var ts; if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } + for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) { + var literal = literals_1[_i]; + entries.push(createCompletionEntryForLiteral(literal)); + } return { isGlobalCompletion: isInSnippetScope, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; } + function isUncheckedFile(sourceFile, compilerOptions) { + return ts.isSourceFileJavaScript(sourceFile) && !ts.isCheckJsEnabledForFile(sourceFile, compilerOptions); + } function isMemberCompletionKind(kind) { switch (kind) { case 0 /* ObjectPropertyDeclaration */: @@ -84177,7 +91198,11 @@ var ts; } }); } - function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions) { + var completionNameForLiteral = JSON.stringify; + function createCompletionEntryForLiteral(literal) { + return { name: completionNameForLiteral(literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: "0" }; + } + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences) { var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); if (!info) { return undefined; @@ -84185,27 +91210,27 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var insertText; var replacementSpan; - if (includeInsertTextCompletions) { - if (origin && origin.type === "this-type") { - insertText = needsConvertPropertyAccess ? "this[" + quote(name) + "]" : "this." + name; - } - else if (needsConvertPropertyAccess) { - insertText = "[" + quote(name) + "]"; - var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); - // If the text after the '.' starts with this name, write over it. Else, add new text. - var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; - replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); - } - if (isJsxInitializer) { - if (insertText === undefined) - insertText = name; - insertText = "{" + insertText + "}"; - if (typeof isJsxInitializer !== "boolean") { - replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); - } + if (origin && origin.kind === 0 /* ThisType */) { + insertText = needsConvertPropertyAccess ? "this[" + quote(name, preferences) + "]" : "this." + name; + } + // We should only have needsConvertPropertyAccess if there's a property access to convert. But see #21790. + // Somehow there was a global with a non-identifier name. Hopefully someone will complain about getting a "foo bar" global completion and provide a repro. + else if ((origin && originIsSymbolMember(origin) || needsConvertPropertyAccess) && propertyAccessToConvert) { + insertText = needsConvertPropertyAccess ? "[" + quote(name, preferences) + "]" : "[" + name + "]"; + var dot = ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile); + // If the text after the '.' starts with this name, write over it. Else, add new text. + var end = ts.startsWith(name, propertyAccessToConvert.name.text) ? propertyAccessToConvert.name.end : dot.end; + replacementSpan = ts.createTextSpanFromBounds(dot.getStart(sourceFile), end); + } + if (isJsxInitializer) { + if (insertText === undefined) + insertText = name; + insertText = "{" + insertText + "}"; + if (typeof isJsxInitializer !== "boolean") { + replacementSpan = ts.createTextSpanFromNode(isJsxInitializer, sourceFile); } } - if (insertText !== undefined && !includeInsertTextCompletions) { + if (insertText !== undefined && !preferences.includeCompletionsWithInsertText) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -84221,15 +91246,23 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(!!origin && origin.type === "export"), + hasAction: trueOrUndefined(!!origin && originIsExport(origin)), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), insertText: insertText, replacementSpan: replacementSpan, }; } - function quote(text) { - // TODO: GH#20619 Use configured quote style - return JSON.stringify(text); + function quote(text, preferences) { + var quoted = JSON.stringify(text); + switch (preferences.quotePreference) { + case undefined: + case "double": + return quoted; + case "single": + return "'" + ts.stripQuotes(quoted).replace("'", "\\'").replace('\\"', '"') + "'"; + default: + return ts.Debug.assertNever(preferences.quotePreference); + } } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { return localSymbol === recommendedCompletion || @@ -84239,19 +91272,19 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; + return origin && originIsExport(origin) ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } - function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. // Based on the order we add things we will always see locals first, then globals, then module exports. // So adding a completion for a local will prevent us from adding completions for external module exports sharing the same name. var uniques = ts.createMap(); - for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { - var symbol = symbols_4[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, includeInsertTextCompletions); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, preferences); if (!entry) { continue; } @@ -84260,7 +91293,7 @@ var ts; continue; } // Latter case tests whether this is a global variable. - if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { + if (!origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); }))) { // TODO: GH#18217 uniques.set(name, true); } entries.push(entry); @@ -84306,22 +91339,24 @@ var ts; })(StringLiteralCompletionKind || (StringLiteralCompletionKind = {})); function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host) { switch (node.parent.kind) { - case 177 /* LiteralType */: + case 180 /* LiteralType */: switch (node.parent.parent.kind) { - case 161 /* TypeReference */: - return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent), typeChecker) }; - case 175 /* IndexedAccessType */: + case 162 /* TypeReference */: + return { kind: 2 /* Types */, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent)), isNewIdentifier: false }; + case 178 /* IndexedAccessType */: // Get all apparent property names // i.e. interface Foo { // foo: string; // bar: string; // } // let x: Foo["/*completion position*/"] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeFromTypeNode(node.parent.parent.objectType).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode(node.parent.parent.objectType)); + case 181 /* ImportType */: + return { kind: 0 /* Paths */, paths: Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; default: return undefined; } - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: if (ts.isObjectLiteralExpression(node.parent.parent) && node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { @@ -84335,11 +91370,10 @@ var ts; // foo({ // '/*completion position*/' // }); - var type = typeChecker.getContextualType(node.parent.parent); - return { kind: 1 /* Properties */, symbols: type && type.getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); } return fromContextualType(); - case 184 /* ElementAccessExpression */: { + case 188 /* ElementAccessExpression */: { var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; if (node === argumentExpression) { // Get all names of properties on the expression @@ -84348,29 +91382,23 @@ var ts; // } // let a: A; // a['/*completion position*/'] - return { kind: 1 /* Properties */, symbols: typeChecker.getTypeAtLocation(expression).getApparentProperties() }; + return stringLiteralCompletionsFromProperties(typeChecker.getTypeAtLocation(expression)); } return undefined; } - case 185 /* CallExpression */: - case 186 /* NewExpression */: - if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { - var argumentInfo_1 = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + case 189 /* CallExpression */: + case 190 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); // f("/*completion position*/") - if (argumentInfo_1) { - var candidates = []; - typeChecker.getResolvedSignature(argumentInfo_1.invocation, candidates, argumentInfo_1.argumentCount); - var uniques_1 = ts.createMap(); - return { kind: 2 /* Types */, types: ts.flatMap(candidates, function (candidate) { return getStringLiteralTypes(typeChecker.getParameterType(candidate, argumentInfo_1.argumentIndex), typeChecker, uniques_1); }) }; - } - return fromContextualType(); + return argumentInfo ? getStringLiteralCompletionsFromSignature(argumentInfo, typeChecker) : fromContextualType(); } // falls through (is `require("")` or `import("")`) - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - case 252 /* ExternalModuleReference */: + case 247 /* ImportDeclaration */: + case 253 /* ExportDeclaration */: + case 257 /* ExternalModuleReference */: // Get all known external module names or complete a path to a module // i.e. import * as ns from "/*completion position*/"; // var y = import("/*completion position*/"); @@ -84384,30 +91412,50 @@ var ts; function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" - return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker), typeChecker) }; + return { kind: 2 /* Types */, types: getStringLiteralTypes(getContextualTypeFromParent(node, typeChecker)), isNewIdentifier: false }; } } - function getStringLiteralTypes(type, typeChecker, uniques) { + function getStringLiteralCompletionsFromSignature(argumentInfo, checker) { + var isNewIdentifier = false; + var uniques = ts.createMap(); + var candidates = []; + checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); + var types = ts.flatMap(candidates, function (candidate) { + if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + return; + var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); + return getStringLiteralTypes(type, uniques); + }); + return { kind: 2 /* Types */, types: types, isNewIdentifier: isNewIdentifier }; + } + function stringLiteralCompletionsFromProperties(type) { + return type && { kind: 1 /* Properties */, symbols: type.getApparentProperties(), hasIndexSignature: hasIndexSignature(type) }; + } + function getStringLiteralTypes(type, uniques) { if (uniques === void 0) { uniques = ts.createMap(); } - if (type && type.flags & 32768 /* TypeParameter */) { - type = type.getConstraint(); - } - return type && type.flags & 131072 /* Union */ - ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, typeChecker, uniques); }) - : type && type.flags & 32 /* StringLiteral */ && !(type.flags & 256 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) + if (!type) + return ts.emptyArray; + type = ts.skipConstraint(type); + return type.isUnion() + ? ts.flatMap(type.types, function (t) { return getStringLiteralTypes(t, uniques); }) + : type.isStringLiteral() && !(type.flags & 512 /* EnumLiteral */) && ts.addToSeen(uniques, type.value) ? [type] : ts.emptyArray; } - function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { - var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); + function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId) { + var compilerOptions = program.getCompilerOptions(); + var completionData = getCompletionData(program, log, sourceFile, isUncheckedFile(sourceFile, compilerOptions), position, { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }, entryId); if (!completionData) { return { type: "none" }; } if (completionData.kind !== 0 /* Data */) { return { type: "request", request: completionData }; } - var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, literals = completionData.literals, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken, isJsxInitializer = completionData.isJsxInitializer; + var literal = ts.find(literals, function (l) { return completionNameForLiteral(l) === entryId.name; }); + if (literal !== undefined) + return { type: "literal", literal: literal }; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new @@ -84415,21 +91463,31 @@ var ts; return ts.firstDefined(symbols, function (symbol) { var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); - return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } : undefined; + return info && info.name === entryId.name && getSourceFromOrigin(origin) === entryId.source + ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken, isJsxInitializer: isJsxInitializer } + : undefined; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; } - function getCompletionEntryDetails(program, log, compilerOptions, sourceFile, position, entryId, allSourceFiles, host, formatContext, getCanonicalFileName) { + function getCompletionEntryDetails(program, log, sourceFile, position, entryId, host, formatContext, preferences, cancellationToken) { var typeChecker = program.getTypeChecker(); + var compilerOptions = program.getCompilerOptions(); var name = entryId.name; + var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + var stringLiteralCompletions = !contextToken || !ts.isStringLiteralLike(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host); + return stringLiteralCompletions && stringLiteralCompletionDetails(name, contextToken, stringLiteralCompletions, sourceFile, typeChecker, cancellationToken); // TODO: GH#18217 + } // Compute all the completion symbols again. - var symbolCompletion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + var symbolCompletion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); switch (symbolCompletion.type) { case "request": { var request = symbolCompletion.request; @@ -84446,44 +91504,61 @@ var ts; } case "symbol": { var symbol = symbolCompletion.symbol, location = symbolCompletion.location, symbolToOriginInfoMap = symbolCompletion.symbolToOriginInfoMap, previousToken = symbolCompletion.previousToken; - var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; - var kindModifiers = ts.SymbolDisplay.getSymbolModifiers(symbol); - var _b = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, 7 /* All */), displayParts = _b.displayParts, documentation = _b.documentation, symbolKind = _b.symbolKind, tags = _b.tags; - return { name: name, kindModifiers: kindModifiers, kind: symbolKind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: sourceDisplay }; + var _a = getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, typeChecker, host, compilerOptions, sourceFile, previousToken, formatContext, program.getSourceFiles(), preferences), codeActions = _a.codeActions, sourceDisplay = _a.sourceDisplay; + return createCompletionDetailsForSymbol(symbol, typeChecker, sourceFile, location, cancellationToken, codeActions, sourceDisplay); // TODO: GH#18217 } - case "none": { + case "literal": { + var literal = symbolCompletion.literal; + return createSimpleDetails(completionNameForLiteral(literal), "string" /* string */, typeof literal === "string" ? ts.SymbolDisplayPartKind.stringLiteral : ts.SymbolDisplayPartKind.numericLiteral); + } + case "none": // Didn't find a symbol with this name. See if we can find a keyword instead. - if (allKeywordsCompletions().some(function (c) { return c.name === name; })) { - return { - name: name, - kind: "keyword" /* keyword */, - kindModifiers: "" /* none */, - displayParts: [ts.displayPart(name, ts.SymbolDisplayPartKind.keyword)], - documentation: undefined, - tags: undefined, - codeActions: undefined, - source: undefined, - }; - } - return undefined; - } + return allKeywordsCompletions().some(function (c) { return c.name === name; }) ? createSimpleDetails(name, "keyword" /* keyword */, ts.SymbolDisplayPartKind.keyword) : undefined; + default: + ts.Debug.assertNever(symbolCompletion); } } Completions.getCompletionEntryDetails = getCompletionEntryDetails; - function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { - var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo && symbolOriginInfo.type === "export" - ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) - : { codeActions: undefined, sourceDisplay: undefined }; + function createSimpleDetails(name, kind, kind2) { + return createCompletionDetails(name, "" /* none */, kind, [ts.displayPart(name, kind2)]); } - function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { + function createCompletionDetailsForSymbol(symbol, checker, sourceFile, location, cancellationToken, codeActions, sourceDisplay) { + var _a = checker.runWithCancellationToken(cancellationToken, function (checker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, sourceFile, location, location, 7 /* All */); + }), displayParts = _a.displayParts, documentation = _a.documentation, symbolKind = _a.symbolKind, tags = _a.tags; + return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); + } + function stringLiteralCompletionDetails(name, location, completion, sourceFile, checker, cancellationToken) { + switch (completion.kind) { + case 0 /* Paths */: { + var match = ts.find(completion.paths, function (p) { return p.name === name; }); + return match && createCompletionDetails(name, "" /* none */, match.kind, [ts.textPart(name)]); + } + case 1 /* Properties */: { + var match = ts.find(completion.symbols, function (s) { return s.name === name; }); + return match && createCompletionDetailsForSymbol(match, checker, sourceFile, location, cancellationToken); + } + case 2 /* Types */: + return ts.find(completion.types, function (t) { return t.value === name; }) ? createCompletionDetails(name, "" /* none */, "type" /* typeElement */, [ts.textPart(name)]) : undefined; + default: + return ts.Debug.assertNever(completion); + } + } + function createCompletionDetails(name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source) { + return { name: name, kindModifiers: kindModifiers, kind: kind, displayParts: displayParts, documentation: documentation, tags: tags, codeActions: codeActions, source: source }; + } + function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, allSourceFiles, preferences) { + var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + if (!symbolOriginInfo || !originIsExport(symbolOriginInfo)) { + return { codeActions: undefined, sourceDisplay: undefined }; + } var moduleSymbol = symbolOriginInfo.moduleSymbol; - var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); - var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, previousToken), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; + var exportedSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + var _a = ts.codefix.getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, getSymbolName(symbol, symbolOriginInfo, compilerOptions.target), host, program, checker, allSourceFiles, formatContext, previousToken, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } - function getCompletionEntrySymbol(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles) { - var completion = getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, entryId, allSourceFiles); + function getCompletionEntrySymbol(program, log, sourceFile, position, entryId) { + var completion = getSymbolCompletionFromEntryId(program, log, sourceFile, position, entryId); return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; @@ -84503,26 +91578,28 @@ var ts; CompletionKind[CompletionKind["String"] = 4] = "String"; CompletionKind[CompletionKind["None"] = 5] = "None"; })(CompletionKind || (CompletionKind = {})); - function getRecommendedCompletion(currentToken, position, sourceFile, checker) { - var ty = getContextualType(currentToken, position, sourceFile, checker); - var symbol = ty && ty.symbol; - // Don't include make a recommended completion for an abstract class - return symbol && (symbol.flags & 384 /* Enum */ || symbol.flags & 32 /* Class */ && !ts.isAbstractConstructorSymbol(symbol)) - ? getFirstSymbolInChain(symbol, currentToken, checker) - : undefined; + function getRecommendedCompletion(previousToken, contextualType, checker) { + // For a union, return the first one with a recommended completion. + return ts.firstDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (type) { + var symbol = type && type.symbol; + // Don't include make a recommended completion for an abstract class + return symbol && (symbol.flags & (8 /* EnumMember */ | 384 /* Enum */ | 32 /* Class */) && !ts.isAbstractConstructorSymbol(symbol)) + ? getFirstSymbolInChain(symbol, previousToken, checker) + : undefined; + }); } - function getContextualType(currentToken, position, sourceFile, checker) { - var parent = currentToken.parent; - switch (currentToken.kind) { + function getContextualType(previousToken, position, sourceFile, checker) { + var parent = previousToken.parent; + switch (previousToken.kind) { case 71 /* Identifier */: - return getContextualTypeFromParent(currentToken, checker); + return getContextualTypeFromParent(previousToken, checker); case 58 /* EqualsToken */: switch (parent.kind) { - case 230 /* VariableDeclaration */: - return checker.getContextualType(parent.initializer); - case 198 /* BinaryExpression */: + case 235 /* VariableDeclaration */: + return checker.getContextualType(parent.initializer); // TODO: GH#18217 + case 202 /* BinaryExpression */: return checker.getTypeAtLocation(parent.left); - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return checker.getContextualTypeForJsxAttribute(parent); default: return undefined; @@ -84532,30 +91609,30 @@ var ts; case 73 /* CaseKeyword */: return getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); case 17 /* OpenBraceToken */: - return ts.isJsxExpression(parent) && parent.parent.kind !== 253 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; + return ts.isJsxExpression(parent) && parent.parent.kind !== 258 /* JsxElement */ ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: - var argInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(currentToken, position, sourceFile); + var argInfo = ts.SignatureHelp.getArgumentInfoForCompletions(previousToken, position, sourceFile); return argInfo // At `,`, treat this as the next argument after the comma. - ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (currentToken.kind === 26 /* CommaToken */ ? 1 : 0)) - : isEqualityOperatorKind(currentToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) + ? checker.getContextualTypeForArgumentAtIndex(argInfo.invocation, argInfo.argumentIndex + (previousToken.kind === 26 /* CommaToken */ ? 1 : 0)) + : isEqualityOperatorKind(previousToken.kind) && ts.isBinaryExpression(parent) && isEqualityOperatorKind(parent.operatorToken.kind) // completion at `x ===/**/` should be for the right side ? checker.getTypeAtLocation(parent.left) - : checker.getContextualType(currentToken); + : checker.getContextualType(previousToken); } } function getContextualTypeFromParent(node, checker) { var parent = node.parent; switch (parent.kind) { - case 186 /* NewExpression */: + case 190 /* NewExpression */: return checker.getContextualType(parent); - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var _a = parent, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case 264 /* CaseClause */: + case 269 /* CaseClause */: return parent.expression === node ? getSwitchedType(parent, checker) : undefined; default: return checker.getContextualType(node); @@ -84571,15 +91648,15 @@ var ts; return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { - return symbol.declarations.some(function (d) { return d.kind === 272 /* SourceFile */; }); + return symbol.declarations.some(function (d) { return d.kind === 277 /* SourceFile */; }); } - function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { + function getCompletionData(program, log, sourceFile, isUncheckedFile, position, preferences, detailsEntryId) { + var typeChecker = program.getTypeChecker(); var start = ts.timestamp(); - var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + var currentToken = ts.getTokenAtPosition(sourceFile, position); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) log("getCompletionData: Get current token: " + (ts.timestamp() - start)); start = ts.timestamp(); - // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); var insideJsDocTagTypeExpression = false; @@ -84622,11 +91699,11 @@ var ts; if (tag.tagName.pos <= position && position <= tag.tagName.end) { return { kind: 1 /* JsDocTagName */ }; } - if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 274 /* JSDocTypeExpression */) { - currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 281 /* JSDocTypeExpression */) { + currentToken = ts.getTokenAtPosition(sourceFile, position); if (!currentToken || (!ts.isDeclarationName(currentToken) && - (currentToken.parent.kind !== 292 /* JSDocPropertyTag */ || + (currentToken.parent.kind !== 302 /* JSDocPropertyTag */ || currentToken.parent.name !== currentToken))) { // Use as type location if inside tag's type expression insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); @@ -84644,16 +91721,16 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { + if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_4 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } // Find the node where completion is requested on. @@ -84665,7 +91742,7 @@ var ts; var isRightOfOpenTag = false; var isStartingCloseTag = false; var isJsxInitializer = false; - var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 + var location = ts.getTouchingPropertyName(sourceFile, position); if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -84676,13 +91753,17 @@ var ts; if (contextToken.kind === 23 /* DotToken */) { isRightOfDot = true; switch (parent.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: propertyAccessToConvert = parent; node = propertyAccessToConvert.expression; break; - case 145 /* QualifiedName */: + case 146 /* QualifiedName */: node = parent.left; break; + case 181 /* ImportType */: + case 212 /* MetaProperty */: + node = parent; + break; default: // There is nothing that precedes the dot, so this likely just a stray character // or leading into a '...' token. Just bail out instead. @@ -84693,7 +91774,7 @@ var ts; // // If the tagname is a property access expression, we will then walk up to the top most of property access expression. // Then, try to get a JSX container and its associated attributes type. - if (parent && parent.kind === 183 /* PropertyAccessExpression */) { + if (parent && parent.kind === 187 /* PropertyAccessExpression */) { contextToken = parent; parent = parent.parent; } @@ -84701,45 +91782,45 @@ var ts; if (currentToken.parent === location) { switch (currentToken.kind) { case 29 /* GreaterThanToken */: - if (currentToken.parent.kind === 253 /* JsxElement */ || currentToken.parent.kind === 255 /* JsxOpeningElement */) { + if (currentToken.parent.kind === 258 /* JsxElement */ || currentToken.parent.kind === 260 /* JsxOpeningElement */) { location = currentToken; } break; case 41 /* SlashToken */: - if (currentToken.parent.kind === 254 /* JsxSelfClosingElement */) { + if (currentToken.parent.kind === 259 /* JsxSelfClosingElement */) { location = currentToken; } break; } } switch (parent.kind) { - case 256 /* JsxClosingElement */: + case 261 /* JsxClosingElement */: if (contextToken.kind === 41 /* SlashToken */) { isStartingCloseTag = true; location = contextToken; } break; - case 198 /* BinaryExpression */: - if (!(parent.left.flags & 32768 /* ThisNodeHasError */)) { - // It has a left-hand side, so we're not in an opening JSX tag. + case 202 /* BinaryExpression */: + if (!binaryExpressionMayBeOpenTag(parent)) { break; } // falls through - case 254 /* JsxSelfClosingElement */: - case 253 /* JsxElement */: - case 255 /* JsxOpeningElement */: + case 259 /* JsxSelfClosingElement */: + case 258 /* JsxElement */: + case 260 /* JsxOpeningElement */: if (contextToken.kind === 27 /* LessThanToken */) { isRightOfOpenTag = true; location = contextToken; } break; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: switch (previousToken.kind) { case 58 /* EqualsToken */: isJsxInitializer = true; break; case 71 /* Identifier */: - if (previousToken !== parent.name) { + // For `
= contextToken.pos); + (ts.isClassLike(parent) && + !!parent.typeParameters && + parent.typeParameters.end >= contextToken.pos); case 23 /* DotToken */: - return containingNodeKind === 179 /* ArrayBindingPattern */; // var [.| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [.| case 56 /* ColonToken */: - return containingNodeKind === 180 /* BindingElement */; // var {x :html| + return containingNodeKind === 184 /* BindingElement */; // var {x :html| case 21 /* OpenBracketToken */: - return containingNodeKind === 179 /* ArrayBindingPattern */; // var [x| + return containingNodeKind === 183 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: - return containingNodeKind === 267 /* CatchClause */ || + return containingNodeKind === 272 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: - return containingNodeKind === 236 /* EnumDeclaration */ || // enum a { | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface a { | - containingNodeKind === 165 /* TypeLiteral */; // const x : { | - case 25 /* SemicolonToken */: - return containingNodeKind === 150 /* PropertySignature */ && - contextToken.parent && contextToken.parent.parent && - (contextToken.parent.parent.kind === 234 /* InterfaceDeclaration */ || // interface a { f; | - contextToken.parent.parent.kind === 165 /* TypeLiteral */); // const x : { a; | + return containingNodeKind === 241 /* EnumDeclaration */; // enum a { | case 27 /* LessThanToken */: - return containingNodeKind === 233 /* ClassDeclaration */ || // class A< | - containingNodeKind === 203 /* ClassExpression */ || // var C = class D< | - containingNodeKind === 234 /* InterfaceDeclaration */ || // interface A< | - containingNodeKind === 235 /* TypeAliasDeclaration */ || // type List< | + return containingNodeKind === 238 /* ClassDeclaration */ || // class A< | + containingNodeKind === 207 /* ClassExpression */ || // var C = class D< | + containingNodeKind === 239 /* InterfaceDeclaration */ || // interface A< | + containingNodeKind === 240 /* TypeAliasDeclaration */ || // type List< | ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: - return containingNodeKind === 151 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); + return containingNodeKind === 152 /* PropertyDeclaration */ && !ts.isClassLike(parent.parent); case 24 /* DotDotDotToken */: - return containingNodeKind === 148 /* Parameter */ || - (contextToken.parent && contextToken.parent.parent && - contextToken.parent.parent.kind === 179 /* ArrayBindingPattern */); // var [...z| + return containingNodeKind === 149 /* Parameter */ || + (!!parent.parent && parent.parent.kind === 183 /* ArrayBindingPattern */); // var [...z| case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: - return containingNodeKind === 148 /* Parameter */ && !ts.isConstructorDeclaration(contextToken.parent.parent); + return containingNodeKind === 149 /* Parameter */ && !ts.isConstructorDeclaration(parent.parent); case 118 /* AsKeyword */: - return containingNodeKind === 246 /* ImportSpecifier */ || - containingNodeKind === 250 /* ExportSpecifier */ || - containingNodeKind === 244 /* NamespaceImport */; + return containingNodeKind === 251 /* ImportSpecifier */ || + containingNodeKind === 255 /* ExportSpecifier */ || + containingNodeKind === 249 /* NamespaceImport */; case 125 /* GetKeyword */: case 136 /* SetKeyword */: - if (isFromClassElementDeclaration(contextToken)) { + if (isFromObjectTypeDeclaration(contextToken)) { return false; } // falls through @@ -85576,8 +92616,7 @@ var ts; } // If the previous token is keyword correspoding to class member completion keyword // there will be completion available here - if (isClassMemberCompletionKeywordText(contextToken.getText()) && - isFromClassElementDeclaration(contextToken)) { + if (isClassMemberCompletionKeyword(keywordForNode(contextToken)) && isFromObjectTypeDeclaration(contextToken)) { return false; } if (isConstructorParameterCompletion(contextToken)) { @@ -85586,28 +92625,28 @@ var ts; // - its name of the parameter and not being edited // eg. constructor(a |<- this shouldnt show completion if (!ts.isIdentifier(contextToken) || - isConstructorParameterCompletionKeywordText(contextToken.getText()) || + ts.isParameterPropertyModifier(keywordForNode(contextToken)) || isCurrentlyEditingNode(contextToken)) { return false; } } // Previous token may have been a keyword that was converted to an identifier. - switch (contextToken.getText()) { - case "abstract": - case "async": - case "class": - case "const": - case "declare": - case "enum": - case "function": - case "interface": - case "let": - case "private": - case "protected": - case "public": - case "static": - case "var": - case "yield": + switch (keywordForNode(contextToken)) { + case 117 /* AbstractKeyword */: + case 120 /* AsyncKeyword */: + case 75 /* ClassKeyword */: + case 76 /* ConstKeyword */: + case 124 /* DeclareKeyword */: + case 83 /* EnumKeyword */: + case 89 /* FunctionKeyword */: + case 109 /* InterfaceKeyword */: + case 110 /* LetKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 114 /* PublicKeyword */: + case 115 /* StaticKeyword */: + case 104 /* VarKeyword */: + case 116 /* YieldKeyword */: return true; } return ts.isDeclarationName(contextToken) @@ -85617,7 +92656,7 @@ var ts; && !(ts.isClassLike(contextToken.parent) && (contextToken !== previousToken || position > previousToken.end)); } function isFunctionLikeButNotConstructor(kind) { - return ts.isFunctionLikeKind(kind) && kind !== 154 /* Constructor */; + return ts.isFunctionLikeKind(kind) && kind !== 155 /* Constructor */; } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { @@ -85626,28 +92665,6 @@ var ts; } return false; } - /** - * Filters out completion suggestions for named imports or exports. - * - * @param exportsOfModule The list of symbols which a module exposes. - * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. - * - * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports - * do not occur at the current position and have not otherwise been typed. - */ - function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { - var existingImportsOrExports = ts.createUnderscoreEscapedMap(); - for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { - var element = namedImportsOrExports_1[_i]; - // If this is the current item we are editing right now, do not filter it out - if (isCurrentlyEditingNode(element)) { - continue; - } - var name = element.propertyName || element.name; - existingImportsOrExports.set(name.escapedText, true); - } - return exportsOfModule.filter(function (e) { return e.escapedName !== "default" /* Default */ && !existingImportsOrExports.get(e.escapedName); }); - } /** * Filters out completion suggestions for named imports or exports. * @@ -85662,12 +92679,12 @@ var ts; for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 268 /* PropertyAssignment */ && - m.kind !== 269 /* ShorthandPropertyAssignment */ && - m.kind !== 180 /* BindingElement */ && - m.kind !== 153 /* MethodDeclaration */ && - m.kind !== 155 /* GetAccessor */ && - m.kind !== 156 /* SetAccessor */) { + if (m.kind !== 273 /* PropertyAssignment */ && + m.kind !== 274 /* ShorthandPropertyAssignment */ && + m.kind !== 184 /* BindingElement */ && + m.kind !== 154 /* MethodDeclaration */ && + m.kind !== 156 /* GetAccessor */ && + m.kind !== 157 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -85675,7 +92692,7 @@ var ts; continue; } var existingName = void 0; - if (m.kind === 180 /* BindingElement */ && m.propertyName) { + if (ts.isBindingElement(m) && m.propertyName) { // include only identifiers in completion list if (m.propertyName.kind === 71 /* Identifier */) { existingName = m.propertyName.escapedText; @@ -85686,9 +92703,9 @@ var ts; // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. var name = ts.getNameOfDeclaration(m); - existingName = ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; + existingName = name && ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined; } - existingMemberNames.set(existingName, true); + existingMemberNames.set(existingName, true); // TODO: GH#18217 } return contextualMemberSymbols.filter(function (m) { return !existingMemberNames.get(m.escapedName); }); } @@ -85697,15 +92714,15 @@ var ts; * * @returns Symbols to be suggested in an class element depending on existing memebers and symbol flags */ - function filterClassMembersList(baseSymbols, implementingTypeSymbols, existingMembers, currentClassElementModifierFlags) { + function filterClassMembersList(baseSymbols, existingMembers, currentClassElementModifierFlags) { var existingMemberNames = ts.createUnderscoreEscapedMap(); for (var _i = 0, existingMembers_2 = existingMembers; _i < existingMembers_2.length; _i++) { var m = existingMembers_2[_i]; // Ignore omitted expressions for missing members - if (m.kind !== 151 /* PropertyDeclaration */ && - m.kind !== 153 /* MethodDeclaration */ && - m.kind !== 155 /* GetAccessor */ && - m.kind !== 156 /* SetAccessor */) { + if (m.kind !== 152 /* PropertyDeclaration */ && + m.kind !== 154 /* MethodDeclaration */ && + m.kind !== 156 /* GetAccessor */ && + m.kind !== 157 /* SetAccessor */) { continue; } // If this is the current item we are editing right now, do not filter it out @@ -85717,10 +92734,7 @@ var ts; continue; } // do not filter it out if the static presence doesnt match - var mIsStatic = ts.hasModifier(m, 32 /* Static */); - var currentElementIsStatic = !!(currentClassElementModifierFlags & 32 /* Static */); - if ((mIsStatic && !currentElementIsStatic) || - (!mIsStatic && currentElementIsStatic)) { + if (ts.hasModifier(m, 32 /* Static */) !== !!(currentClassElementModifierFlags & 32 /* Static */)) { continue; } var existingName = ts.getPropertyNameForPropertyNameNode(m.name); @@ -85728,23 +92742,11 @@ var ts; existingMemberNames.set(existingName, true); } } - var result = []; - addPropertySymbols(baseSymbols, 8 /* Private */); - addPropertySymbols(implementingTypeSymbols, 24 /* NonPublicAccessibilityModifier */); - return result; - function addPropertySymbols(properties, inValidModifierFlags) { - for (var _i = 0, properties_12 = properties; _i < properties_12.length; _i++) { - var property = properties_12[_i]; - if (isValidProperty(property, inValidModifierFlags)) { - result.push(property); - } - } - } - function isValidProperty(propertySymbol, inValidModifierFlags) { - return !existingMemberNames.get(propertySymbol.escapedName) && - propertySymbol.getDeclarations() && - !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & inValidModifierFlags); - } + return baseSymbols.filter(function (propertySymbol) { + return !existingMemberNames.has(propertySymbol.escapedName) && + !!propertySymbol.declarations && + !(ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 8 /* Private */); + }); } /** * Filters out completion suggestions from 'symbols' according to existing JSX attributes. @@ -85760,14 +92762,14 @@ var ts; if (isCurrentlyEditingNode(attr)) { continue; } - if (attr.kind === 260 /* JsxAttribute */) { + if (attr.kind === 265 /* JsxAttribute */) { seenNames.set(attr.name.escapedText, true); } } return symbols.filter(function (a) { return !seenNames.get(a.escapedName); }); } function isCurrentlyEditingNode(node) { - return node.getStart() <= position && position <= node.getEnd(); + return node.getStart(sourceFile) <= position && position <= node.getEnd(); } } function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { @@ -85790,7 +92792,7 @@ var ts; // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: - case 1 /* Global */: + case 1 /* Global */: // For a 'this.' completion it will be in a global context, but may have a non-identifier name. // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; case 5 /* None */: @@ -85804,7 +92806,7 @@ var ts; var _keywordCompletions = []; var allKeywordsCompletions = ts.memoize(function () { var res = []; - for (var i = 72 /* FirstKeyword */; i <= 144 /* LastKeyword */; i++) { + for (var i = 72 /* FirstKeyword */; i <= 145 /* LastKeyword */; i++) { res.push({ name: ts.tokenToString(i), kind: "keyword" /* keyword */, @@ -85823,62 +92825,36 @@ var ts; return kind !== 140 /* UndefinedKeyword */; case 1 /* ClassElementKeywords */: return isClassMemberCompletionKeyword(kind); - case 2 /* ConstructorParameterKeywords */: - return isConstructorParameterCompletionKeyword(kind); - case 3 /* FunctionLikeBodyKeywords */: - return isFunctionLikeBodyCompletionKeyword(kind); - case 4 /* TypeKeywords */: + case 2 /* InterfaceElementKeywords */: + return isInterfaceOrTypeLiteralCompletionKeyword(kind); + case 3 /* ConstructorParameterKeywords */: + return ts.isParameterPropertyModifier(kind); + case 4 /* FunctionLikeBodyKeywords */: + return !isClassMemberCompletionKeyword(kind); + case 5 /* TypeKeywords */: return ts.isTypeKeyword(kind); default: return ts.Debug.assertNever(keywordFilter); } })); } + function isInterfaceOrTypeLiteralCompletionKeyword(kind) { + return kind === 132 /* ReadonlyKeyword */; + } function isClassMemberCompletionKeyword(kind) { switch (kind) { - case 114 /* PublicKeyword */: - case 113 /* ProtectedKeyword */: - case 112 /* PrivateKeyword */: case 117 /* AbstractKeyword */: - case 115 /* StaticKeyword */: case 123 /* ConstructorKeyword */: - case 132 /* ReadonlyKeyword */: case 125 /* GetKeyword */: case 136 /* SetKeyword */: case 120 /* AsyncKeyword */: return true; + default: + return ts.isClassMemberModifier(kind); } } - function isClassMemberCompletionKeywordText(text) { - return isClassMemberCompletionKeyword(ts.stringToToken(text)); - } - function isConstructorParameterCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - } - } - function isConstructorParameterCompletionKeywordText(text) { - return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); - } - function isFunctionLikeBodyCompletionKeyword(kind) { - switch (kind) { - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - case 123 /* ConstructorKeyword */: - case 115 /* StaticKeyword */: - case 117 /* AbstractKeyword */: - case 125 /* GetKeyword */: - case 136 /* SetKeyword */: - case 140 /* UndefinedKeyword */: - return false; - } - return true; + function keywordForNode(node) { + return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } function isEqualityOperatorKind(kind) { switch (kind) { @@ -85893,48 +92869,106 @@ var ts; } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { - var jsDoc = getJsDocHavingNode(node).jsDoc; - if (!jsDoc) - return undefined; - for (var _i = 0, jsDoc_1 = jsDoc; _i < jsDoc_1.length; _i++) { - var _a = jsDoc_1[_i], pos = _a.pos, end = _a.end, tags = _a.tags; - if (!tags || position < pos || position > end) - continue; - for (var i = tags.length - 1; i >= 0; i--) { - var tag = tags[i]; - if (position >= tag.pos) { - return tag; - } - } - } + var jsdoc = ts.findAncestor(node, ts.isJSDoc); + return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); } - function getJsDocHavingNode(node) { - if (!ts.isToken(node)) - return node; - switch (node.kind) { - case 104 /* VarKeyword */: - case 110 /* LetKeyword */: - case 76 /* ConstKeyword */: - // if the current token is var, let or const, skip the VariableDeclarationList - return node.parent.parent; - default: - return node.parent; - } + function getPropertiesForObjectExpression(contextualType, obj, checker) { + return contextualType.isUnion() + ? checker.getAllPossiblePropertiesOfTypes(contextualType.types.filter(function (memberType) { + // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. + return !(memberType.flags & 32764 /* Primitive */ || + checker.isArrayLikeType(memberType) || + ts.typeHasCallOrConstructSignatures(memberType, checker) || + checker.isTypeInvalidDueToUnionDiscriminant(memberType, obj)); + })) + : contextualType.getApparentProperties(); } /** * Gets all properties on a type, but if that type is a union of several types, * excludes array-like types or callable/constructable types. */ - function getPropertiesForCompletion(type, checker, isForAccess) { - if (!(type.flags & 131072 /* Union */)) { - return ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + function getPropertiesForCompletion(type, checker) { + return type.isUnion() + ? ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(type.types), "getAllPossiblePropertiesOfTypes() should all be defined") + : ts.Debug.assertEachDefined(type.getApparentProperties(), "getApparentProperties() should all be defined"); + } + /** + * Returns the immediate owning class declaration of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location) { + // class c { method() { } | method2() { } } + switch (location.kind) { + case 303 /* SyntaxList */: + return ts.tryCast(location.parent, ts.isObjectTypeDeclaration); + case 1 /* EndOfFileToken */: + var cls = ts.tryCast(ts.lastOrUndefined(ts.cast(location.parent, ts.isSourceFile).statements), ts.isObjectTypeDeclaration); + if (cls && !ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile)) { + return cls; + } + } + if (!contextToken) + return undefined; + switch (contextToken.kind) { + case 25 /* SemicolonToken */: // class c {getValue(): number; | } + case 18 /* CloseBraceToken */: // class c { method() { } | } + // class c { method() { } b| } + return isFromObjectTypeDeclaration(location) && location.parent.name === location + ? location.parent.parent + : ts.tryCast(location, ts.isObjectTypeDeclaration); + case 17 /* OpenBraceToken */: // class c { | + case 26 /* CommaToken */: // class c {getValue(): number, | } + return ts.tryCast(contextToken.parent, ts.isObjectTypeDeclaration); + default: + if (!isFromObjectTypeDeclaration(contextToken)) + return undefined; + var isValidKeyword = ts.isClassLike(contextToken.parent.parent) ? isClassMemberCompletionKeyword : isInterfaceOrTypeLiteralCompletionKeyword; + return (isValidKeyword(contextToken.kind) || ts.isIdentifier(contextToken) && isValidKeyword(ts.stringToToken(contextToken.text))) // TODO: GH#18217 + ? contextToken.parent.parent : undefined; + } + } + // TODO: GH#19856 Would like to return `node is Node & { parent: (ClassElement | TypeElement) & { parent: ObjectTypeDeclaration } }` but then compilation takes > 10 minutes + function isFromObjectTypeDeclaration(node) { + return node.parent && ts.isClassOrTypeElement(node.parent) && ts.isObjectTypeDeclaration(node.parent.parent); + } + function hasIndexSignature(type) { + return !!type.getStringIndexType() || !!type.getNumberIndexType(); + } + function isValidTrigger(sourceFile, triggerCharacter, contextToken, position) { + switch (triggerCharacter) { + case ".": + case "@": + return true; + case '"': + case "'": + case "`": + // Only automatically bring up completions if this is an opening quote. + return isStringLiteralOrTemplate(contextToken) && position === contextToken.getStart(sourceFile) + 1; + case "<": + // Opening JSX tag + return contextToken.kind === 27 /* LessThanToken */ && (!ts.isBinaryExpression(contextToken.parent) || binaryExpressionMayBeOpenTag(contextToken.parent)); + case "/": + return ts.isStringLiteralLike(contextToken) + ? !!ts.tryGetImportFromModuleSpecifier(contextToken) + : contextToken.kind === 41 /* SlashToken */ && ts.isJsxClosingElement(contextToken.parent); + default: + return ts.Debug.assertNever(triggerCharacter); + } + } + function binaryExpressionMayBeOpenTag(_a) { + var left = _a.left; + return ts.nodeIsMissing(left); + } + function isStringLiteralOrTemplate(node) { + switch (node.kind) { + case 9 /* StringLiteral */: + case 13 /* NoSubstitutionTemplateLiteral */: + case 204 /* TemplateExpression */: + case 191 /* TaggedTemplateExpression */: + return true; + default: + return false; } - var types = type.types; - // If we're providing completions for an object literal, skip primitive, array-like, or callable types since those shouldn't be implemented by object literals. - var filteredTypes = isForAccess ? types : types.filter(function (memberType) { - return !(memberType.flags & 16382 /* Primitive */ || checker.isArrayLikeType(memberType) || ts.typeHasCallOrConstructSignatures(memberType, checker)); - }); - return ts.Debug.assertEachDefined(checker.getAllPossiblePropertiesOfTypes(filteredTypes), "getAllPossiblePropertiesOfTypes() should all be defined"); } })(Completions = ts.Completions || (ts.Completions = {})); })(ts || (ts = {})); @@ -85944,7 +92978,7 @@ var ts; var DocumentHighlights; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; @@ -85965,13 +92999,21 @@ var ts; }; } function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); + var sourceFilesSet = ts.arrayToSet(sourceFilesToSearch, function (f) { return f.fileName; }); + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet); if (!referenceEntries) return undefined; var map = ts.arrayToMultiMap(referenceEntries.map(ts.FindAllReferences.toHighlightSpan), function (e) { return e.fileName; }, function (e) { return e.span; }); return ts.arrayFrom(map.entries(), function (_a) { var fileName = _a[0], highlightSpans = _a[1]; - return ({ fileName: fileName, highlightSpans: highlightSpans }); + if (!sourceFilesSet.has(fileName)) { + ts.Debug.assert(program.redirectTargetsSet.has(fileName)); + var redirectTarget_1 = program.getSourceFile(fileName); + var redirect = ts.find(sourceFilesToSearch, function (f) { return !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget_1; }); + fileName = redirect.fileName; + ts.Debug.assert(sourceFilesSet.has(fileName)); + } + return { fileName: fileName, highlightSpans: highlightSpans }; }); } function getSyntacticDocumentHighlights(node, sourceFile) { @@ -86009,6 +93051,12 @@ var ts; case 125 /* GetKeyword */: case 136 /* SetKeyword */: return getFromAllDeclarations(ts.isAccessor, [125 /* GetKeyword */, 136 /* SetKeyword */]); + case 121 /* AwaitKeyword */: + return useParent(node.parent, ts.isAwaitExpression, getAsyncAndAwaitOccurrences); + case 120 /* AsyncKeyword */: + return highlightSpans(getAsyncAndAwaitOccurrences(node)); + case 116 /* YieldKeyword */: + return highlightSpans(getYieldOccurrences(node)); default: return ts.isModifierKind(node.kind) && (ts.isDeclaration(node.parent) || ts.isVariableStatement(node.parent)) ? highlightSpans(getModifierOccurrences(node.kind, node.parent)) @@ -86036,7 +93084,7 @@ var ts; } else if (ts.isTryStatement(node)) { // Exceptions thrown within a try block lacking a catch clause are "owned" in the current context. - return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), aggregateOwnedThrowStatements(node.finallyBlock)); + return ts.concatenate(node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock), node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock)); } // Do not cross function boundaries. return ts.isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements); @@ -86050,7 +93098,7 @@ var ts; var child = throwStatement; while (child.parent) { var parent = child.parent; - if (ts.isFunctionBlock(parent) || parent.kind === 272 /* SourceFile */) { + if (ts.isFunctionBlock(parent) || parent.kind === 277 /* SourceFile */) { return parent; } // A throw-statement is only owned by a try-statement if the try-statement has @@ -86077,48 +93125,41 @@ var ts; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); - return actualOwner && actualOwner === owner; + return !!actualOwner && actualOwner === owner; } function getBreakOrContinueOwner(statement) { return ts.findAncestor(statement, function (node) { switch (node.kind) { - case 225 /* SwitchStatement */: - if (statement.kind === 221 /* ContinueStatement */) { + case 230 /* SwitchStatement */: + if (statement.kind === 226 /* ContinueStatement */) { return false; } // falls through - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: return !statement.label || isLabeledBy(node, statement.label.escapedText); default: // Don't cross function boundaries. // TODO: GH#20090 - return (ts.isFunctionLike(node) && "quit"); + return ts.isFunctionLike(node) && "quit"; } }); } function getModifierOccurrences(modifier, declaration) { - var modifierFlag = ts.modifierToFlag(modifier); - return ts.mapDefined(getNodesToSearchForModifier(declaration, modifierFlag), function (node) { - if (ts.getModifierFlags(node) & modifierFlag) { - var mod = ts.find(node.modifiers, function (m) { return m.kind === modifier; }); - ts.Debug.assert(!!mod); - return mod; - } - }); + return ts.mapDefined(getNodesToSearchForModifier(declaration, ts.modifierToFlag(modifier)), function (node) { return ts.findModifier(node, modifier); }); } function getNodesToSearchForModifier(declaration, modifierFlag) { // Types of node whose children might have modifiers. var container = declaration.parent; switch (container.kind) { - case 238 /* ModuleBlock */: - case 272 /* SourceFile */: - case 211 /* Block */: - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: + case 216 /* Block */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // Container is either a class declaration or the declaration is a classDeclaration if (modifierFlag & 128 /* Abstract */ && ts.isClassDeclaration(declaration)) { return declaration.members.concat([declaration]); @@ -86126,13 +93167,12 @@ var ts; else { return container.statements; } - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 232 /* FunctionDeclaration */: { + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 237 /* FunctionDeclaration */: return container.parameters.concat((ts.isClassLike(container.parent) ? container.parent.members : [])); - } - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: var nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -86165,7 +93205,7 @@ var ts; var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 88 /* ForKeyword */, 106 /* WhileKeyword */, 81 /* DoKeyword */)) { // If we succeeded and got a do-while loop, then start looking for a 'while' keyword. - if (loopNode.kind === 216 /* DoStatement */) { + if (loopNode.kind === 221 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 106 /* WhileKeyword */)) { @@ -86185,13 +93225,13 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 216 /* DoStatement */: - case 217 /* WhileStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 221 /* DoStatement */: + case 222 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -86256,6 +93296,48 @@ var ts; }); return keywords; } + function getAsyncAndAwaitOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + if (func.modifiers) { + func.modifiers.forEach(function (modifier) { + pushKeywordIf(keywords, modifier, 120 /* AsyncKeyword */); + }); + } + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isAwaitExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 121 /* AwaitKeyword */); + } + }); + }); + return keywords; + } + function getYieldOccurrences(node) { + var func = ts.getContainingFunction(node); + if (!func) { + return undefined; + } + var keywords = []; + ts.forEachChild(func, function (child) { + traverseWithoutCrossingFunction(child, function (node) { + if (ts.isYieldExpression(node)) { + pushKeywordIf(keywords, node.getFirstToken(), 116 /* YieldKeyword */); + } + }); + }); + return keywords; + } + // Do not cross function/class/interface/module/type boundaries. + function traverseWithoutCrossingFunction(node, cb) { + cb(node); + if (!ts.isFunctionLike(node) && !ts.isClassLike(node) && !ts.isInterfaceDeclaration(node) && !ts.isModuleDeclaration(node) && !ts.isTypeAliasDeclaration(node) && !ts.isTypeNode(node)) { + ts.forEachChild(node, function (child) { return traverseWithoutCrossingFunction(child, cb); }); + } + } function getIfElseOccurrences(ifStatement, sourceFile) { var keywords = getIfElseKeywords(ifStatement, sourceFile); var result = []; @@ -86323,6 +93405,11 @@ var ts; var ts; (function (ts) { function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + return createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory); + } + ts.createDocumentRegistry = createDocumentRegistry; + /*@internal*/ + function createDocumentRegistryInternal(useCaseSensitiveFileNames, currentDirectory, externalCache) { if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. @@ -86336,7 +93423,7 @@ var ts; if (!bucket && createIfMissing) { buckets.set(key, bucket = ts.createMap()); } - return bucket; + return bucket; // TODO: GH#18217 } function reportStats() { var bucketInfoArray = ts.arrayFrom(buckets.keys()).filter(function (name) { return name && name.charAt(0) === "_"; }).map(function (name) { @@ -86345,8 +93432,7 @@ var ts; entries.forEach(function (entry, name) { sourceFiles.push({ name: name, - refCount: entry.languageServiceRefCount, - references: entry.owners.slice(0) + refCount: entry.languageServiceRefCount }); }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); @@ -86376,13 +93462,27 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { var bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ true); var entry = bucket.get(path); + var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : compilationSettings.target; + if (!entry && externalCache) { + var sourceFile = externalCache.getDocument(key, path); + if (sourceFile) { + ts.Debug.assert(acquiring); + entry = { + sourceFile: sourceFile, + languageServiceRefCount: 0 + }; + bucket.set(path, entry); + } + } if (!entry) { // Have never seen this file with these settings. Create a new source file for it. - var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, /*setNodeParents*/ false, scriptKind); + var sourceFile = ts.createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, /*setNodeParents*/ false, scriptKind); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, sourceFile); + } entry = { sourceFile: sourceFile, languageServiceRefCount: 1, - owners: [] }; bucket.set(path, entry); } @@ -86391,7 +93491,10 @@ var ts; // the script snapshot. If so, update it appropriately. Otherwise, we can just // return it as is. if (entry.sourceFile.version !== version) { - entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); + entry.sourceFile = ts.updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, scriptSnapshot.getChangeRange(entry.sourceFile.scriptSnapshot)); // TODO: GH#18217 + if (externalCache) { + externalCache.setDocument(key, path, entry.sourceFile); + } } // If we're acquiring, then this is the first time this LS is asking for this document. // Increase our ref count so we know there's another LS using the document. If we're @@ -86402,6 +93505,7 @@ var ts; entry.languageServiceRefCount++; } } + ts.Debug.assert(entry.languageServiceRefCount !== 0); return entry.sourceFile; } function releaseDocument(fileName, compilationSettings) { @@ -86419,6 +93523,13 @@ var ts; bucket.delete(path); } } + function getLanguageServiceRefCounts(path) { + return ts.arrayFrom(buckets.entries(), function (_a) { + var key = _a[0], bucket = _a[1]; + var entry = bucket.get(path); + return [key, entry && entry.languageServiceRefCount]; + }); + } return { acquireDocument: acquireDocument, acquireDocumentWithKey: acquireDocumentWithKey, @@ -86426,11 +93537,12 @@ var ts; updateDocumentWithKey: updateDocumentWithKey, releaseDocument: releaseDocument, releaseDocumentWithKey: releaseDocumentWithKey, + getLanguageServiceRefCounts: getLanguageServiceRefCounts, reportStats: reportStats, getKeyForCompilationSettings: getKeyForCompilationSettings }; } - ts.createDocumentRegistry = createDocumentRegistry; + ts.createDocumentRegistryInternal = createDocumentRegistryInternal; })(ts || (ts = {})); /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ /* @internal */ @@ -86439,10 +93551,10 @@ var ts; var FindAllReferences; (function (FindAllReferences) { /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ - function createImportTracker(sourceFiles, checker, cancellationToken) { + function createImportTracker(sourceFiles, sourceFilesSet, checker, cancellationToken) { var allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); return function (exportSymbol, exportInfo, isForRename) { - var _a = getImportersForExport(sourceFiles, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; + var _a = getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, exportInfo, checker, cancellationToken), directImports = _a.directImports, indirectUsers = _a.indirectUsers; return __assign({ indirectUsers: indirectUsers }, getSearchesFromDirectImports(directImports, exportSymbol, exportInfo.exportKind, checker, isForRename)); }; } @@ -86459,7 +93571,7 @@ var ts; ImportExport[ImportExport["Export"] = 1] = "Export"; })(ImportExport = FindAllReferences.ImportExport || (FindAllReferences.ImportExport = {})); /** Returns import statements that directly reference the exporting module, and a list of files that may access the module through a namespace. */ - function getImportersForExport(sourceFiles, allDirectImports, _a, checker, cancellationToken) { + function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, _a, checker, cancellationToken) { var exportingModuleSymbol = _a.exportingModuleSymbol, exportKind = _a.exportKind; var markSeenDirectImport = ts.nodeSeenTracker(); var markSeenIndirectUser = ts.nodeSeenTracker(); @@ -86476,7 +93588,7 @@ var ts; // Module augmentations may use this module's exports without importing it. for (var _i = 0, _a = exportingModuleSymbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - if (ts.isExternalModuleAugmentation(decl)) { + if (ts.isExternalModuleAugmentation(decl) && sourceFilesSet.has(decl.getSourceFile().fileName)) { addIndirectUser(decl); } } @@ -86491,12 +93603,13 @@ var ts; if (!markSeenDirectImport(direct)) { continue; } - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { - case 185 /* CallExpression */: + case 189 /* CallExpression */: if (!isAvailableThroughGlobal) { var parent = direct.parent; - if (exportKind === 2 /* ExportEquals */ && parent.kind === 230 /* VariableDeclaration */) { + if (exportKind === 2 /* ExportEquals */ && parent.kind === 235 /* VariableDeclaration */) { var name = parent.name; if (name.kind === 71 /* Identifier */) { directImports.push(name); @@ -86507,26 +93620,22 @@ var ts; addIndirectUser(direct.getSourceFile()); } break; - case 241 /* ImportEqualsDeclaration */: - handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */)); + case 71 /* Identifier */: // for 'const x = require("y"); + break; // TODO: GH#23879 + case 246 /* ImportEqualsDeclaration */: + handleNamespaceImport(direct, direct.name, ts.hasModifier(direct, 1 /* Export */), /*alreadyAddedDirect*/ false); break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: + directImports.push(direct); var namedBindings = direct.importClause && direct.importClause.namedBindings; - if (namedBindings && namedBindings.kind === 244 /* NamespaceImport */) { - handleNamespaceImport(direct, namedBindings.name); + if (namedBindings && namedBindings.kind === 249 /* NamespaceImport */) { + handleNamespaceImport(direct, namedBindings.name, /*isReExport*/ false, /*alreadyAddedDirect*/ true); } - else if (ts.isDefaultImport(direct)) { - var sourceFileLike = getSourceFileLikeForImportDeclaration(direct); - if (!isAvailableThroughGlobal) { - addIndirectUser(sourceFileLike); // Add a check for indirect uses to handle synthetic default imports - } - directImports.push(direct); - } - else { - directImports.push(direct); + else if (!isAvailableThroughGlobal && ts.isDefaultImport(direct)) { + addIndirectUser(getSourceFileLikeForImportDeclaration(direct)); // Add a check for indirect uses to handle synthetic default imports } break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: if (!direct.exportClause) { // This is `export * from "foo"`, so imports of this module may import the export too. handleDirectImports(getContainingModuleSymbol(direct, checker)); @@ -86536,18 +93645,24 @@ var ts; directImports.push(direct); } break; + case 181 /* ImportType */: + directImports.push(direct); + break; + default: + ts.Debug.assertNever(direct, "Unexpected import kind: " + ts.Debug.showSyntaxKind(direct)); } } } } - function handleNamespaceImport(importDeclaration, name, isReExport) { + function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { if (exportKind === 2 /* ExportEquals */) { // This is a direct import, not import-as-namespace. - directImports.push(importDeclaration); + if (!alreadyAddedDirect) + directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { var sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); - ts.Debug.assert(sourceFileLike.kind === 272 /* SourceFile */ || sourceFileLike.kind === 237 /* ModuleDeclaration */); + ts.Debug.assert(sourceFileLike.kind === 277 /* SourceFile */ || sourceFileLike.kind === 242 /* ModuleDeclaration */); if (isReExport || findNamespaceReExports(sourceFileLike, name, checker)) { addIndirectUsers(sourceFileLike); } @@ -86560,7 +93675,7 @@ var ts; ts.Debug.assert(!isAvailableThroughGlobal); var isNew = markSeenIndirectUser(sourceFileLike); if (isNew) { - indirectUserDeclarations.push(sourceFileLike); + indirectUserDeclarations.push(sourceFileLike); // TODO: GH#18217 } return isNew; } @@ -86602,7 +93717,7 @@ var ts; } return { importSearches: importSearches, singleReferences: singleReferences }; function handleImport(decl) { - if (decl.kind === 241 /* ImportEqualsDeclaration */) { + if (decl.kind === 246 /* ImportEqualsDeclaration */) { if (isExternalModuleImportEquals(decl)) { handleNamespaceImportLike(decl.name); } @@ -86612,40 +93727,48 @@ var ts; handleNamespaceImportLike(decl); return; } + if (decl.kind === 181 /* ImportType */) { + if (decl.qualifier) { + if (ts.isIdentifier(decl.qualifier) && decl.qualifier.escapedText === ts.symbolName(exportSymbol)) { + singleReferences.push(decl.qualifier); + } + } + else if (exportKind === 2 /* ExportEquals */) { + singleReferences.push(decl.argument.literal); + } + return; + } // Ignore if there's a grammar error if (decl.moduleSpecifier.kind !== 9 /* StringLiteral */) { return; } - if (decl.kind === 248 /* ExportDeclaration */) { + if (decl.kind === 253 /* ExportDeclaration */) { searchForNamedImport(decl.exportClause); return; } - var importClause = decl.importClause; - if (!importClause) { - return; - } - var namedBindings = importClause.namedBindings; - if (namedBindings && namedBindings.kind === 244 /* NamespaceImport */) { - handleNamespaceImportLike(namedBindings.name); - return; - } - if (exportKind === 0 /* Named */) { - searchForNamedImport(namedBindings); - } - else { - // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals - var name = importClause.name; - // If a default import has the same name as the default export, allow to rename it. - // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. - if (name && (!isForRename || name.escapedText === symbolName(exportSymbol))) { - var defaultImportAlias = checker.getSymbolAtLocation(name); - addSearch(name, defaultImportAlias); - } - // 'default' might be accessed as a named import `{ default as foo }`. - if (!isForRename && exportKind === 1 /* Default */) { - searchForNamedImport(namedBindings); + var _a = decl.importClause || { name: undefined, namedBindings: undefined }, name = _a.name, namedBindings = _a.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case 249 /* NamespaceImport */: + handleNamespaceImportLike(namedBindings.name); + break; + case 250 /* NamedImports */: + // 'default' might be accessed as a named import `{ default as foo }`. + if (exportKind === 0 /* Named */ || exportKind === 1 /* Default */) { + searchForNamedImport(namedBindings); + } + break; + default: + ts.Debug.assertNever(namedBindings); } } + // `export =` might be imported by a default import if `--allowSyntheticDefaultImports` is on, so this handles both ExportKind.Default and ExportKind.ExportEquals. + // If a default import has the same name as the default export, allow to rename it. + // Given `import f` and `export default function f`, we will rename both, but for `import g` we will rename just that. + if (name && (exportKind === 1 /* Default */ || exportKind === 2 /* ExportEquals */) && (!isForRename || name.escapedText === ts.symbolEscapedNameNoDefault(exportSymbol))) { + var defaultImportAlias = checker.getSymbolAtLocation(name); + addSearch(name, defaultImportAlias); + } } /** * `import x = require("./x") or `import * as x from "./x"`. @@ -86671,13 +93794,15 @@ var ts; if (propertyName) { // This is `import { foo as bar } from "./a"` or `export { foo as bar } from "./a"`. `foo` isn't a local in the file, so just add it as a single reference. singleReferences.push(propertyName); - if (!isForRename) { // If renaming `foo`, don't touch `bar`, just `foo`. + // If renaming `{ foo as bar }`, don't touch `bar`, just `foo`. + // But do rename `foo` in ` { default as foo }` if that's the original export name. + if (!isForRename || name.escapedText === exportSymbol.escapedName) { // Search locally for `bar`. addSearch(name, checker.getSymbolAtLocation(name)); } } else { - var localSymbol = element.kind === 250 /* ExportSpecifier */ && element.propertyName + var localSymbol = element.kind === 255 /* ExportSpecifier */ && element.propertyName ? checker.getExportSpecifierLocalTargetSymbol(element) // For re-exporting under a different name, we want to get the re-exported symbol. : checker.getSymbolAtLocation(name); addSearch(name, localSymbol); @@ -86692,27 +93817,21 @@ var ts; /** Returns 'true' is the namespace 'name' is re-exported from this module, and 'false' if it is only used locally. */ function findNamespaceReExports(sourceFileLike, name, checker) { var namespaceImportSymbol = checker.getSymbolAtLocation(name); - return forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { - if (statement.kind !== 248 /* ExportDeclaration */) + return !!forEachPossibleImportOrExportStatement(sourceFileLike, function (statement) { + if (!ts.isExportDeclaration(statement)) return; - var _a = statement, exportClause = _a.exportClause, moduleSpecifier = _a.moduleSpecifier; - if (moduleSpecifier || !exportClause) - return; - for (var _i = 0, _b = exportClause.elements; _i < _b.length; _i++) { - var element = _b[_i]; - if (checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol) { - return true; - } - } + var exportClause = statement.exportClause, moduleSpecifier = statement.moduleSpecifier; + return !moduleSpecifier && exportClause && + exportClause.elements.some(function (element) { return checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol; }); }); } function findModuleReferences(program, sourceFiles, searchModuleSymbol) { var refs = []; var checker = program.getTypeChecker(); - for (var _i = 0, sourceFiles_4 = sourceFiles; _i < sourceFiles_4.length; _i++) { - var referencingFile = sourceFiles_4[_i]; + for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { + var referencingFile = sourceFiles_5[_i]; var searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === 272 /* SourceFile */) { + if (searchSourceFile.kind === 277 /* SourceFile */) { for (var _a = 0, _b = referencingFile.referencedFiles; _a < _b.length; _a++) { var ref = _b[_a]; if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { @@ -86740,9 +93859,10 @@ var ts; /** Returns a map from a module symbol Id to all import statements that directly reference the module. */ function getDirectImportsMap(sourceFiles, checker, cancellationToken) { var map = ts.createMap(); - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var sourceFile = sourceFiles_5[_i]; - cancellationToken.throwIfCancellationRequested(); + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var sourceFile = sourceFiles_6[_i]; + if (cancellationToken) + cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, function (importDecl, moduleSpecifier) { var moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol) { @@ -86759,7 +93879,7 @@ var ts; } /** Iterates over all statements at the top level or in module declarations. Returns the first truthy result. */ function forEachPossibleImportOrExportStatement(sourceFileLike, action) { - return ts.forEach(sourceFileLike.kind === 272 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { + return ts.forEach(sourceFileLike.kind === 277 /* SourceFile */ ? sourceFileLike.statements : sourceFileLike.body.statements, function (statement) { return action(statement) || (isAmbientModuleDeclaration(statement) && ts.forEach(statement.body && statement.body.statements, action)); }); } @@ -86767,27 +93887,25 @@ var ts; function forEachImport(sourceFile, action) { if (sourceFile.externalModuleIndicator || sourceFile.imports !== undefined) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var moduleSpecifier = _a[_i]; - action(importerFromModuleSpecifier(moduleSpecifier), moduleSpecifier); + var i = _a[_i]; + action(ts.importFromModuleSpecifier(i), i); } } else { forEachPossibleImportOrExportStatement(sourceFile, function (statement) { switch (statement.kind) { - case 248 /* ExportDeclaration */: - case 242 /* ImportDeclaration */: { + case 253 /* ExportDeclaration */: + case 247 /* ImportDeclaration */: { var decl = statement; - if (decl.moduleSpecifier && decl.moduleSpecifier.kind === 9 /* StringLiteral */) { + if (decl.moduleSpecifier && ts.isStringLiteral(decl.moduleSpecifier)) { action(decl, decl.moduleSpecifier); } break; } - case 241 /* ImportEqualsDeclaration */: { + case 246 /* ImportEqualsDeclaration */: { var decl = statement; - var moduleReference = decl.moduleReference; - if (moduleReference.kind === 252 /* ExternalModuleReference */ && - moduleReference.expression.kind === 9 /* StringLiteral */) { - action(decl, moduleReference.expression); + if (isExternalModuleImportEquals(decl)) { + action(decl, decl.moduleReference.expression); } break; } @@ -86795,19 +93913,6 @@ var ts; }); } } - function importerFromModuleSpecifier(moduleSpecifier) { - var decl = moduleSpecifier.parent; - switch (decl.kind) { - case 185 /* CallExpression */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return decl; - case 252 /* ExternalModuleReference */: - return decl.parent; - default: - ts.Debug.fail("Unexpected module specifier parent: " + decl.kind); - } - } /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. * If at an import, look locally for the symbol it imports. @@ -86819,12 +93924,13 @@ var ts; return comingFromExport ? getExport() : getExport() || getImport(); function getExport() { var parent = node.parent; + var grandParent = parent.parent; if (symbol.exportSymbol) { - if (parent.kind === 183 /* PropertyAccessExpression */) { + if (parent.kind === 187 /* PropertyAccessExpression */) { // When accessing an export of a JS module, there's no alias. The symbol will still be flagged as an export even though we're at the use. // So check that we are at the declaration. - return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(parent.parent) - ? getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ false) + return symbol.declarations.some(function (d) { return d === parent; }) && ts.isBinaryExpression(grandParent) + ? getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ false) : undefined; } else { @@ -86851,15 +93957,18 @@ var ts; return getExportAssignmentExport(parent); } // If we are in `export = class A {};` (or `export = class A {};`) at `A`, `parent.parent` is the export assignment. - else if (ts.isExportAssignment(parent.parent)) { - return getExportAssignmentExport(parent.parent); + else if (ts.isExportAssignment(grandParent)) { + return getExportAssignmentExport(grandParent); } // Similar for `module.exports =` and `exports.A =`. else if (ts.isBinaryExpression(parent)) { return getSpecialPropertyExport(parent, /*useLhsSymbol*/ true); } - else if (ts.isBinaryExpression(parent.parent)) { - return getSpecialPropertyExport(parent.parent, /*useLhsSymbol*/ true); + else if (ts.isBinaryExpression(grandParent)) { + return getSpecialPropertyExport(grandParent, /*useLhsSymbol*/ true); + } + else if (ts.isJSDocTypedefTag(parent)) { + return exportInfo(symbol, 0 /* Named */); } } function getExportAssignmentExport(ex) { @@ -86905,7 +94014,7 @@ var ts; // If the import has a different name than the export, do not continue searching. // If `importedName` is undefined, do continue searching as the export is anonymous. // (All imports returned from this function will be ignored anyway if we are in rename and this is a not a named export.) - var importedName = symbolName(importedSymbol); + var importedName = ts.symbolEscapedNameNoDefault(importedSymbol); if (importedName === undefined || importedName === "default" /* Default */ || importedName === symbol.escapedName) { return __assign({ kind: 0 /* Import */, symbol: importedSymbol }, isImport); } @@ -86931,15 +94040,18 @@ var ts; else if (ts.isBinaryExpression(decl)) { // `module.exports = class {}` return ts.Debug.assertDefined(decl.right.symbol); } + else if (ts.isSourceFile(decl)) { // json module + return ts.Debug.assertDefined(decl.symbol); + } return ts.Debug.fail(); } // If a reference is a class expression, the exported node would be its parent. // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent, node) { - if (parent.kind === 230 /* VariableDeclaration */) { + if (parent.kind === 235 /* VariableDeclaration */) { var p = parent; return p.name !== node ? undefined : - p.parent.kind === 267 /* CatchClause */ ? undefined : p.parent.parent.kind === 212 /* VariableStatement */ ? p.parent.parent : undefined; + p.parent.kind === 272 /* CatchClause */ ? undefined : p.parent.parent.kind === 217 /* VariableStatement */ ? p.parent.parent : undefined; } else { return parent; @@ -86948,15 +94060,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 246 /* ImportSpecifier */: + case 251 /* ImportSpecifier */: // For a rename import `{ foo as bar }`, don't search for the imported symbol. Just find local uses of `bar`. return parent.propertyName ? undefined : { isNamedImport: true }; - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -86972,15 +94084,6 @@ var ts; return ts.isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol: exportingModuleSymbol, exportKind: exportKind } : undefined; } FindAllReferences.getExportInfo = getExportInfo; - function symbolName(symbol) { - if (symbol.escapedName !== "default" /* Default */) { - return symbol.escapedName; - } - return ts.forEach(symbol.declarations, function (decl) { - var name = ts.getNameOfDeclaration(decl); - return name && name.kind === 71 /* Identifier */ && name.escapedText; - }); - } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. @@ -86998,65 +94101,65 @@ var ts; return checker.getMergedSymbol(getSourceFileLikeForImportDeclaration(importer).symbol); } function getSourceFileLikeForImportDeclaration(node) { - if (node.kind === 185 /* CallExpression */) { + if (node.kind === 189 /* CallExpression */) { return node.getSourceFile(); } var parent = node.parent; - if (parent.kind === 272 /* SourceFile */) { + if (parent.kind === 277 /* SourceFile */) { return parent; } - ts.Debug.assert(parent.kind === 238 /* ModuleBlock */); + ts.Debug.assert(parent.kind === 243 /* ModuleBlock */); return ts.cast(parent.parent, isAmbientModuleDeclaration); } function isAmbientModuleDeclaration(node) { - return node.kind === 237 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; + return node.kind === 242 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */; } - function isExternalModuleImportEquals(_a) { - var moduleReference = _a.moduleReference; - return moduleReference.kind === 252 /* ExternalModuleReference */ && moduleReference.expression.kind === 9 /* StringLiteral */; + function isExternalModuleImportEquals(eq) { + return eq.moduleReference.kind === 257 /* ExternalModuleReference */ && eq.moduleReference.expression.kind === 9 /* StringLiteral */; } })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { var FindAllReferences; (function (FindAllReferences) { function nodeEntry(node, isInString) { - return { type: "node", node: node, isInString: isInString }; + return { type: "node", node: node.name || node, isInString: isInString }; } FindAllReferences.nodeEntry = nodeEntry; function findReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, /*options*/ {}); + var node = ts.getTouchingPropertyName(sourceFile, position); + var referencedSymbols = FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken); var checker = program.getTypeChecker(); return !referencedSymbols || !referencedSymbols.length ? undefined : ts.mapDefined(referencedSymbols, function (_a) { var definition = _a.definition, references = _a.references; // Only include referenced symbols that have a valid definition. - return definition && { definition: definitionToReferencedSymbolDefinitionInfo(definition, checker, node), references: references.map(toReferenceEntry) }; + return definition && { + definition: checker.runWithCancellationToken(cancellationToken, function (checker) { return definitionToReferencedSymbolDefinitionInfo(definition, checker, node); }), + references: references.map(toReferenceEntry) + }; }); } FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { - // A node in a JSDoc comment can't have an implementation anyway. - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); + var node = ts.getTouchingPropertyName(sourceFile, position); var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { - if (node.kind === 272 /* SourceFile */) { + if (node.kind === 277 /* SourceFile */) { return undefined; } var checker = program.getTypeChecker(); // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). - if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var result_4 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_4.push(nodeEntry(node)); }); - return result_4; + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + var result_6 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_6.push(nodeEntry(node)); }); + return result_6; } else if (node.kind === 97 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -87069,14 +94172,14 @@ var ts; return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } - function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + function findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options) { return ts.map(flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function flattenEntries(referenceSymbols) { @@ -87088,8 +94191,8 @@ var ts; case "symbol": { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; + var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; } case "label": { var node_3 = def.node; @@ -87097,13 +94200,13 @@ var ts; } case "keyword": { var node_4 = def.node; - var name_5 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; + var name_4 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; } case "this": { var node_5 = def.node; var symbol = checker.getSymbolAtLocation(node_5); - var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts; + var displayParts_2 = symbol && ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, node_5.getSourceFile(), ts.getContainerNode(node_5), node_5).displayParts || [ts.textPart("this")]; return { node: node_5, name: "this", kind: "var" /* variableElement */, displayParts: displayParts_2 }; } case "string": { @@ -87116,15 +94219,7 @@ var ts; })(); var node = info.node, name = info.name, kind = info.kind, displayParts = info.displayParts; var sourceFile = node.getSourceFile(); - return { - containerKind: "" /* unknown */, - containerName: "", - fileName: sourceFile.fileName, - kind: kind, - name: name, - textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: displayParts - }; + return { containerKind: "" /* unknown */, containerName: "", fileName: sourceFile.fileName, kind: kind, name: name, textSpan: getTextSpan(ts.isComputedPropertyName(node) ? node.expression : node, sourceFile), displayParts: displayParts }; } function getDefinitionKindAndDisplayParts(symbol, checker, node) { var meaning = FindAllReferences.Core.getIntersectingMeaningFromDeclarations(node, symbol); @@ -87137,20 +94232,22 @@ var ts; return { textSpan: entry.textSpan, fileName: entry.fileName, isWriteAccess: false, isDefinition: false }; } var node = entry.node, isInString = entry.isInString; + var sourceFile = node.getSourceFile(); return { - fileName: node.getSourceFile().fileName, - textSpan: getTextSpan(node), + fileName: sourceFile.fileName, + textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 79 /* DefaultKeyword */ || ts.isAnyDeclarationName(node) || ts.isLiteralComputedPropertyDeclarationName(node), - isInString: isInString + isInString: isInString, }; } function toImplementationLocation(entry, checker) { if (entry.type === "node") { var node = entry.node; - return __assign({ textSpan: getTextSpan(node), fileName: node.getSourceFile().fileName }, implementationKindDisplayParts(node, checker)); + var sourceFile = node.getSourceFile(); + return __assign({ textSpan: getTextSpan(node, sourceFile), fileName: sourceFile.fileName }, implementationKindDisplayParts(node, checker)); } else { var textSpan = entry.textSpan, fileName = entry.fileName; @@ -87162,13 +94259,13 @@ var ts; if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); } - else if (node.kind === 182 /* ObjectLiteralExpression */) { + else if (node.kind === 186 /* ObjectLiteralExpression */) { return { kind: "interface" /* interfaceElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("object literal"), ts.punctuationPart(20 /* CloseParenToken */)] }; } - else if (node.kind === 203 /* ClassExpression */) { + else if (node.kind === 207 /* ClassExpression */) { return { kind: "local class" /* localClassElement */, displayParts: [ts.punctuationPart(19 /* OpenParenToken */), ts.textPart("anonymous local class"), ts.punctuationPart(20 /* CloseParenToken */)] @@ -87180,22 +94277,22 @@ var ts; } function toHighlightSpan(entry) { if (entry.type === "span") { - var fileName_1 = entry.fileName, textSpan = entry.textSpan; - return { fileName: fileName_1, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; + var fileName = entry.fileName, textSpan = entry.textSpan; + return { fileName: fileName, span: { textSpan: textSpan, kind: "reference" /* reference */ } }; } var node = entry.node, isInString = entry.isInString; - var fileName = entry.node.getSourceFile().fileName; + var sourceFile = node.getSourceFile(); var writeAccess = isWriteAccessForReference(node); var span = { - textSpan: getTextSpan(node), + textSpan: getTextSpan(node, sourceFile), kind: writeAccess ? "writtenReference" /* writtenReference */ : "reference" /* reference */, isInString: isInString }; - return { fileName: fileName, span: span }; + return { fileName: sourceFile.fileName, span: span }; } FindAllReferences.toHighlightSpan = toHighlightSpan; - function getTextSpan(node) { - var start = node.getStart(); + function getTextSpan(node, sourceFile) { + var start = node.getStart(sourceFile); var end = node.getEnd(); if (node.kind === 9 /* StringLiteral */) { start += 1; @@ -87217,11 +94314,13 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options, sourceFilesSet) { if (options === void 0) { options = {}; } + if (sourceFilesSet === void 0) { sourceFilesSet = ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }); } if (ts.isSourceFile(node)) { var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); - return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); + var moduleSymbol = reference && program.getTypeChecker().getMergedSymbol(reference.file.symbol); + return moduleSymbol && getReferencedSymbolsForModule(program, moduleSymbol, /*excludeImportTypeOfExportEquals*/ false, sourceFiles, sourceFilesSet); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -87236,32 +94335,37 @@ var ts; // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } - if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { - return getReferencedSymbolsForModule(program, symbol, sourceFiles); + var moduleReferences = ts.emptyArray; + var moduleSourceFile = isModuleSymbol(symbol); + var referencedNode = node; + if (moduleSourceFile) { + var exportEquals = symbol.exports.get("export=" /* ExportEquals */); + // If !!exportEquals, we're about to add references to `import("mod")` anyway, so don't double-count them. + moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) + return moduleReferences; + // Continue to get references to 'export ='. + symbol = ts.skipAlias(exportEquals, checker); + referencedNode = undefined; } - return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); + return ts.concatenate(moduleReferences, getReferencedSymbolsForSymbol(symbol, referencedNode, sourceFiles, sourceFilesSet, checker, cancellationToken, options)); } Core.getReferencedSymbolsForNode = getReferencedSymbolsForNode; - function isModuleReferenceLocation(node) { - if (!ts.isStringLiteralLike(node)) { - return false; - } - switch (node.parent.kind) { - case 237 /* ModuleDeclaration */: - case 252 /* ExternalModuleReference */: - case 242 /* ImportDeclaration */: - case 248 /* ExportDeclaration */: - return true; - case 185 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); - default: - return false; - } + function isModuleSymbol(symbol) { + return symbol.flags & 1536 /* Module */ ? ts.find(symbol.declarations, ts.isSourceFile) : undefined; } - function getReferencedSymbolsForModule(program, symbol, sourceFiles) { + function getReferencedSymbolsForModule(program, symbol, excludeImportTypeOfExportEquals, sourceFiles, sourceFilesSet) { ts.Debug.assert(!!symbol.valueDeclaration); - var references = FindAllReferences.findModuleReferences(program, sourceFiles, symbol).map(function (reference) { + var references = ts.mapDefined(FindAllReferences.findModuleReferences(program, sourceFiles, symbol), function (reference) { if (reference.kind === "import") { + var parent = reference.literal.parent; + if (ts.isLiteralTypeNode(parent)) { + var importType = ts.cast(parent.parent, ts.isImportTypeNode); + if (excludeImportTypeOfExportEquals && !importType.qualifier) { + return undefined; + } + } + // import("foo") with no qualifier will reference the `export =` of the module, which may be referenced anyway. return { type: "node", node: reference.literal }; } else { @@ -87275,17 +94379,20 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var decl = _a[_i]; switch (decl.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case 237 /* ModuleDeclaration */: - references.push({ type: "node", node: decl.name }); + case 242 /* ModuleDeclaration */: + if (sourceFilesSet.has(decl.getSourceFile().fileName)) { + references.push({ type: "node", node: decl.name }); + } break; default: + // This may be merged with something. ts.Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); } } - return [{ definition: { type: "symbol", symbol: symbol }, references: references }]; + return references.length ? [{ definition: { type: "symbol", symbol: symbol }, references: references }] : ts.emptyArray; } /** getReferencedSymbols for special node kinds. */ function getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken) { @@ -87312,23 +94419,23 @@ var ts; return undefined; } /** Core find-all-references algorithm for a normal symbol. */ - function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; + function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { + symbol = node && skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) || symbol; // Compute the meaning from the location and the symbol it references - var searchMeaning = getIntersectingMeaningFromDeclarations(node, symbol); + var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; - var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); - if (node.kind === 79 /* DefaultKeyword */) { + var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); + if (node && node.kind === 79 /* DefaultKeyword */) { addReference(node, symbol, state); searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: populateSearchSymbolSet(symbol, node, checker, options.implementations) }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state); + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); } else { // Global search @@ -87369,7 +94476,6 @@ var ts; return ts.firstDefined(symbol.declarations, function (decl) { if (!decl.parent) { // Assertions for GH#21814. We should be handling SourceFile symbols in `getReferencedSymbolsForModule` instead of getting here. - ts.Debug.assert(decl.kind === 272 /* SourceFile */); ts.Debug.fail("Unexpected symbol at " + ts.Debug.showSyntaxKind(node) + ": " + ts.Debug.showSymbol(symbol)); } return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) @@ -87388,10 +94494,11 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, + function State(sourceFiles, sourceFilesSet, /** True if we're searching for constructor references. */ specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; + this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; this.checker = checker; this.cancellationToken = cancellationToken; @@ -87423,31 +94530,27 @@ var ts; this.symbolIdToReferences = []; // Source file ID → symbol ID → Whether the symbol has been searched for in the source file. this.sourceFileToSeenSymbols = []; - this.includedSourceFiles = ts.arrayToSet(sourceFiles, function (s) { return s.fileName; }); } State.prototype.includesSourceFile = function (sourceFile) { - return this.includedSourceFiles.has(sourceFile.fileName); + return this.sourceFilesSet.has(sourceFile.fileName); }; /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ State.prototype.getImportSearches = function (exportSymbol, exportInfo) { if (!this.importTracker) - this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.checker, this.cancellationToken); - return this.importTracker(exportSymbol, exportInfo, this.options.isForRename); + this.importTracker = FindAllReferences.createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + return this.importTracker(exportSymbol, exportInfo, !!this.options.isForRename); }; - /** @param allSearchSymbols set of additinal symbols for use by `includes`. */ + /** @param allSearchSymbols set of additional symbols for use by `includes`. */ State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form // here appears to be intentional). - var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, allSearchSymbols = searchOptions.allSearchSymbols; + var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? [symbol] : _b; var escapedText = ts.escapeLeadingUnderscores(text); - var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); - return { - symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, - includes: function (referenceSymbol) { return allSearchSymbols ? ts.contains(allSearchSymbols, referenceSymbol) : referenceSymbol === symbol; }, - }; + var parents = this.options.implementations && location ? getParentSymbolsOfPropertyAccess(location, symbol, this.checker) : undefined; + return { symbol: symbol, comingFrom: comingFrom, text: text, escapedText: escapedText, parents: parents, allSearchSymbols: allSearchSymbols, includes: function (sym) { return ts.contains(allSearchSymbols, sym); } }; }; /** * Callback to add references for a particular searched symbol. @@ -87470,11 +94573,15 @@ var ts; }); }; /** Returns `true` the first time we search for a symbol in a file and `false` afterwards. */ - State.prototype.markSearchedSymbol = function (sourceFile, symbol) { + State.prototype.markSearchedSymbols = function (sourceFile, symbols) { var sourceId = ts.getNodeId(sourceFile); - var symbolId = ts.getSymbolId(symbol); - var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = []); - return !seenSymbols[symbolId] && (seenSymbols[symbolId] = true); + var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = ts.createMap()); + var anyNewSymbols = false; + for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { + var sym = symbols_4[_i]; + anyNewSymbols = ts.addToSeen(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; + } + return anyNewSymbols; }; return State; }()); @@ -87486,7 +94593,8 @@ var ts; var addRef = state.referenceAdder(exportSymbol); for (var _i = 0, singleReferences_1 = singleReferences; _i < singleReferences_1.length; _i++) { var singleRef = singleReferences_1[_i]; - addRef(singleRef); + if (shouldAddSingleReference(singleRef, state)) + addRef(singleRef); } } // For each import, find all references to that import in its source file. @@ -87515,14 +94623,42 @@ var ts; } } } + function eachExportReference(sourceFiles, checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName, isDefaultExport, cb) { + var importTracker = FindAllReferences.createImportTracker(sourceFiles, ts.arrayToSet(sourceFiles, function (f) { return f.fileName; }), checker, cancellationToken); + var _a = importTracker(exportSymbol, { exportKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */, exportingModuleSymbol: exportingModuleSymbol }, /*isForRename*/ false), importSearches = _a.importSearches, indirectUsers = _a.indirectUsers; + for (var _i = 0, importSearches_2 = importSearches; _i < importSearches_2.length; _i++) { + var importLocation = importSearches_2[_i][0]; + cb(importLocation); + } + for (var _b = 0, indirectUsers_2 = indirectUsers; _b < indirectUsers_2.length; _b++) { + var indirectUser = indirectUsers_2[_b]; + for (var _c = 0, _d = getPossibleSymbolReferenceNodes(indirectUser, isDefaultExport ? "default" : exportName); _c < _d.length; _c++) { + var node = _d[_c]; + if (ts.isIdentifier(node) && checker.getSymbolAtLocation(node) === exportSymbol) { + cb(node); + } + } + } + } + Core.eachExportReference = eachExportReference; + function shouldAddSingleReference(singleRef, state) { + if (!hasMatchingMeaning(singleRef, state)) + return false; + if (!state.options.isForRename) + return true; + // Don't rename an import type `import("./module-name")` when renaming `name` in `export = name;` + if (!ts.isIdentifier(singleRef)) + return false; + // At `default` in `import { default as x }` or `export { default as x }`, do add a reference, but do not rename. + return !((ts.isExportSpecifier(singleRef.parent) || ts.isImportSpecifier(singleRef.parent)) && singleRef.escapedText === "default" /* Default */); + } // Go to the symbol we imported from and find references for it. function searchForImportedSymbol(symbol, state) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; var exportingFile = declaration.getSourceFile(); - if (state.includesSourceFile(exportingFile)) { - getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state); - } + // Need to search in the file even if it's not in the search-file set, because it might export the symbol. + getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); } } /** Search for all occurences of an identifier in a source file (and filter out the ones that match). */ @@ -87532,29 +94668,22 @@ var ts; } } function getPropertySymbolOfDestructuringAssignment(location, checker) { - return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) && - checker.getPropertySymbolOfDestructuringAssignment(location); + return ts.isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) + ? checker.getPropertySymbolOfDestructuringAssignment(location) + : undefined; } function getObjectBindingElementWithoutPropertyName(symbol) { - var bindingElement = ts.getDeclarationOfKind(symbol, 180 /* BindingElement */); + var bindingElement = ts.getDeclarationOfKind(symbol, 184 /* BindingElement */); if (bindingElement && - bindingElement.parent.kind === 178 /* ObjectBindingPattern */ && + bindingElement.parent.kind === 182 /* ObjectBindingPattern */ && + ts.isIdentifier(bindingElement.name) && !bindingElement.propertyName) { return bindingElement; } } function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { var bindingElement = getObjectBindingElementWithoutPropertyName(symbol); - if (!bindingElement) - return undefined; - var typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); - var propSymbol = typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); - if (propSymbol && propSymbol.flags & 98304 /* Accessor */) { - // See GH#16922 - ts.Debug.assert(!!(propSymbol.flags & 33554432 /* Transient */)); - return propSymbol.target; - } - return propSymbol; + return bindingElement && ts.getPropertySymbolFromBindingElement(checker, bindingElement); } /** * Determines the smallest scope in which a symbol may have named references. @@ -87568,7 +94697,7 @@ var ts; // If this is the symbol of a named function expression or named class expression, // then named references are limited to its own scope. var declarations = symbol.declarations, flags = symbol.flags, parent = symbol.parent, valueDeclaration = symbol.valueDeclaration; - if (valueDeclaration && (valueDeclaration.kind === 190 /* FunctionExpression */ || valueDeclaration.kind === 203 /* ClassExpression */)) { + if (valueDeclaration && (valueDeclaration.kind === 194 /* FunctionExpression */ || valueDeclaration.kind === 207 /* ClassExpression */)) { return valueDeclaration; } if (!declarations) { @@ -87578,7 +94707,7 @@ var ts; if (flags & (4 /* Property */ | 8192 /* Method */)) { var privateDeclaration = ts.find(declarations, function (d) { return ts.hasModifier(d, 8 /* Private */); }); if (privateDeclaration) { - return ts.getAncestor(privateDeclaration, 233 /* ClassDeclaration */); + return ts.getAncestor(privateDeclaration, 238 /* ClassDeclaration */); } // Else this is a public property and could be accessed from anywhere. return undefined; @@ -87596,18 +94725,18 @@ var ts; - But if the parent has `export as namespace`, the symbol is globally visible through that namespace. */ var exposedByParent = parent && !(symbol.flags & 262144 /* TypeParameter */); - if (exposedByParent && !((parent.flags & 1536 /* Module */) && ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { + if (exposedByParent && !(ts.isExternalModuleSymbol(parent) && !parent.globalExports)) { return undefined; } var scope; - for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { - var declaration = declarations_9[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var declaration = declarations_10[_i]; var container = ts.getContainerNode(declaration); if (scope && scope !== container) { // Different declarations have different containers, bail out return undefined; } - if (!container || container.kind === 272 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { + if (!container || container.kind === 277 /* SourceFile */ && !ts.isExternalOrCommonJsModule(container)) { // This is a global variable and not an external module, any declaration defined // within this scope is visible outside the file return undefined; @@ -87620,19 +94749,58 @@ var ts; // declare module "a" { export type T = number; } // declare module "b" { import { T } from "a"; export const x: T; } // So we must search the whole source file. (Because we will mark the source file as seen, we we won't return to it when searching for imports.) - return exposedByParent ? scope.getSourceFile() : scope; + return exposedByParent ? scope.getSourceFile() : scope; // TODO: GH#18217 } /** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */ function isSymbolReferencedInFile(definition, checker, sourceFile) { - var symbol = checker.getSymbolAtLocation(definition); - if (!symbol) - return true; // Be lenient with invalid code. - return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(function (position) { - var token = ts.tryCast(ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), ts.isIdentifier); - return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol; - }); + return eachSymbolReferenceInFile(definition, checker, sourceFile, function () { return true; }) || false; } Core.isSymbolReferencedInFile = isSymbolReferencedInFile; + function eachSymbolReferenceInFile(definition, checker, sourceFile, cb) { + var symbol = checker.getSymbolAtLocation(definition); + if (!symbol) + return undefined; + for (var _i = 0, _a = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _i < _a.length; _i++) { + var token = _a[_i]; + if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) + continue; + var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + if (referenceSymbol === symbol + || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol + || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { + var res = cb(token); + if (res) + return res; + } + } + } + Core.eachSymbolReferenceInFile = eachSymbolReferenceInFile; + function eachSignatureCall(signature, sourceFiles, checker, cb) { + if (!signature.name || !ts.isIdentifier(signature.name)) + return; + var symbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(signature.name)); + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; + for (var _a = 0, _b = getPossibleSymbolReferenceNodes(sourceFile, symbol.name); _a < _b.length; _a++) { + var name = _b[_a]; + if (!ts.isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) + continue; + var called = ts.climbPastPropertyAccess(name); + var call = called.parent; + if (!ts.isCallExpression(call) || call.expression !== called) + continue; + var referenceSymbol = checker.getSymbolAtLocation(name); + if (referenceSymbol && checker.getRootSymbols(referenceSymbol).some(function (s) { return s === symbol; })) { + cb(call); + } + } + } + } + Core.eachSignatureCall = eachSignatureCall; + function getPossibleSymbolReferenceNodes(sourceFile, symbolName, container) { + if (container === void 0) { container = sourceFile; } + return getPossibleSymbolReferencePositions(sourceFile, symbolName, container).map(function (pos) { return ts.getTouchingPropertyName(sourceFile, pos); }); + } function getPossibleSymbolReferencePositions(sourceFile, symbolName, container) { if (container === void 0) { container = sourceFile; } var positions = []; @@ -87665,10 +94833,9 @@ var ts; function getLabelReferencesInNode(container, targetLabel) { var sourceFile = container.getSourceFile(); var labelName = targetLabel.text; - var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, labelName, container), function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), function (node) { // Only pick labels that are either the target label, or have a target that is the target label - return node && (node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel)) ? FindAllReferences.nodeEntry(node) : undefined; + return node === targetLabel || (ts.isJumpStatementTarget(node) && ts.getTargetLabel(node, labelName) === targetLabel) ? FindAllReferences.nodeEntry(node) : undefined; }); return [{ definition: { type: "label", node: targetLabel }, references: references }]; } @@ -87677,9 +94844,11 @@ var ts; switch (node.kind) { case 71 /* Identifier */: return node.text.length === searchSymbolName.length; - case 9 /* StringLiteral */: - return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) && - node.text.length === searchSymbolName.length; + case 9 /* StringLiteral */: { + var str = node; + return (ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) && + str.text.length === searchSymbolName.length; + } case 8 /* NumericLiteral */: return ts.isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; case 79 /* DefaultKeyword */: @@ -87691,33 +94860,36 @@ var ts; function getAllReferencesForKeyword(sourceFiles, keywordKind, cancellationToken) { var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (position) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, ts.tokenToString(keywordKind), sourceFile), function (referenceLocation) { return referenceLocation.kind === keywordKind ? FindAllReferences.nodeEntry(referenceLocation) : undefined; }); }); return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references: references }] : undefined; } - function getReferencesInSourceFile(sourceFile, search, state) { + function getReferencesInSourceFile(sourceFile, search, state, addReferencesHere) { + if (addReferencesHere === void 0) { addReferencesHere = true; } state.cancellationToken.throwIfCancellationRequested(); - return getReferencesInContainer(sourceFile, sourceFile, search, state); + return getReferencesInContainer(sourceFile, sourceFile, search, state, addReferencesHere); } /** * Search within node "container" for references for a search value, where the search value is defined as a * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). * searchLocation: a node where the search value */ - function getReferencesInContainer(container, sourceFile, search, state) { - if (!state.markSearchedSymbol(sourceFile, search.symbol)) { + function getReferencesInContainer(container, sourceFile, search, state, addReferencesHere) { + if (!state.markSearchedSymbols(sourceFile, search.allSearchSymbols)) { return; } for (var _i = 0, _a = getPossibleSymbolReferencePositions(sourceFile, search.text, container); _i < _a.length; _i++) { var position = _a[_i]; - getReferencesAtLocation(sourceFile, position, search, state); + getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere); } } - function getReferencesAtLocation(sourceFile, position, search, state) { - var referenceLocation = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + function hasMatchingMeaning(referenceLocation, state) { + return !!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning); + } + function getReferencesAtLocation(sourceFile, position, search, state, addReferencesHere) { + var referenceLocation = ts.getTouchingPropertyName(sourceFile, position); if (!isValidReferencePosition(referenceLocation, search.text)) { // This wasn't the start of a token. Check to see if it might be a // match in a comment or string if that's what the caller is asking @@ -87731,9 +94903,8 @@ var ts; } return; } - if (!(ts.getMeaningFromLocation(referenceLocation) & state.searchMeaning)) { + if (!hasMatchingMeaning(referenceLocation, state)) return; - } var referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -87745,7 +94916,7 @@ var ts; } if (ts.isExportSpecifier(parent)) { ts.Debug.assert(referenceLocation.kind === 71 /* Identifier */); - getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state); + getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent, search, state, addReferencesHere); return; } var relatedSymbol = getRelatedSymbol(search, referenceSymbol, referenceLocation, state); @@ -87755,7 +94926,8 @@ var ts; } switch (state.specialSearchKind) { case 0 /* None */: - addReference(referenceLocation, relatedSymbol, state); + if (addReferencesHere) + addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -87768,7 +94940,7 @@ var ts; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } - function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state) { + function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere) { var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -87776,7 +94948,10 @@ var ts; return; } if (!propertyName) { - addRef(); + // Don't rename at `export { default } from "m";`. (but do continue to search for imports of the re-export) + if (!(state.options.isForRename && name.escapedText === "default" /* Default */)) { + addRef(); + } } else if (referenceLocation === propertyName) { // For `export { foo as bar } from "baz"`, "`foo`" will be added from the singleReferences for import searches of the original export. @@ -87784,7 +94959,7 @@ var ts; if (!exportDeclaration.moduleSpecifier) { addRef(); } - if (!state.options.isForRename && state.markSeenReExportRHS(name)) { + if (addReferencesHere && !state.options.isForRename && state.markSeenReExportRHS(name)) { addReference(name, referenceSymbol, state); } } @@ -87797,7 +94972,8 @@ var ts; if (!(referenceLocation === propertyName && state.options.isForRename)) { var exportKind = referenceLocation.originalKeywordKind === 79 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); - ts.Debug.assert(!!exportInfo); + if (!exportInfo) + return ts.Debug.fail(); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. @@ -87807,7 +94983,8 @@ var ts; searchForImportedSymbol(imported, state); } function addRef() { - addReference(referenceLocation, localSymbol, state); + if (addReferencesHere) + addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -87844,6 +95021,7 @@ var ts; function getReferenceForShorthandProperty(_a, search, state) { var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); + var name = valueDeclaration && ts.getNameOfDeclaration(valueDeclaration); /* * Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment * has two meanings: property name and property value. Therefore when we do findAllReference at the position where @@ -87851,8 +95029,8 @@ var ts; * the position in short-hand property assignment excluding property accessing. However, if we do findAllReference at the * position of property accessing, the referenceEntry of such position will be handled in the first case. */ - if (!(flags & 33554432 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, state); + if (!(flags & 33554432 /* Transient */) && name && search.includes(shorthandValueSymbol)) { + addReference(name, shorthandValueSymbol, state); } } function addReference(referenceLocation, relatedSymbol, state) { @@ -87885,31 +95063,28 @@ var ts; } function addClassStaticThisReferences(referenceLocation, search, state) { addReference(referenceLocation, search.symbol, state); - if (!state.options.isForRename && ts.isClassLike(referenceLocation.parent)) { - ts.Debug.assert(referenceLocation.parent.name === referenceLocation); - // This is the class declaration. - addStaticThisReferences(referenceLocation.parent, state.referenceAdder(search.symbol)); - } - } - function addStaticThisReferences(classLike, pusher) { + var classLike = referenceLocation.parent; + if (state.options.isForRename || !ts.isClassLike(classLike)) + return; + ts.Debug.assert(classLike.name === referenceLocation); + var addRef = state.referenceAdder(search.symbol); for (var _i = 0, _a = classLike.members; _i < _a.length; _i++) { var member = _a[_i]; if (!(ts.isMethodOrAccessor(member) && ts.hasModifier(member, 32 /* Static */))) { continue; } - member.body.forEachChild(function cb(node) { - if (node.kind === 99 /* ThisKeyword */) { - pusher(node); - } - else if (!ts.isFunctionLike(node)) { - node.forEachChild(cb); - } - }); + if (member.body) { + member.body.forEachChild(function cb(node) { + if (node.kind === 99 /* ThisKeyword */) { + addRef(node); + } + else if (!ts.isFunctionLike(node) && !ts.isClassLike(node)) { + node.forEachChild(cb); + } + }); + } } } - function getPropertyAccessExpressionFromRightHandSide(node) { - return ts.isRightSideOfPropertyAccess(node) && node.parent; - } /** * `classSymbol` is the class where the constructor was defined. * Reference the constructor and all calls to `new this()`. @@ -87918,12 +95093,12 @@ var ts; for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { var decl = _a[_i]; var ctrKeyword = ts.findChildOfKind(decl, 123 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 154 /* Constructor */ && !!ctrKeyword); + ts.Debug.assert(decl.kind === 155 /* Constructor */ && !!ctrKeyword); addNode(ctrKeyword); } classSymbol.exports.forEach(function (member) { var decl = member.valueDeclaration; - if (decl && decl.kind === 153 /* MethodDeclaration */) { + if (decl && decl.kind === 154 /* MethodDeclaration */) { var body = decl.body; if (body) { forEachDescendantOfKind(body, 99 /* ThisKeyword */, function (thisKeyword) { @@ -87937,14 +95112,13 @@ var ts; } /** Find references to `super` in the constructor of an extending class. */ function findSuperConstructorAccesses(cls, addNode) { - var symbol = cls.symbol; - var ctr = symbol.members.get("__constructor" /* Constructor */); + var ctr = cls.symbol.members.get("__constructor" /* Constructor */); if (!ctr) { return; } for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - ts.Debug.assert(decl.kind === 154 /* Constructor */); + ts.Debug.assert(decl.kind === 155 /* Constructor */); var body = decl.body; if (body) { forEachDescendantOfKind(body, 97 /* SuperKeyword */, function (node) { @@ -87958,13 +95132,13 @@ var ts; function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { - addReference(refNode.parent); + addReference(refNode); return; } if (refNode.kind !== 71 /* Identifier */) { return; } - if (refNode.parent.kind === 269 /* ShorthandPropertyAssignment */) { + if (refNode.parent.kind === 274 /* ShorthandPropertyAssignment */) { // Go ahead and dereference the shorthand assignment by going to its definition getReferenceEntriesForShorthandPropertyAssignment(refNode, state.checker, addReference); } @@ -87975,78 +95149,50 @@ var ts; return; } // If we got a type reference, try and see if the reference applies to any expressions that can implement an interface - var containingTypeReference = getContainingTypeReference(refNode); - if (containingTypeReference && state.markSeenContainingTypeReference(containingTypeReference)) { - var parent = containingTypeReference.parent; - if (ts.hasType(parent) && parent.type === containingTypeReference && ts.hasInitializer(parent) && isImplementationExpression(parent.initializer)) { - addReference(parent.initializer); + // Find the first node whose parent isn't a type node -- i.e., the highest type node. + var typeNode = ts.findAncestor(refNode, function (a) { return !ts.isQualifiedName(a.parent) && !ts.isTypeNode(a.parent) && !ts.isTypeElement(a.parent); }); + var typeHavingNode = typeNode.parent; + if (ts.hasType(typeHavingNode) && typeHavingNode.type === typeNode && state.markSeenContainingTypeReference(typeHavingNode)) { + if (ts.hasInitializer(typeHavingNode)) { + addIfImplementation(typeHavingNode.initializer); } - else if (ts.isFunctionLike(parent) && parent.type === containingTypeReference && parent.body) { - var body = parent.body; - if (body.kind === 211 /* Block */) { + else if (ts.isFunctionLike(typeHavingNode) && typeHavingNode.body) { + var body = typeHavingNode.body; + if (body.kind === 216 /* Block */) { ts.forEachReturnStatement(body, function (returnStatement) { - if (returnStatement.expression && isImplementationExpression(returnStatement.expression)) { - addReference(returnStatement.expression); - } + if (returnStatement.expression) + addIfImplementation(returnStatement.expression); }); } - else if (isImplementationExpression(body)) { - addReference(body); + else { + addIfImplementation(body); } } - else if (ts.isAssertionExpression(parent) && isImplementationExpression(parent.expression)) { - addReference(parent.expression); + else if (ts.isAssertionExpression(typeHavingNode)) { + addIfImplementation(typeHavingNode.expression); } } - } - function getSymbolsForClassAndInterfaceComponents(type, result) { - if (result === void 0) { result = []; } - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var componentType = _a[_i]; - if (componentType.symbol && componentType.symbol.getFlags() & (32 /* Class */ | 64 /* Interface */)) { - result.push(componentType.symbol); - } - if (componentType.getFlags() & 393216 /* UnionOrIntersection */) { - getSymbolsForClassAndInterfaceComponents(componentType, result); - } + function addIfImplementation(e) { + if (isImplementationExpression(e)) + addReference(e); } - return result; - } - function getContainingTypeReference(node) { - var topLevelTypeReference; - while (node) { - if (ts.isTypeNode(node)) { - topLevelTypeReference = node; - } - node = node.parent; - } - return topLevelTypeReference; } function getContainingClassIfInHeritageClause(node) { - if (node && node.parent) { - if (node.kind === 205 /* ExpressionWithTypeArguments */ - && node.parent.kind === 266 /* HeritageClause */ - && ts.isClassLike(node.parent.parent)) { - return node.parent.parent; - } - else if (node.kind === 71 /* Identifier */ || node.kind === 183 /* PropertyAccessExpression */) { - return getContainingClassIfInHeritageClause(node.parent); - } - } - return undefined; + return ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) ? getContainingClassIfInHeritageClause(node.parent) + : ts.isExpressionWithTypeArguments(node) ? ts.tryCast(node.parent.parent, ts.isClassLike) : undefined; } /** * Returns true if this is an expression that can be considered an implementation */ function isImplementationExpression(node) { switch (node.kind) { - case 189 /* ParenthesizedExpression */: + case 193 /* ParenthesizedExpression */: return isImplementationExpression(node.expression); - case 191 /* ArrowFunction */: - case 190 /* FunctionExpression */: - case 182 /* ObjectLiteralExpression */: - case 203 /* ClassExpression */: - case 181 /* ArrayLiteralExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 186 /* ObjectLiteralExpression */: + case 207 /* ClassExpression */: + case 185 /* ArrayLiteralExpression */: return true; default: return false; @@ -88067,58 +95213,29 @@ var ts; * distinction between structurally compatible implementations and explicit implementations, so we * must use the AST. * - * @param child A class or interface Symbol + * @param symbol A class or interface Symbol * @param parent Another class or interface Symbol * @param cachedResults A map of symbol id pairs (i.e. "child,parent") to booleans indicating previous results */ - function explicitlyInheritsFrom(child, parent, cachedResults, checker) { - var parentIsInterface = parent.getFlags() & 64 /* Interface */; - return searchHierarchy(child); - function searchHierarchy(symbol) { - if (symbol === parent) { - return true; - } - var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); - var cached = cachedResults.get(key); - if (cached !== undefined) { - return cached; - } - // Set the key so that we don't infinitely recurse - cachedResults.set(key, false); - var inherits = ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - if (parentIsInterface) { - var interfaceReferences = ts.getClassImplementsHeritageClauseElements(declaration); - if (interfaceReferences) { - for (var _i = 0, interfaceReferences_1 = interfaceReferences; _i < interfaceReferences_1.length; _i++) { - var typeReference = interfaceReferences_1[_i]; - if (searchTypeReference(typeReference)) { - return true; - } - } - } - } - return searchTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - if (parentIsInterface) { - return ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), searchTypeReference); - } - } - return false; - }); - cachedResults.set(key, inherits); - return inherits; + function explicitlyInheritsFrom(symbol, parent, cachedResults, checker) { + if (symbol === parent) { + return true; } - function searchTypeReference(typeReference) { - if (typeReference) { + var key = ts.getSymbolId(symbol) + "," + ts.getSymbolId(parent); + var cached = cachedResults.get(key); + if (cached !== undefined) { + return cached; + } + // Set the key so that we don't infinitely recurse + cachedResults.set(key, false); + var inherits = symbol.declarations.some(function (declaration) { + return ts.getAllSuperTypeNodes(declaration).some(function (typeReference) { var type = checker.getTypeAtLocation(typeReference); - if (type && type.symbol) { - return searchHierarchy(type.symbol); - } - } - return false; - } + return !!type && !!type.symbol && explicitlyInheritsFrom(type.symbol, parent, cachedResults, checker); + }); + }); + cachedResults.set(key, inherits); + return inherits; } function getReferencesForSuperKeyword(superKeyword) { var searchSpaceNode = ts.getSuperContainer(superKeyword, /*stopOnFunctions*/ false); @@ -88128,13 +95245,13 @@ var ts; // Whether 'super' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; @@ -88142,9 +95259,8 @@ var ts; return undefined; } var sourceFile = searchSpaceNode.getSourceFile(); - var references = ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, "super", searchSpaceNode), function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (!node || node.kind !== 97 /* SuperKeyword */) { + var references = ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), function (node) { + if (node.kind !== 97 /* SuperKeyword */) { return; } var container = ts.getSuperContainer(node, /*stopOnFunctions*/ false); @@ -88160,87 +95276,67 @@ var ts; // Whether 'this' occurs in a static context within a class. var staticFlag = 32 /* Static */; switch (searchSpaceNode.kind) { - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: if (ts.isObjectLiteralMethod(searchSpaceNode)) { break; } // falls through - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: staticFlag &= ts.getModifierFlags(searchSpaceNode); searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; - case 272 /* SourceFile */: + case 277 /* SourceFile */: if (ts.isExternalModule(searchSpaceNode)) { return undefined; } // falls through - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: break; // Computed properties in classes are not handled here because references to this are illegal, // so there is no point finding references to them. default: return undefined; } - var references = []; - for (var _i = 0, _a = searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()]; _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var references = ts.flatMap(searchSpaceNode.kind === 277 /* SourceFile */ ? sourceFiles : [searchSpaceNode.getSourceFile()], function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - var positions = getPossibleSymbolReferencePositions(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode); - getThisReferencesInFile(sourceFile, searchSpaceNode.kind === 272 /* SourceFile */ ? sourceFile : searchSpaceNode, positions, staticFlag, references); - } + return getPossibleSymbolReferenceNodes(sourceFile, "this", ts.isSourceFile(searchSpaceNode) ? sourceFile : searchSpaceNode).filter(function (node) { + if (!ts.isThis(node)) { + return false; + } + var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); + switch (searchSpaceNode.kind) { + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + return searchSpaceNode.symbol === container.symbol; + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + return ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol; + case 207 /* ClassExpression */: + case 238 /* ClassDeclaration */: + // Make sure the container belongs to the same class + // and has the appropriate static modifier from the original container. + return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; + case 277 /* SourceFile */: + return container.kind === 277 /* SourceFile */ && !ts.isExternalModule(container); + } + }); + }).map(function (n) { return FindAllReferences.nodeEntry(n); }); return [{ definition: { type: "this", node: thisOrSuperKeyword }, references: references }]; } - function getThisReferencesInFile(sourceFile, searchSpaceNode, possiblePositions, staticFlag, result) { - ts.forEach(possiblePositions, function (position) { - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false); - if (!node || !ts.isThis(node)) { - return; - } - var container = ts.getThisContainer(node, /* includeArrowFunctions */ false); - switch (searchSpaceNode.kind) { - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - if (searchSpaceNode.symbol === container.symbol) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - if (ts.isObjectLiteralMethod(searchSpaceNode) && searchSpaceNode.symbol === container.symbol) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 203 /* ClassExpression */: - case 233 /* ClassDeclaration */: - // Make sure the container belongs to the same class - // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - case 272 /* SourceFile */: - if (container.kind === 272 /* SourceFile */ && !ts.isExternalModule(container)) { - result.push(FindAllReferences.nodeEntry(node)); - } - break; - } - }); - } function getReferencesForStringLiteral(node, sourceFiles, cancellationToken) { var references = ts.flatMap(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - return ts.mapDefined(getPossibleSymbolReferencePositions(sourceFile, node.text), function (position) { - var ref = ts.tryCast(ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ false), ts.isStringLiteral); - return ref && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; + return ts.mapDefined(getPossibleSymbolReferenceNodes(sourceFile, node.text), function (ref) { + return ts.isStringLiteral(ref) && ref.text === node.text ? FindAllReferences.nodeEntry(ref, /*isInString*/ true) : undefined; }); }); return [{ @@ -88251,26 +95347,27 @@ var ts; // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. function populateSearchSymbolSet(symbol, location, checker, implementations) { - // The search set contains at least the current symbol var result = []; + forEachRelatedSymbol(symbol, location, checker, function (sym, root, base) { result.push(base || root || sym); }, + /*allowBaseTypes*/ function () { return !implementations; }); + return result; + } + function forEachRelatedSymbol(symbol, location, checker, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { - // If the location is name of property symbol from object literal destructuring pattern - // Search the property symbol - // for ( { property: p2 } of elems) { } - if (containingObjectLiteralElement.kind !== 269 /* ShorthandPropertyAssignment */) { - var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); - if (propertySymbol) { - result.push(propertySymbol); - } - } // If the location is in a context sensitive location (i.e. in an object literal) try // to get a contextual type for it, and add the property symbol from the contextual // type to the search set - for (var _i = 0, _a = getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker); _i < _a.length; _i++) { - var contextualSymbol = _a[_i]; - addRootSymbols(contextualSymbol); - } + var res_1 = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), fromRoot); + if (res_1) + return res_1; + // If the location is name of property symbol from object literal destructuring pattern + // Search the property symbol + // for ( { property: p2 } of elems) { } + var propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); + var res1 = propertySymbol && cbSymbol(propertySymbol); + if (res1) + return res1; /* Because in short-hand property assignment, location has two meaning : property name and as value of the property * When we do findAllReference at the position of the short-hand property assignment, we would want to have references to position of * property name and variable declaration of the identifier. @@ -88283,177 +95380,60 @@ var ts; * will be included correctly. */ var shorthandValueSymbol = checker.getShorthandAssignmentValueSymbol(location.parent); - if (shorthandValueSymbol) { - result.push(shorthandValueSymbol); - } + var res2 = shorthandValueSymbol && cbSymbol(shorthandValueSymbol); + if (res2) + return res2; + } + var res = fromRoot(symbol); + if (res) + return res; + if (symbol.valueDeclaration && ts.isParameterPropertyDeclaration(symbol.valueDeclaration)) { + // For a parameter property, now try on the other symbol (property if this was a parameter, parameter if this was a property). + var paramProps = checker.getSymbolsOfParameterPropertyDeclaration(ts.cast(symbol.valueDeclaration, ts.isParameter), symbol.name); + ts.Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); // is [parameter, property] + return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } - // If the symbol.valueDeclaration is a property parameter declaration, - // we should include both parameter declaration symbol and property declaration symbol - // Parameter Declaration symbol is only visible within function scope, so the symbol is stored in constructor.locals. - // Property Declaration symbol is a member of the class, so the symbol is stored in its class Declaration.symbol.members - ts.addRange(result, getParameterPropertySymbols(symbol, checker)); // If this is symbol of binding element without propertyName declaration in Object binding pattern // Include the property in the search var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); - if (bindingElementPropertySymbol) { - result.push(bindingElementPropertySymbol); - addRootSymbols(bindingElementPropertySymbol); - } - addRootSymbols(symbol); - return result; - function addRootSymbols(sym) { - // If this is a union property, add all the symbols from all its source symbols in all unioned types. - // If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list - for (var _i = 0, _a = checker.getRootSymbols(sym); _i < _a.length; _i++) { - var rootSymbol = _a[_i]; - result.push(rootSymbol); - // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions - if (!implementations && rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - } - } - } - } - function getParameterPropertySymbols(symbol, checker) { - return symbol.valueDeclaration && ts.isParameter(symbol.valueDeclaration) && ts.isParameterPropertyDeclaration(symbol.valueDeclaration) - ? checker.getSymbolsOfParameterPropertyDeclaration(symbol.valueDeclaration, symbol.name) - : undefined; - } - /** - * Find symbol of the given property-name and add the symbol to the given result array - * @param symbol a symbol to start searching for the given propertyName - * @param propertyName a name of property to search for - * @param result an array of symbol of found property symbols - * @param previousIterationSymbolsCache a cache of symbol from previous iterations of calling this function to prevent infinite revisiting of the same symbol. - * The value of previousIterationSymbol is undefined when the function is first called. - */ - function getPropertySymbolsFromBaseTypes(symbol, propertyName, result, previousIterationSymbolsCache, checker) { - if (!symbol) { - return; - } - // If the current symbol is the same as the previous-iteration symbol, we can just return the symbol that has already been visited - // This is particularly important for the following cases, so that we do not infinitely visit the same symbol. - // For example: - // interface C extends C { - // /*findRef*/propName: string; - // } - // The first time getPropertySymbolsFromBaseTypes is called when finding-all-references at propName, - // the symbol argument will be the symbol of an interface "C" and previousIterationSymbol is undefined, - // the function will add any found symbol of the property-name, then its sub-routine will call - // getPropertySymbolsFromBaseTypes again to walk up any base types to prevent revisiting already - // visited symbol, interface "C", the sub-routine will pass the current symbol as previousIterationSymbol. - if (previousIterationSymbolsCache.has(symbol.escapedName)) { - return; - } - if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) { - ts.forEach(symbol.getDeclarations(), function (declaration) { - if (ts.isClassLike(declaration)) { - getPropertySymbolFromTypeReference(ts.getClassExtendsHeritageClauseElement(declaration)); - ts.forEach(ts.getClassImplementsHeritageClauseElements(declaration), getPropertySymbolFromTypeReference); - } - else if (declaration.kind === 234 /* InterfaceDeclaration */) { - ts.forEach(ts.getInterfaceBaseTypeNodes(declaration), getPropertySymbolFromTypeReference); - } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol); + function fromRoot(sym) { + // If this is a union property: + // - In populateSearchSymbolsSet we will add all the symbols from all its source symbols in all unioned types. + // - In findRelatedSymbol, we will just use the union symbol if any source symbol is included in the search. + // If the symbol is an instantiation from a another symbol (e.g. widened symbol): + // - In populateSearchSymbolsSet, add the root the list + // - In findRelatedSymbol, return the source symbol if that is in the search. (Do not return the instantiation symbol.) + return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { + return cbSymbol(sym, rootSymbol) + // Add symbol of properties/methods of the same name in base classes and implemented interfaces definitions + || (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */) && allowBaseTypes(rootSymbol) + ? ts.getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, checker, function (base) { return cbSymbol(sym, rootSymbol, base); }) + : undefined); }); } - return; - function getPropertySymbolFromTypeReference(typeReference) { - if (typeReference) { - var type = checker.getTypeAtLocation(typeReference); - if (type) { - var propertySymbol = checker.getPropertyOfType(type, propertyName); - if (propertySymbol) { - result.push.apply(result, checker.getRootSymbols(propertySymbol)); - } - // Visit the typeReference as well to see if it directly or indirectly use that property - previousIterationSymbolsCache.set(symbol.escapedName, symbol); - getPropertySymbolsFromBaseTypes(type.symbol, propertyName, result, previousIterationSymbolsCache, checker); - } - } - } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - if (search.includes(referenceSymbol)) { - return referenceSymbol; - } - if (referenceSymbol.flags & 1 /* FunctionScopedVariable */) { - ts.Debug.assert(!(referenceSymbol.flags & 4 /* Property */)); - var paramProps = getParameterPropertySymbols(referenceSymbol, checker); - if (paramProps) { - return getRelatedSymbol(search, ts.find(paramProps, function (x) { return !!(x.flags & 4 /* Property */); }), referenceLocation, state); - } - } - // If the reference location 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 symbol to - // compare to our searchSymbol - var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(referenceLocation); - if (containingObjectLiteralElement) { - var contextualSymbol = ts.firstDefined(getPropertySymbolsFromContextualType(containingObjectLiteralElement, checker), findRootSymbol); - if (contextualSymbol) { - return contextualSymbol; - } - // If the reference location is the name of property from object literal destructuring pattern - // Get the property symbol from the object literal's type and look if thats the search symbol - // In below eg. get 'property' from type of elems iterating type - // for ( { property: p2 } of elems) { } - var propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation, checker); - if (propertySymbol && search.includes(propertySymbol)) { - return propertySymbol; - } - } - // If the reference location is the binding element and doesn't have property name - // then include the binding element in the related symbols - // let { a } : { a }; - var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol, checker); - if (bindingElementPropertySymbol) { - var fromBindingElement = findRootSymbol(bindingElementPropertySymbol); - if (fromBindingElement) - return fromBindingElement; - } - return findRootSymbol(referenceSymbol); - function findRootSymbol(sym) { - // Unwrap symbols to get to the root (e.g. transient symbols as a result of widening) - // Or a union property, use its underlying unioned symbols - return ts.firstDefined(checker.getRootSymbols(sym), function (rootSymbol) { - // if it is in the list, then we are done - if (search.includes(rootSymbol)) { - return rootSymbol; - } - // Finally, try all properties with the same name in any type the containing type extended or implemented, and - // see if any is in the list. If we were passed a parent symbol, only include types that are subtypes of the - // parent symbol - if (rootSymbol.parent && rootSymbol.parent.flags & (32 /* Class */ | 64 /* Interface */)) { - // Parents will only be defined if implementations is true - if (search.parents && !ts.some(search.parents, function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })) { - return undefined; - } - var result = []; - getPropertySymbolsFromBaseTypes(rootSymbol.parent, rootSymbol.name, result, /*previousIterationSymbolsCache*/ ts.createSymbolTable(), checker); - return ts.find(result, search.includes); - } - return undefined; - }); - } - } - function getNameFromObjectLiteralElement(node) { - if (node.name.kind === 146 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (ts.isStringOrNumericLiteral(nameExpression)) { - return nameExpression.text; - } - return undefined; - } - return ts.getTextOfIdentifierOrLiteral(node.name); + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, function (sym, rootSymbol, baseSymbol) { return search.includes(baseSymbol || rootSymbol || sym) + // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. + ? rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym + : undefined; }, + /*allowBaseTypes*/ function (rootSymbol) { + return !(search.parents && !search.parents.some(function (parent) { return explicitlyInheritsFrom(rootSymbol.parent, parent, state.inheritsFromCache, checker); })); + }); } /** Gets all symbols for one property. Does not get symbols for every property. */ function getPropertySymbolsFromContextualType(node, checker) { var contextualType = checker.getContextualType(node.parent); - var name = getNameFromObjectLiteralElement(node); - var symbol = contextualType && name && contextualType.getProperty(name); + if (!contextualType) + return ts.emptyArray; + var name = ts.getNameFromPropertyName(node.name); + if (!name) + return ts.emptyArray; + var symbol = contextualType.getProperty(name); return symbol ? [symbol] : - contextualType && contextualType.flags & 131072 /* Union */ ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; + contextualType.isUnion() ? ts.mapDefined(contextualType.types, function (t) { return t.getProperty(name); }) : ts.emptyArray; } /** * Given an initial searchMeaning, extracted from a location, widen the search scope based on the declarations @@ -88475,8 +95455,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { - var declaration = declarations_10[_i]; + for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { + var declaration = declarations_11[_i]; var declarationMeaning = ts.getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -88488,35 +95468,10 @@ var ts; } Core.getIntersectingMeaningFromDeclarations = getIntersectingMeaningFromDeclarations; function isImplementation(node) { - if (!node) { - return false; - } - else if (ts.isVariableLike(node) && ts.hasInitializer(node)) { - return true; - } - else if (node.kind === 230 /* VariableDeclaration */) { - var parentStatement = getParentStatementOfVariableDeclaration(node); - return parentStatement && ts.hasModifier(parentStatement, 2 /* Ambient */); - } - else if (ts.isFunctionLike(node)) { - return !!node.body || ts.hasModifier(node, 2 /* Ambient */); - } - else { - switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - return true; - } - } - return false; - } - function getParentStatementOfVariableDeclaration(node) { - if (node.parent && node.parent.parent && node.parent.parent.kind === 212 /* VariableStatement */) { - ts.Debug.assert(node.parent.kind === 231 /* VariableDeclarationList */); - return node.parent.parent; - } + return !!(node.flags & 4194304 /* Ambient */) + || (ts.isVariableLike(node) ? ts.hasInitializer(node) + : ts.isFunctionLikeDeclaration(node) ? !!node.body + : ts.isClassLike(node) || ts.isModuleOrEnumDeclaration(node)); } function getReferenceEntriesForShorthandPropertyAssignment(node, checker, addReference) { var refSymbol = checker.getSymbolAtLocation(node); @@ -88543,12 +95498,6 @@ var ts; function tryGetClassByExtendingIdentifier(node) { return ts.tryGetClassExtendingExpressionWithTypeArguments(ts.climbPastPropertyAccess(node).parent); } - function isNameOfExternalModuleImportOrDeclaration(node) { - if (node.kind === 9 /* StringLiteral */) { - return ts.isNameOfModuleDeclaration(node) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node); - } - return false; - } /** * If we are just looking for implementations and this is a property access expression, we need to get the * symbol of the local type of the symbol the property is being accessed on. This is because our search @@ -88556,26 +95505,218 @@ var ts; * being accessed (i.e. it is declared in some parent class or interface) */ function getParentSymbolsOfPropertyAccess(location, symbol, checker) { - var propertyAccessExpression = getPropertyAccessExpressionFromRightHandSide(location); - if (!propertyAccessExpression) { - return undefined; - } - var localParentType = checker.getTypeAtLocation(propertyAccessExpression.expression); - if (!localParentType) { - return undefined; - } - if (localParentType.symbol && localParentType.symbol.flags & (32 /* Class */ | 64 /* Interface */) && localParentType.symbol !== symbol.parent) { - return [localParentType.symbol]; - } - else if (localParentType.flags & 393216 /* UnionOrIntersection */) { - return getSymbolsForClassAndInterfaceComponents(localParentType); - } + var propertyAccessExpression = ts.isRightSideOfPropertyAccess(location) ? location.parent : undefined; + var lhsType = propertyAccessExpression && checker.getTypeAtLocation(propertyAccessExpression.expression); + var res = ts.mapDefined(lhsType && (lhsType.isUnionOrIntersection() ? lhsType.types : lhsType.symbol === symbol.parent ? undefined : [lhsType]), function (t) { + return t.symbol && t.symbol.flags & (32 /* Class */ | 64 /* Interface */) ? t.symbol : undefined; + }); + return res.length === 0 ? undefined : res; } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + function getEditsForFileRename(program, oldFileOrDirPath, newFileOrDirPath, host, formatContext, preferences, sourceMapper) { + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var oldToNew = getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper); + var newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper); + return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) { + updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames); + updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences); + }); + } + ts.getEditsForFileRename = getEditsForFileRename; + // exported for tests + function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName, sourceMapper) { + var canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); + return function (path) { + var originalPath = sourceMapper && sourceMapper.tryGetOriginalLocation({ fileName: path, position: 0 }); + var updatedPath = getUpdatedPath(originalPath ? originalPath.fileName : path); + return originalPath + ? updatedPath === undefined ? undefined : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) + : updatedPath; + }; + function getUpdatedPath(pathToUpdate) { + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) + return newFileOrDirPath; + var suffix = ts.tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); + return suffix === undefined ? undefined : newFileOrDirPath + "/" + suffix; + } + } + ts.getPathUpdater = getPathUpdater; + // Relative path from a0 to b0 should be same as relative path from a1 to b1. Returns b1. + function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { + var rel = ts.getRelativePathFromFile(a0, b0, getCanonicalFileName); + return combinePathsSafe(ts.getDirectoryPath(a1), rel); + } + function updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames) { + var configFile = program.getCompilerOptions().configFile; + if (!configFile) + return; + var configDir = ts.getDirectoryPath(configFile.fileName); + var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!jsonObjectLiteral) + return; + forEachProperty(jsonObjectLiteral, function (property, propertyName) { + switch (propertyName) { + case "files": + case "include": + case "exclude": { + var foundExactMatch = updatePaths(property); + if (!foundExactMatch && propertyName === "include" && ts.isArrayLiteralExpression(property.initializer)) { + var includes = ts.mapDefined(property.initializer.elements, function (e) { return ts.isStringLiteral(e) ? e.text : undefined; }); + var matchers = ts.getFileMatcherPatterns(configDir, /*excludes*/ [], includes, useCaseSensitiveFileNames, currentDirectory); + // If there isn't some include for this, add a new one. + if (!ts.getRegexFromPattern(ts.Debug.assertDefined(matchers.includeFilePattern), useCaseSensitiveFileNames).test(newFileOrDirPath)) { + changeTracker.insertNodeAfter(configFile, ts.last(property.initializer.elements), ts.createStringLiteral(relativePath(newFileOrDirPath))); + } + } + break; + } + case "compilerOptions": + forEachProperty(property.initializer, function (property, propertyName) { + var option = ts.getOptionFromName(propertyName); + if (option && (option.isFilePath || option.type === "list" && option.element.isFilePath)) { + updatePaths(property); + } + else if (propertyName === "paths") { + forEachProperty(property.initializer, function (pathsProperty) { + if (!ts.isArrayLiteralExpression(pathsProperty.initializer)) + return; + for (var _i = 0, _a = pathsProperty.initializer.elements; _i < _a.length; _i++) { + var e = _a[_i]; + tryUpdateString(e); + } + }); + } + }); + break; + } + }); + function updatePaths(property) { + // Type annotation needed due to #7294 + var elements = ts.isArrayLiteralExpression(property.initializer) ? property.initializer.elements : [property.initializer]; + var foundExactMatch = false; + for (var _i = 0, elements_5 = elements; _i < elements_5.length; _i++) { + var element = elements_5[_i]; + foundExactMatch = tryUpdateString(element) || foundExactMatch; + } + return foundExactMatch; + } + function tryUpdateString(element) { + if (!ts.isStringLiteral(element)) + return false; + var elementFileName = combinePathsSafe(configDir, element.text); + var updated = oldToNew(elementFileName); + if (updated !== undefined) { + changeTracker.replaceRangeWithText(configFile, createStringRange(element, configFile), relativePath(updated)); + return true; + } + return false; + } + function relativePath(path) { + return ts.getRelativePathFromDirectory(configDir, path, /*ignoreCase*/ !useCaseSensitiveFileNames); + } + } + function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences) { + var allFiles = program.getSourceFiles(); + var _loop_15 = function (sourceFile) { + var newFromOld = oldToNew(sourceFile.path); + var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; + var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); + var oldFromNew = newToOld(sourceFile.fileName); + var oldImportFromPath = oldFromNew || sourceFile.fileName; + var oldImportFromDirectory = ts.getDirectoryPath(oldImportFromPath); + var importingSourceFileMoved = newFromOld !== undefined || oldFromNew !== undefined; + updateImportsWorker(sourceFile, changeTracker, function (referenceText) { + if (!ts.pathIsRelative(referenceText)) + return undefined; + var oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); + var newAbsolute = oldToNew(oldAbsolute); + return newAbsolute === undefined ? undefined : ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); + }, function (importLiteral) { + var importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); + // No need to update if it's an ambient module^M + if (importedModuleSymbol && importedModuleSymbol.declarations.some(function (d) { return ts.isAmbientModule(d); })) + return undefined; + var toImport = oldFromNew !== undefined + // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. + // TODO:GH#18217 + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); + // Need an update if the imported file moved, or the importing file moved and was using a relative path. + return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) + ? ts.moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences) + : undefined; + }); + }; + for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { + var sourceFile = allFiles_1[_i]; + _loop_15(sourceFile); + } + } + function combineNormal(pathA, pathB) { + return ts.normalizePath(ts.combinePaths(pathA, pathB)); + } + function combinePathsSafe(pathA, pathB) { + return ts.ensurePathIsNonModuleName(combineNormal(pathA, pathB)); + } + function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSourceFile, program, host, oldToNew) { + if (importedModuleSymbol) { + // `find` should succeed because we checked for ambient modules before calling this function. + var oldFileName = ts.find(importedModuleSymbol.declarations, ts.isSourceFile).fileName; + var newFileName = oldToNew(oldFileName); + return newFileName === undefined ? { newFileName: oldFileName, updated: false } : { newFileName: newFileName, updated: true }; + } + else { + var resolved = host.resolveModuleNames + ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) + : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); + return getSourceFileToImportFromResolved(resolved, oldToNew, host); + } + } + function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + return resolved && ((resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, getIfExists)); + function getIfExists(oldLocation) { + var newLocation = oldToNew(oldLocation); + return host.fileExists(oldLocation) || newLocation !== undefined && host.fileExists(newLocation) // TODO: GH#18217 + ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } + : undefined; + } + } + function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { + for (var _i = 0, _a = sourceFile.referencedFiles; _i < _a.length; _i++) { + var ref = _a[_i]; + var updated = updateRef(ref.fileName); + if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) + changeTracker.replaceRangeWithText(sourceFile, ref, updated); + } + for (var _b = 0, _c = sourceFile.imports; _b < _c.length; _b++) { + var importStringLiteral = _c[_b]; + var updated = updateImport(importStringLiteral); + if (updated !== undefined && updated !== importStringLiteral.text) + changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + } + } + function createStringRange(node, sourceFile) { + return ts.createTextRange(node.getStart(sourceFile) + 1, node.end - 1); + } + function forEachProperty(objectLiteral, cb) { + if (!ts.isObjectLiteralExpression(objectLiteral)) + return; + for (var _i = 0, _a = objectLiteral.properties; _i < _a.length; _i++) { + var property = _a[_i]; + if (ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name)) { + cb(property, property.name.text); + } + } + } +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var GoToDefinition; (function (GoToDefinition) { @@ -88584,34 +95725,38 @@ var ts; if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; } + var parent = node.parent; // Labels if (ts.isJumpStatementTarget(node)) { var label = ts.getTargetLabel(node.parent, node.text); - return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; + return label ? [createDefinitionInfoFromName(label, "label" /* label */, node.text, /*containerName*/ undefined)] : undefined; // TODO: GH#18217 } var typeChecker = program.getTypeChecker(); - var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); - if (calledDeclaration) { - return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; - } - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbol(node, typeChecker); // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { - return undefined; + return getDefinitionInfoForIndexSignatures(node, typeChecker); } - // If this is an alias, and the request came at the declaration location - // get the aliased symbol instead. This allows for goto def on an import e.g. - // import {A, B} from "mod"; - // to jump to the implementation directly. - if (symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { - var aliased = typeChecker.getAliasedSymbol(symbol); - if (aliased.declarations) { - symbol = aliased; + var calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); + // Don't go to the component constructor definition for a JSX element, just go to the component definition. + if (calledDeclaration && !(ts.isJsxOpeningLikeElement(node.parent) && ts.isConstructorDeclaration(calledDeclaration))) { + var sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration); + // For a function, if this is the original function definition, return just sigInfo. + // If this is the original constructor definition, parent is the class. + if (typeChecker.getRootSymbols(symbol).some(function (s) { return symbolMatchesSignature(s, calledDeclaration); }) || + // TODO: GH#23742 Following check shouldn't be necessary if 'require' is an alias + symbol.declarations.some(function (d) { return ts.isVariableDeclaration(d) && !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ false); })) { + return [sigInfo]; + } + else { + var defs = getDefinitionFromSymbol(typeChecker, symbol, node); + // For a 'super()' call, put the signature first, else put the variable first. + return node.kind === 97 /* SuperKeyword */ ? [sigInfo].concat(defs) : defs.concat([sigInfo]); } } // Because name in short-hand property assignment has two different meanings: property name and property value, @@ -88619,16 +95764,9 @@ var ts; // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. - if (node.parent.kind === 269 /* ShorthandPropertyAssignment */) { - var shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - if (!shorthandSymbol) { - return []; - } - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind_1 = ts.SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); - var shorthandSymbolName_1 = typeChecker.symbolToString(shorthandSymbol); - var shorthandContainerName_1 = typeChecker.symbolToString(symbol.parent, node); - return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind_1, shorthandSymbolName_1, shorthandContainerName_1); }); + if (node.parent.kind === 274 /* ShorthandPropertyAssignment */) { + var shorthandSymbol_1 = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + return shorthandSymbol_1 ? shorthandSymbol_1.declarations.map(function (decl) { return createDefinitionInfo(decl, typeChecker, shorthandSymbol_1, node); }) : []; } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern @@ -88641,9 +95779,9 @@ var ts; // 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 (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && + (node === (parent.propertyName || parent.name))) { + var type = typeChecker.getTypeAtLocation(parent.parent); if (type) { var propSymbols = ts.getPropertySymbolsFromType(type, node); if (propSymbols) { @@ -88669,6 +95807,14 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + /** + * True if we should not add definitions for both the signature symbol and the definition symbol. + * True for `const |f = |() => 0`, false for `function |f() {} const |g = f;`. + */ + function symbolMatchesSignature(s, calledDeclaration) { + return s === calledDeclaration.symbol || s === calledDeclaration.symbol.parent || + !ts.isCallLikeExpression(calledDeclaration.parent) && s === calledDeclaration.parent.symbol; + } function getReferenceAtPosition(sourceFile, position, program) { var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { @@ -88678,15 +95824,20 @@ var ts; var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - var file = reference && program.getSourceFile(reference.resolvedFileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); // TODO:GH#18217 return file && { fileName: typeReferenceDirective.fileName, file: file }; } + var libReferenceDirective = findReferenceInPosition(sourceFile.libReferenceDirectives, position); + if (libReferenceDirective) { + var file = program.getLibFileFromReference(libReferenceDirective); + return file && { fileName: libReferenceDirective.fileName, file: file }; + } return undefined; } GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { return undefined; } @@ -88695,7 +95846,7 @@ var ts; if (!type) { return undefined; } - if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { + if (type.isUnion() && !(type.flags & 32 /* Enum */)) { return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); @@ -88707,15 +95858,41 @@ var ts; return undefined; } // Check if position is on triple slash reference. - var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + var comment = findReferenceInPosition(sourceFile.referencedFiles, position) || + findReferenceInPosition(sourceFile.typeReferenceDirectives, position) || + findReferenceInPosition(sourceFile.libReferenceDirectives, position); if (comment) { return { definitions: definitions, textSpan: ts.createTextSpanFromRange(comment) }; } - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); var textSpan = ts.createTextSpan(node.getStart(), node.getWidth()); return { definitions: definitions, textSpan: textSpan }; } GoToDefinition.getDefinitionAndBoundSpan = getDefinitionAndBoundSpan; + // At 'x.foo', see if the type of 'x' has an index signature, and if so find its declarations. + function getDefinitionInfoForIndexSignatures(node, checker) { + if (!ts.isPropertyAccessExpression(node.parent) || node.parent.name !== node) + return; + var type = checker.getTypeAtLocation(node.parent.expression); + return ts.mapDefined(type.isUnionOrIntersection() ? type.types : [type], function (nonUnionType) { + var info = checker.getIndexInfoOfType(nonUnionType, 0 /* String */); + return info && info.declaration && createDefinitionFromSignatureDeclaration(checker, info.declaration); + }); + } + function getSymbol(node, checker) { + var symbol = checker.getSymbolAtLocation(node); + // If this is an alias, and the request came at the declaration location + // get the aliased symbol instead. This allows for goto def on an import e.g. + // import {A, B} from "mod"; + // to jump to the implementation directly. + if (symbol && symbol.flags & 2097152 /* Alias */ && shouldSkipAlias(node, symbol.declarations[0])) { + var aliased = checker.getAliasedSymbol(symbol); + if (aliased.declarations) { + return aliased; + } + } + return symbol; + } // Go to the original declaration for cases: // // (1) when the aliased symbol was declared in the location(parent). @@ -88729,18 +95906,17 @@ var ts; return true; } switch (declaration.kind) { - case 243 /* ImportClause */: - case 241 /* ImportEqualsDeclaration */: + case 248 /* ImportClause */: + case 246 /* ImportEqualsDeclaration */: return true; - case 246 /* ImportSpecifier */: - return declaration.parent.kind === 245 /* NamedImports */; + case 251 /* ImportSpecifier */: + return declaration.parent.kind === 250 /* NamedImports */; default: return false; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, typeChecker, symbol, node); }); function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class @@ -88758,30 +95934,22 @@ var ts; if (!signatureDeclarations) { return undefined; } - var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : ts.isFunctionLike); return declarations.length - ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), typeChecker, symbol, node)] : undefined; } } - function isSignatureDeclaration(node) { - switch (node.kind) { - case 154 /* Constructor */: - case 158 /* ConstructSignature */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - return true; - default: - return false; - } - } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ - function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); + function createDefinitionInfo(declaration, checker, symbol, node) { + var symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = ts.SymbolDisplay.getSymbolKind(checker, symbol, node); + var containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; + return createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ - function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { + function createDefinitionInfoFromName(declaration, symbolKind, symbolName, containerName) { + var name = ts.getNameOfDeclaration(declaration) || declaration; var sourceFile = name.getSourceFile(); return { fileName: sourceFile.fileName, @@ -88792,25 +95960,11 @@ var ts; containerName: containerName }; } - function getSymbolInfo(typeChecker, symbol, node) { - return { - symbolName: typeChecker.symbolToString(symbol), - symbolKind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node), - containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" - }; - } function createDefinitionFromSignatureDeclaration(typeChecker, decl) { - var _a = getSymbolInfo(typeChecker, decl.symbol, decl), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - return createDefinitionInfo(decl, symbolKind, symbolName, containerName); + return createDefinitionInfo(decl, typeChecker, decl.symbol, decl); } function findReferenceInPosition(refs, pos) { - for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) { - var ref = refs_1[_i]; - if (ref.pos <= pos && pos <= ref.end) { - return ref; - } - } - return undefined; + return ts.find(refs, function (ref) { return ts.textRangeContainsPositionInclusive(ref, pos); }); } GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { @@ -88820,14 +95974,14 @@ var ts; kind: "script" /* scriptElement */, name: name, containerName: undefined, - containerKind: undefined + containerKind: undefined, }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node) { var target = climbPastManyPropertyAccesses(node); var callLike = target.parent; - return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target && callLike; + return callLike && ts.isCallLikeExpression(callLike) && ts.getInvokedExpression(callLike) === target ? callLike : undefined; } function climbPastManyPropertyAccesses(node) { return ts.isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; @@ -88835,14 +95989,8 @@ var ts; function tryGetSignatureDeclaration(typeChecker, node) { var callLike = getAncestorCallLikeExpression(node); var signature = callLike && typeChecker.getResolvedSignature(callLike); - if (signature) { - var decl = signature.declaration; - if (decl && isSignatureDeclaration(decl)) { - return decl; - } - } // Don't go to a function type, go to the value having that type. - return undefined; + return ts.tryCast(signature && signature.declaration, function (d) { return ts.isFunctionLike(d) && !ts.isFunctionTypeNode(d); }); } })(GoToDefinition = ts.GoToDefinition || (ts.GoToDefinition = {})); })(ts || (ts = {})); @@ -88852,47 +96000,83 @@ var ts; var JsDoc; (function (JsDoc) { var jsDocTagNames = [ + "abstract", + "access", + "alias", + "argument", + "async", "augments", "author", - "argument", "borrows", + "callback", "class", + "classdesc", "constant", "constructor", "constructs", + "copyright", "default", "deprecated", "description", + "emits", + "enum", "event", "example", + "exports", "extends", + "external", "field", - "fileOverview", + "file", + "fileoverview", + "fires", "function", + "generator", + "global", + "hideconstructor", + "host", "ignore", - "inheritDoc", + "implements", + "inheritdoc", "inner", + "instance", + "interface", + "kind", "lends", - "link", - "memberOf", + "license", + "listens", + "member", + "memberof", "method", + "mixes", + "module", "name", "namespace", + "override", + "package", "param", "private", - "prop", "property", + "protected", "public", + "readonly", "requires", "returns", "see", "since", "static", + "summary", "template", + "this", "throws", + "todo", + "tutorial", "type", "typedef", - "version" + "var", + "variation", + "version", + "virtual", + "yields" ]; var jsDocTagNameCompletionEntries; var jsDocTagCompletionEntries; @@ -88920,10 +96104,12 @@ var ts; JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; function getCommentHavingNodes(declaration) { switch (declaration.kind) { - case 292 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: + case 302 /* JSDocPropertyTag */: return [declaration]; - case 291 /* JSDocTypedefTag */: - return [declaration.parent]; + case 295 /* JSDocCallbackTag */: + case 301 /* JSDocTypedefTag */: + return [declaration, declaration.parent]; default: return ts.getJSDocCommentsAndTags(declaration); } @@ -88943,15 +96129,16 @@ var ts; function getCommentText(tag) { var comment = tag.comment; switch (tag.kind) { - case 285 /* JSDocAugmentsTag */: + case 293 /* JSDocAugmentsTag */: return withNode(tag.class); - case 290 /* JSDocTemplateTag */: + case 300 /* JSDocTemplateTag */: return withList(tag.typeParameters); - case 289 /* JSDocTypeTag */: + case 299 /* JSDocTypeTag */: return withNode(tag.typeExpression); - case 291 /* JSDocTypedefTag */: - case 292 /* JSDocPropertyTag */: - case 287 /* JSDocParameterTag */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: + case 302 /* JSDocPropertyTag */: + case 296 /* JSDocParameterTag */: var name = tag.name; return name ? withNode(name) : comment; default: @@ -89033,7 +96220,7 @@ var ts; if (!ts.isIdentifier(param.name)) return undefined; var name = param.name.text; - if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) + if (jsdoc.tags.some(function (t) { return t !== tag && ts.isJSDocParameterTag(t) && ts.isIdentifier(t.name) && t.name.escapedText === name; }) // TODO: GH#18217 || nameThusFar !== undefined && !ts.startsWith(name, nameThusFar)) { return undefined; } @@ -89081,8 +96268,8 @@ var ts; if (ts.isInString(sourceFile, position) || ts.isInComment(sourceFile, position) || ts.hasDocComment(sourceFile, position)) { return undefined; } - var tokenAtPos = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); - var tokenStart = tokenAtPos.getStart(); + var tokenAtPos = ts.getTokenAtPosition(sourceFile, position); + var tokenStart = tokenAtPos.getStart(sourceFile); if (!tokenAtPos || tokenStart < position) { return undefined; } @@ -89091,7 +96278,7 @@ var ts; return undefined; } var commentOwner = commentOwnerInfo.commentOwner, parameters = commentOwnerInfo.parameters; - if (commentOwner.getStart() < position) { + if (commentOwner.getStart(sourceFile) < position) { return undefined; } if (!parameters || parameters.length === 0) { @@ -89099,22 +96286,7 @@ var ts; var singleLineResult = "/** */"; return { newText: singleLineResult, caretOffset: 3 }; } - var posLineAndChar = sourceFile.getLineAndCharacterOfPosition(position); - var lineStart = sourceFile.getLineStarts()[posLineAndChar.line]; - // replace non-whitespace characters in prefix with spaces. - var indentationStr = sourceFile.text.substr(lineStart, posLineAndChar.character).replace(/\S/i, function () { return " "; }); - var isJavaScriptFile = ts.hasJavaScriptFileExtension(sourceFile.fileName); - var docParams = ""; - for (var i = 0; i < parameters.length; i++) { - var currentName = parameters[i].name; - var paramName = currentName.kind === 71 /* Identifier */ ? currentName.escapedText : "param" + i; - if (isJavaScriptFile) { - docParams += indentationStr + " * @param {any} " + paramName + newLine; - } - else { - docParams += indentationStr + " * @param " + paramName + newLine; - } - } + var indentationStr = getIndentationStringAtPosition(sourceFile, position); // A doc comment consists of the following // * The opening comment line // * the first line (without a param) for the object's untagged info (this is also where the caret ends up) @@ -89122,32 +96294,48 @@ var ts; // * TODO: other tags. // * the closing comment line // * if the caret was directly in front of the object, then we add an extra line and indentation. - var preamble = "/**" + newLine + - indentationStr + " * "; + var preamble = "/**" + newLine + indentationStr + " * "; var result = preamble + newLine + - docParams + + parameterDocComments(parameters, ts.hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); return { newText: result, caretOffset: preamble.length }; } JsDoc.getDocCommentTemplateAtPosition = getDocCommentTemplateAtPosition; + function getIndentationStringAtPosition(sourceFile, position) { + var text = sourceFile.text; + var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); + var pos = lineStart; + for (; pos <= position && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) + ; + return text.slice(lineStart, pos); + } + function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { + return parameters.map(function (_a, i) { + var name = _a.name, dotDotDotToken = _a.dotDotDotToken; + var paramName = name.kind === 71 /* Identifier */ ? name.text : "param" + i; + var type = isJavaScriptFile ? (dotDotDotToken ? "{...any} " : "{any} ") : ""; + return indentationStr + " * @param " + type + paramName + newLine; + }).join(""); + } function getCommentOwnerInfo(tokenAtPos) { for (var commentOwner = tokenAtPos; commentOwner; commentOwner = commentOwner.parent) { switch (commentOwner.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: + case 153 /* MethodSignature */: var parameters = commentOwner.parameters; return { commentOwner: commentOwner, parameters: parameters }; - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 150 /* PropertySignature */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 235 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 151 /* PropertySignature */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 240 /* TypeAliasDeclaration */: return { commentOwner: commentOwner }; - case 212 /* VariableStatement */: { + case 217 /* VariableStatement */: { var varStatement = commentOwner; var varDeclarations = varStatement.declarationList.declarations; var parameters_1 = varDeclarations.length === 1 && varDeclarations[0].initializer @@ -89155,14 +96343,14 @@ var ts; : undefined; return { commentOwner: commentOwner, parameters: parameters_1 }; } - case 272 /* SourceFile */: + case 277 /* SourceFile */: return undefined; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // If in walking up the tree, we hit a a nested namespace declaration, // then we must be somewhere within a dotted namespace name; however we don't // want to give back a JSDoc template for the 'b' or 'c' in 'namespace a.b.c { }'. - return commentOwner.parent.kind === 237 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; - case 198 /* BinaryExpression */: { + return commentOwner.parent.kind === 242 /* ModuleDeclaration */ ? undefined : { commentOwner: commentOwner }; + case 202 /* BinaryExpression */: { var be = commentOwner; if (ts.getSpecialPropertyAssignmentKind(be) === 0 /* None */) { return undefined; @@ -89182,21 +96370,17 @@ var ts; * @returns the parameters of a signature found on the RHS if one exists; otherwise 'emptyArray'. */ function getParametersFromRightHandSideOfAssignment(rightHandSide) { - while (rightHandSide.kind === 189 /* ParenthesizedExpression */) { + while (rightHandSide.kind === 193 /* ParenthesizedExpression */) { rightHandSide = rightHandSide.expression; } switch (rightHandSide.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return rightHandSide.parameters; - case 203 /* ClassExpression */: - for (var _i = 0, _a = rightHandSide.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 154 /* Constructor */) { - return member.parameters; - } - } - break; + case 207 /* ClassExpression */: { + var ctr = ts.find(rightHandSide.members, ts.isConstructorDeclaration); + return ctr ? ctr.parameters : ts.emptyArray; + } } return ts.emptyArray; } @@ -89204,425 +96388,74 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; -(function (ts) { - function stringToInt(str) { - var n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error("Error in parseInt(" + JSON.stringify(str) + ")"); - } - return n; - } - var isPrereleaseRegex = /^(.*)-next.\d+/; - var prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - var semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - var Semver = /** @class */ (function () { - function Semver(major, minor, patch, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - isPrerelease) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.isPrerelease = isPrerelease; - } - Semver.parse = function (semver) { - var isPrerelease = isPrereleaseRegex.test(semver); - var result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error("Unexpected semver: " + semver + " (isPrerelease: " + isPrerelease + ")"); - } - return result; - }; - Semver.fromRaw = function (_a) { - var major = _a.major, minor = _a.minor, patch = _a.patch, isPrerelease = _a.isPrerelease; - return new Semver(major, minor, patch, isPrerelease); - }; - // This must parse the output of `versionString`. - Semver.tryParse = function (semver, isPrerelease) { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - var rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - var match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - }; - Object.defineProperty(Semver.prototype, "versionString", { - get: function () { - return this.isPrerelease ? this.major + "." + this.minor + ".0-next." + this.patch : this.major + "." + this.minor + "." + this.patch; - }, - enumerable: true, - configurable: true - }); - Semver.prototype.equals = function (sem) { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - }; - Semver.prototype.greaterThan = function (sem) { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - }; - return Semver; - }()); - ts.Semver = Semver; -})(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// -/// -/// -/// -/* @internal */ -var ts; -(function (ts) { - var JsTyping; - (function (JsTyping) { - /* @internal */ - function isTypingUpToDate(cachedTyping, availableTypingVersions) { - var availableVersion = ts.Semver.parse(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest")); - return !availableVersion.greaterThan(cachedTyping.version); - } - JsTyping.isTypingUpToDate = isTypingUpToDate; - /* @internal */ - JsTyping.nodeCoreModuleList = [ - "buffer", "querystring", "events", "http", "cluster", - "zlib", "os", "https", "punycode", "repl", "readline", - "vm", "child_process", "url", "dns", "net", - "dgram", "fs", "path", "string_decoder", "tls", - "crypto", "stream", "util", "assert", "tty", "domain", - "constants", "process", "v8", "timers", "console" - ]; - 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 - * @param projectRootPath is the path to the project root directory - * @param safeListPath is the path used to retrieve the safe list - * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions - * @param typeAcquisition is used to customize the typing acquisition process - * @param compilerOptions are used as a source for typing inference - */ - function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) { - if (!typeAcquisition || !typeAcquisition.enable) { - return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; - } - // A typing name to typing file path mapping - var inferredTypings = ts.createMap(); - // Only infer typings for .js and .jsx files - fileNames = ts.mapDefined(fileNames, function (fileName) { - var path = ts.normalizePath(fileName); - if (ts.hasJavaScriptFileExtension(path)) { - return path; - } - }); - var filesToWatch = []; - if (typeAcquisition.include) - addInferredTypings(typeAcquisition.include, "Explicitly included types"); - var exclude = typeAcquisition.exclude || []; - // Directories to search for package.json, bower.json and other typing information - var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath); - possibleSearchDirs.set(projectRootPath, true); - possibleSearchDirs.forEach(function (_true, searchDir) { - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); - }); - getTypingNamesFromSourceFileNames(fileNames); - // add typings for unresolved imports - if (unresolvedImports) { - var module = ts.deduplicate(unresolvedImports.map(function (moduleId) { return nodeCoreModules.has(moduleId) ? "node" : moduleId; }), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive); - addInferredTypings(module, "Inferred typings from unresolved imports"); - } - // Add the cached typing locations for inferred typings that are already installed - packageNameToTypingLocation.forEach(function (typing, name) { - if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && isTypingUpToDate(typing, typesRegistry.get(name))) { - inferredTypings.set(name, typing.typingLocation); - } - }); - // Remove typings that the user has added to the exclude list - for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) { - var excludeTypingName = exclude_1[_i]; - var didDelete = inferredTypings.delete(excludeTypingName); - if (didDelete && log) - log("Typing for " + excludeTypingName + " is in exclude list, will be ignored."); - } - var newTypingNames = []; - var cachedTypingPaths = []; - inferredTypings.forEach(function (inferred, typing) { - if (inferred !== undefined) { - cachedTypingPaths.push(inferred); - } - else { - newTypingNames.push(typing); - } - }); - var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; - if (log) - log("Result: " + JSON.stringify(result)); - return result; - function addInferredTyping(typingName) { - if (!inferredTypings.has(typingName)) { - inferredTypings.set(typingName, undefined); - } - } - function addInferredTypings(typingNames, message) { - if (log) - log(message + ": " + JSON.stringify(typingNames)); - ts.forEach(typingNames, addInferredTyping); - } - /** - * Get the typing info from common package manager json files like package.json or bower.json - */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (!host.fileExists(jsonPath)) { - return; - } - filesToWatch.push(jsonPath); - var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; - var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); - addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies"); - } - /** - * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" - * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred - * to the 'angular-route' typing name. - * @param fileNames are the names for source files in the project - */ - function getTypingNamesFromSourceFileNames(fileNames) { - var fromFileNames = ts.mapDefined(fileNames, function (j) { - if (!ts.hasJavaScriptFileExtension(j)) - return undefined; - var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase())); - var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName); - return safeList.get(cleanedTypingName); - }); - if (fromFileNames.length) { - addInferredTypings(fromFileNames, "Inferred typings from file names"); - } - var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); }); - if (hasJsxFile) { - if (log) - log("Inferred 'react' typings due to presence of '.jsx' extension"); - addInferredTyping("react"); - } - } - /** - * Infer typing names from packages folder (ex: node_module, bower_components) - * @param packagesFolderPath is the path to the packages folder - */ - function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { - filesToWatch.push(packagesFolderPath); - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(packagesFolderPath)) { - return; - } - // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - if (log) - log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames)); - var packageNames = []; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; - var normalizedFileName = ts.normalizePath(fileName); - var baseFileName = ts.getBaseFileName(normalizedFileName); - if (baseFileName !== "package.json" && baseFileName !== "bower.json") { - continue; - } - var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_5.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (baseFileName === "package.json" && packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - var ownTypes = packageJson.types || packageJson.typings; - if (ownTypes) { - var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); - if (log) - log(" Package '" + packageJson.name + "' provides its own types."); - inferredTypings.set(packageJson.name, absolutePath); - } - else { - packageNames.push(packageJson.name); - } - } - addInferredTypings(packageNames, " Found package names"); - } - } - JsTyping.discoverTypings = discoverTypings; - var PackageNameValidationResult; - (function (PackageNameValidationResult) { - PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; - PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; - PackageNameValidationResult[PackageNameValidationResult["EmptyName"] = 2] = "EmptyName"; - PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 3] = "NameTooLong"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 4] = "NameStartsWithDot"; - PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 5] = "NameStartsWithUnderscore"; - PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 6] = "NameContainsNonURISafeCharacters"; - })(PackageNameValidationResult = JsTyping.PackageNameValidationResult || (JsTyping.PackageNameValidationResult = {})); - var maxPackageNameLength = 214; - /** - * Validates package name using rules defined at https://docs.npmjs.com/files/package.json - */ - function validatePackageName(packageName) { - if (!packageName) { - return 2 /* EmptyName */; - } - if (packageName.length > maxPackageNameLength) { - return 3 /* NameTooLong */; - } - if (packageName.charCodeAt(0) === 46 /* dot */) { - return 4 /* NameStartsWithDot */; - } - if (packageName.charCodeAt(0) === 95 /* _ */) { - return 5 /* NameStartsWithUnderscore */; - } - // check if name is scope package like: starts with @ and has one '/' in the middle - // scoped packages are not currently supported - // TODO: when support will be added we'll need to split and check both scope and package name - if (/^@[^/]+\/[^/]+$/.test(packageName)) { - return 1 /* ScopedPackagesNotSupported */; - } - if (encodeURIComponent(packageName) !== packageName) { - return 6 /* NameContainsNonURISafeCharacters */; - } - return 0 /* Ok */; - } - JsTyping.validatePackageName = validatePackageName; - function renderPackageNameValidationFailure(result, typing) { - switch (result) { - case 2 /* EmptyName */: - return "Package name '" + typing + "' cannot be empty"; - case 3 /* NameTooLong */: - return "Package name '" + typing + "' should be less than " + maxPackageNameLength + " characters"; - case 4 /* NameStartsWithDot */: - return "Package name '" + typing + "' cannot start with '.'"; - case 5 /* NameStartsWithUnderscore */: - return "Package name '" + typing + "' cannot start with '_'"; - case 1 /* ScopedPackagesNotSupported */: - return "Package '" + typing + "' is scoped and currently is not supported"; - case 6 /* NameContainsNonURISafeCharacters */: - return "Package name '" + typing + "' contains non URI safe characters"; - case 0 /* Ok */: - return ts.Debug.fail(); // Shouldn't have called this. - default: - ts.Debug.assertNever(result); - } - } - JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure; - })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); + if (!patternMatcher) + return ts.emptyArray; var rawItems = []; - var _loop_8 = function (sourceFile) { + var _loop_16 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); - if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { + if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; } - ts.forEachEntry(sourceFile.getNamedDeclarations(), function (declarations, name) { + sourceFile.getNamedDeclarations().forEach(function (declarations, name) { getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, sourceFile.fileName, rawItems); }); }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; - _loop_8(sourceFile); + for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { + var sourceFile = sourceFiles_8[_i]; + _loop_16(sourceFile); } rawItems.sort(compareNavigateToItems); - if (maxResultCount !== undefined) { - rawItems = rawItems.slice(0, maxResultCount); - } - return rawItems.map(createNavigateToItem); + return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); } NavigateTo.getNavigateToItems = getNavigateToItems; function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checker, fileName, rawItems) { // First do a quick check to see if the name of the declaration matches the // last portion of the (possibly) dotted name they're searching for. - var matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); - if (!matches) { + var match = patternMatcher.getMatchForLastSegmentOfPattern(name); + if (!match) { return; // continue to next named declarations } - for (var _i = 0, declarations_11 = declarations; _i < declarations_11.length; _i++) { - var declaration = declarations_11[_i]; - if (!shouldKeepItem(declaration, checker)) { + for (var _i = 0, declarations_12 = declarations; _i < declarations_12.length; _i++) { + var declaration = declarations_12[_i]; + if (!shouldKeepItem(declaration, checker)) continue; - } - // It was a match! If the pattern has dots in it, then also see if the - // declaration container matches as well. - var containerMatches = matches; if (patternMatcher.patternContainsDots) { - containerMatches = patternMatcher.getMatches(getContainers(declaration), name); - if (!containerMatches) { - continue; + // If the pattern has dots in it, then also see if the declaration container matches as well. + var fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); + if (fullMatch) { + rawItems.push({ name: name, fileName: fileName, matchKind: fullMatch.kind, isCaseSensitive: fullMatch.isCaseSensitive, declaration: declaration }); } } - var matchKind = bestMatchKind(containerMatches); - var isCaseSensitive = allMatchesAreCaseSensitive(containerMatches); - rawItems.push({ name: name, fileName: fileName, matchKind: matchKind, isCaseSensitive: isCaseSensitive, declaration: declaration }); + else { + rawItems.push({ name: name, fileName: fileName, matchKind: match.kind, isCaseSensitive: match.isCaseSensitive, declaration: declaration }); + } } } function shouldKeepItem(declaration, checker) { switch (declaration.kind) { - case 243 /* ImportClause */: - case 246 /* ImportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - var importer = checker.getSymbolAtLocation(declaration.name); + case 248 /* ImportClause */: + case 251 /* ImportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + var importer = checker.getSymbolAtLocation(declaration.name); // TODO: GH#18217 var imported = checker.getAliasedSymbol(importer); return importer.escapedName !== imported.escapedName; default: return true; } } - function allMatchesAreCaseSensitive(matches) { - ts.Debug.assert(matches.length > 0); - // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - if (!match.isCaseSensitive) { - return false; - } - } - return true; - } function tryAddSingleDeclarationName(declaration, containers) { var name = ts.getNameOfDeclaration(declaration); if (name && ts.isPropertyNameLiteral(name)) { containers.unshift(ts.getTextOfIdentifierOrLiteral(name)); return true; } - else if (name && name.kind === 146 /* ComputedPropertyName */) { + else if (name && name.kind === 147 /* ComputedPropertyName */) { return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); } else { @@ -89654,33 +96487,19 @@ var ts; // First, if we started with a computed property name, then add all but the last // portion into the container array. var name = ts.getNameOfDeclaration(declaration); - if (name.kind === 146 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { - return undefined; - } + if (name && name.kind === 147 /* ComputedPropertyName */ && !tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { + return ts.emptyArray; } // Now, walk up our containers, adding all their names to the container array. - declaration = ts.getContainerNode(declaration); - while (declaration) { - if (!tryAddSingleDeclarationName(declaration, containers)) { - return undefined; + var container = ts.getContainerNode(declaration); + while (container) { + if (!tryAddSingleDeclarationName(container, containers)) { + return ts.emptyArray; } - declaration = ts.getContainerNode(declaration); + container = ts.getContainerNode(container); } return containers; } - function bestMatchKind(matches) { - ts.Debug.assert(matches.length > 0); - var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; - var kind = match.kind; - if (kind < bestMatchKind) { - bestMatchKind = kind; - } - } - return bestMatchKind; - } function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. return ts.compareValues(i1.matchKind, i2.matchKind) @@ -89700,12 +96519,11 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */ + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -89782,7 +96600,7 @@ var ts; } function rootNavigationBarNode(sourceFile) { ts.Debug.assert(!parentsStack.length); - var root = { node: sourceFile, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; + var root = { node: sourceFile, name: undefined, additionalNodes: undefined, parent: undefined, children: undefined, indent: 0 }; parent = root; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -89798,6 +96616,7 @@ var ts; function emptyNavigationBarNode(node) { return { node: node, + name: ts.isDeclaration(node) || ts.isExpression(node) ? ts.getNameOfDeclaration(node) : undefined, additionalNodes: undefined, parent: parent, children: undefined, @@ -89818,7 +96637,7 @@ var ts; /** Call after calling `startNode` and adding children to it. */ function endNode() { if (parent.children) { - mergeChildren(parent.children); + mergeChildren(parent.children, parent); sortChildren(parent.children); } parent = parentsStack.pop(); @@ -89835,7 +96654,7 @@ var ts; return; } switch (node.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: // Get parameter properties, and treat them as being on the *same* level as the constructor, not under it. var ctr = node; addNodeWithRecursiveChild(ctr, ctr.body); @@ -89847,33 +96666,33 @@ var ts; } } break; - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 152 /* MethodSignature */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 153 /* MethodSignature */: if (!ts.hasDynamicName(node)) { addNodeWithRecursiveChild(node, node.body); } break; - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: if (!ts.hasDynamicName(node)) { addLeafNode(node); } break; - case 243 /* ImportClause */: + case 248 /* ImportClause */: var importClause = node; // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addLeafNode(importClause); + addLeafNode(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; var namedBindings = importClause.namedBindings; if (namedBindings) { - if (namedBindings.kind === 244 /* NamespaceImport */) { + if (namedBindings.kind === 249 /* NamespaceImport */) { addLeafNode(namedBindings); } else { @@ -89884,8 +96703,8 @@ var ts; } } break; - case 180 /* BindingElement */: - case 230 /* VariableDeclaration */: + case 184 /* BindingElement */: + case 235 /* VariableDeclaration */: var _d = node, name = _d.name, initializer = _d.initializer; if (ts.isBindingPattern(name)) { addChildrenRecursively(name); @@ -89906,12 +96725,12 @@ var ts; addNodeWithRecursiveChild(node, initializer); } break; - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: addNodeWithRecursiveChild(node, node.body); break; - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: startNode(node); for (var _e = 0, _f = node.members; _e < _f.length; _e++) { var member = _f[_e]; @@ -89921,9 +96740,9 @@ var ts; } endNode(); break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: startNode(node); for (var _g = 0, _h = node.members; _g < _h.length; _g++) { var member = _h[_g]; @@ -89931,18 +96750,18 @@ var ts; } endNode(); break; - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: addNodeWithRecursiveChild(node, getInteriorModule(node).body); break; - case 250 /* ExportSpecifier */: - case 241 /* ImportEqualsDeclaration */: - case 159 /* IndexSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 235 /* TypeAliasDeclaration */: + case 255 /* ExportSpecifier */: + case 246 /* ImportEqualsDeclaration */: + case 160 /* IndexSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 240 /* TypeAliasDeclaration */: addLeafNode(node); break; - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var special = ts.getSpecialPropertyAssignmentKind(node); switch (special) { case 1 /* ExportsProperty */: @@ -89950,7 +96769,7 @@ var ts; case 3 /* PrototypeProperty */: case 6 /* Prototype */: addNodeWithRecursiveChild(node, node.right); - break; + return; case 4 /* ThisProperty */: case 5 /* Property */: case 0 /* None */: @@ -89964,7 +96783,7 @@ var ts; if (ts.hasJSDocNodes(node)) { ts.forEach(node.jsDoc, function (jsDoc) { ts.forEach(jsDoc.tags, function (tag) { - if (tag.kind === 291 /* JSDocTypedefTag */) { + if (ts.isJSDocTypeAlias(tag)) { addLeafNode(tag); } }); @@ -89974,7 +96793,7 @@ var ts; } } /** Merge declarations of the same kind. */ - function mergeChildren(children) { + function mergeChildren(children, node) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { var declName = ts.getNameOfDeclaration(child.node); @@ -89991,7 +96810,7 @@ var ts; if (itemsWithSameName instanceof Array) { for (var _i = 0, itemsWithSameName_1 = itemsWithSameName; _i < itemsWithSameName_1.length; _i++) { var itemWithSameName = itemsWithSameName_1[_i]; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } } @@ -90000,7 +96819,7 @@ var ts; } else { var itemWithSameName = itemsWithSameName; - if (tryMerge(itemWithSameName, child)) { + if (tryMerge(itemWithSameName, child, node)) { return false; } nameToItems.set(name, [itemWithSameName, child]); @@ -90008,37 +96827,45 @@ var ts; } }); } - function tryMerge(a, b) { - if (shouldReallyMerge(a.node, b.node)) { + function tryMerge(a, b, parent) { + if (shouldReallyMerge(a.node, b.node, parent)) { merge(a, b); return true; } return false; } /** a and b have the same name, but they may not be mergeable. */ - function shouldReallyMerge(a, b) { - if (a.kind !== b.kind) { + function shouldReallyMerge(a, b, parent) { + if (a.kind !== b.kind || a.parent !== b.parent && !(isOwnChild(a, parent) && isOwnChild(b, parent))) { return false; } switch (a.kind) { - case 151 /* PropertyDeclaration */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 152 /* PropertyDeclaration */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: return ts.hasModifier(a, 32 /* Static */) === ts.hasModifier(b, 32 /* Static */); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: return areSameModule(a, b); default: return true; } } + // We want to merge own children like `I` in in `module A { interface I {} } module A { interface I {} }` + // We don't want to merge unrelated children like `m` in `const o = { a: { m() {} }, b: { m() {} } };` + function isOwnChild(n, parent) { + var par = ts.isModuleBlock(n.parent) ? n.parent.parent : n.parent; + return par === parent.node || ts.contains(parent.additionalNodes, par); + } // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { - return a.body.kind === b.body.kind && (a.body.kind !== 237 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); + // TODO: GH#18217 + return a.body.kind === b.body.kind && (a.body.kind !== 242 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ function merge(target, source) { + var _a; target.additionalNodes = target.additionalNodes || []; target.additionalNodes.push(source.node); if (source.additionalNodes) { @@ -90046,17 +96873,16 @@ var ts; } target.children = ts.concatenate(target.children, source.children); if (target.children) { - mergeChildren(target.children); + mergeChildren(target.children, target); sortChildren(target.children); } - var _a; } /** Recursively ensure that each NavNode's children are in sorted order. */ function sortChildren(children) { children.sort(compareChildren); } function compareChildren(child1, child2) { - return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) + return ts.compareStringsCaseSensitiveUI(tryGetName(child1.node), tryGetName(child2.node)) // TODO: GH#18217 || ts.compareValues(navigationBarNodeKind(child1), navigationBarNodeKind(child2)); } /** @@ -90065,29 +96891,26 @@ var ts; * So `new()` can still come before an `aardvark` method. */ function tryGetName(node) { - if (node.kind === 237 /* ModuleDeclaration */) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } var declName = ts.getNameOfDeclaration(node); if (declName) { - return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); + return ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(declName)); // TODO: GH#18217 } switch (node.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 203 /* ClassExpression */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 207 /* ClassExpression */: return getFunctionOrClassName(node); - case 291 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return undefined; } } - function getItemName(node) { - if (node.kind === 237 /* ModuleDeclaration */) { + function getItemName(node, name) { + if (node.kind === 242 /* ModuleDeclaration */) { return getModuleName(node); } - var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -90095,16 +96918,16 @@ var ts; } } switch (node.kind) { - case 272 /* SourceFile */: + case 277 /* SourceFile */: var sourceFile = node; return ts.isExternalModule(sourceFile) ? "\"" + ts.escapeString(ts.getBaseFileName(ts.removeFileExtension(ts.normalizePath(sourceFile.fileName)))) + "\"" : ""; - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: if (ts.getModifierFlags(node) & 512 /* Default */) { return "default"; } @@ -90112,37 +96935,18 @@ var ts; // (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the // navigation bar. return getFunctionOrClassName(node); - case 154 /* Constructor */: + case 155 /* Constructor */: return "constructor"; - case 158 /* ConstructSignature */: + case 159 /* ConstructSignature */: return "new()"; - case 157 /* CallSignature */: + case 158 /* CallSignature */: return "()"; - case 159 /* IndexSignature */: + case 160 /* IndexSignature */: return "[]"; - case 291 /* JSDocTypedefTag */: - return getJSDocTypedefTagName(node); default: return ""; } } - function getJSDocTypedefTagName(node) { - if (node.name) { - return node.name.text; - } - else { - var parentNode = node.parent && node.parent.parent; - if (parentNode && parentNode.kind === 212 /* VariableStatement */) { - if (parentNode.declarationList.declarations.length > 0) { - var nameIdentifier = parentNode.declarationList.declarations[0].name; - if (nameIdentifier.kind === 71 /* Identifier */) { - return nameIdentifier.text; - } - } - } - return ""; - } - } /** Flattens the NavNode tree to a list, keeping only the top-level items. */ function topLevelItems(root) { var topLevel = []; @@ -90161,24 +96965,25 @@ var ts; return topLevel; function isTopLevel(item) { switch (navigationBarNodeKind(item)) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 236 /* EnumDeclaration */: - case 234 /* InterfaceDeclaration */: - case 237 /* ModuleDeclaration */: - case 272 /* SourceFile */: - case 235 /* TypeAliasDeclaration */: - case 291 /* JSDocTypedefTag */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 241 /* EnumDeclaration */: + case 239 /* InterfaceDeclaration */: + case 242 /* ModuleDeclaration */: + case 277 /* SourceFile */: + case 240 /* TypeAliasDeclaration */: + case 301 /* JSDocTypedefTag */: + case 295 /* JSDocCallbackTag */: return true; - case 154 /* Constructor */: - case 153 /* MethodDeclaration */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 230 /* VariableDeclaration */: + case 155 /* Constructor */: + case 154 /* MethodDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 235 /* VariableDeclaration */: return hasSomeImportantChild(item); - case 191 /* ArrowFunction */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: return isTopLevelFunctionDeclaration(item); default: return false; @@ -90188,35 +96993,36 @@ var ts; return false; } switch (navigationBarNodeKind(item.parent)) { - case 238 /* ModuleBlock */: - case 272 /* SourceFile */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: + case 243 /* ModuleBlock */: + case 277 /* SourceFile */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: return true; default: return hasSomeImportantChild(item); } } function hasSomeImportantChild(item) { - return ts.forEach(item.children, function (child) { + return ts.some(item.children, function (child) { var childKind = navigationBarNodeKind(child); - return childKind !== 230 /* VariableDeclaration */ && childKind !== 180 /* BindingElement */; + return childKind !== 235 /* VariableDeclaration */ && childKind !== 184 /* BindingElement */; }); } } } function convertToTree(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: getModifiers(n.node), spans: getSpans(n), + nameSpan: n.name && getNodeSpan(n.name), childItems: ts.map(n.children, convertToTree) }; } function convertToTopLevelItem(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: getModifiers(n.node), spans: getSpans(n), @@ -90227,7 +97033,7 @@ var ts; }; function convertToChildItem(n) { return { - text: getItemName(n.node), + text: getItemName(n.node, n.name), kind: ts.getNodeKind(n.node), kindModifiers: ts.getNodeModifiers(n.node), spans: getSpans(n), @@ -90256,7 +97062,7 @@ var ts; // Otherwise, we need to aggregate each identifier to build up the qualified name. var result = []; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); - while (moduleDeclaration.body && moduleDeclaration.body.kind === 237 /* ModuleDeclaration */) { + while (moduleDeclaration.body && moduleDeclaration.body.kind === 242 /* ModuleDeclaration */) { moduleDeclaration = moduleDeclaration.body; result.push(ts.getTextOfIdentifierOrLiteral(moduleDeclaration.name)); } @@ -90267,16 +97073,16 @@ var ts; * We store 'A' as associated with a NavNode, and use getModuleName to traverse down again. */ function getInteriorModule(decl) { - return decl.body.kind === 237 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; + return decl.body.kind === 242 /* ModuleDeclaration */ ? getInteriorModule(decl.body) : decl; // TODO: GH#18217 } function isComputedProperty(member) { - return !member.name || member.name.kind === 146 /* ComputedPropertyName */; + return !member.name || member.name.kind === 147 /* ComputedPropertyName */; } function getNodeSpan(node) { - return node.kind === 272 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); + return node.kind === 277 /* SourceFile */ ? ts.createTextSpanFromRange(node) : ts.createTextSpanFromNode(node, curSourceFile); } function getModifiers(node) { - if (node.parent && node.parent.kind === 230 /* VariableDeclaration */) { + if (node.parent && node.parent.kind === 235 /* VariableDeclaration */) { node = node.parent; } return ts.getNodeModifiers(node); @@ -90286,16 +97092,16 @@ var ts; return ts.declarationNameToString(node.name); } // See if it is a var initializer. If so, use the var name. - else if (node.parent.kind === 230 /* VariableDeclaration */) { + else if (node.parent.kind === 235 /* VariableDeclaration */) { return ts.declarationNameToString(node.parent.name); } // See if it is of the form " = function(){...}". If so, use the text from the left-hand side. - else if (node.parent.kind === 198 /* BinaryExpression */ && + else if (node.parent.kind === 202 /* BinaryExpression */ && node.parent.operatorToken.kind === 58 /* EqualsToken */) { return nodeText(node.parent.left).replace(whiteSpaceRegex, ""); } // See if it is a property assignment, and if so use the property name - else if (node.parent.kind === 268 /* PropertyAssignment */ && node.parent.name) { + else if (node.parent.kind === 273 /* PropertyAssignment */ && node.parent.name) { return nodeText(node.parent.name); } // Default exports are named "default" @@ -90308,9 +97114,9 @@ var ts; } function isFunctionOrClassExpression(node) { switch (node.kind) { - case 191 /* ArrowFunction */: - case 190 /* FunctionExpression */: - case 203 /* ClassExpression */: + case 195 /* ArrowFunction */: + case 194 /* FunctionExpression */: + case 207 /* ClassExpression */: return true; default: return false; @@ -90329,56 +97135,68 @@ var ts; * 2) Coalescing imports from the same module * 3) Sorting imports */ - function organizeImports(sourceFile, formatContext, host, program) { + function organizeImports(sourceFile, formatContext, host, program, _preferences) { var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext }); + var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); }; // All of the old ImportDeclarations in the file, in syntactic order. var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(topLevelImportDecls); + organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports); + // All of the old ExportDeclarations in the file, in syntactic order. + var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); + var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); - organizeImportsWorker(ambientModuleImportDecls); + organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); + var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); - function organizeImportsWorker(oldImportDecls) { + function organizeImportsWorker(oldImportDecls, coalesce) { if (ts.length(oldImportDecls) === 0) { return; } + // Special case: normally, we'd expect leading and trailing trivia to follow each import + // around as it's sorted. However, we do not want this to happen for leading trivia + // on the first import because it is probably the header comment for the file. + // Consider: we could do a more careful check that this trivia is actually a header, + // but the consequences of being wrong are very minor. + ts.suppressLeadingTrivia(oldImportDecls[0]); var oldImportGroups = ts.group(oldImportDecls, function (importDecl) { return getExternalModuleName(importDecl.moduleSpecifier); }); var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); }); var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) { return getExternalModuleName(importGroup[0].moduleSpecifier) - ? coalesceImports(removeUnusedImports(importGroup, sourceFile, program)) + ? coalesce(importGroup) : importGroup; }); // Delete or replace the first import. if (newImportDecls.length === 0) { - changeTracker.deleteNode(sourceFile, oldImportDecls[0]); + changeTracker.delete(sourceFile, oldImportDecls[0]); } else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: false, + useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false, suffix: ts.getNewLineOrDefaultFromHost(host, formatContext.options), }); } // Delete any subsequent imports. for (var i = 1; i < oldImportDecls.length; i++) { - changeTracker.deleteNode(sourceFile, oldImportDecls[i]); + changeTracker.delete(sourceFile, oldImportDecls[i]); } } } OrganizeImports.organizeImports = organizeImports; function getModuleBlock(moduleDecl) { var body = moduleDecl.body; - return body && !ts.isIdentifier(body) && (ts.isModuleBlock(body) ? body : getModuleBlock(body)); + return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(); - var jsxContext = sourceFile.languageVariant === 1 /* JSX */ && program.getCompilerOptions().jsx; + var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -90402,7 +97220,7 @@ var ts; } else { // List of named imports - var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.propertyName || e.name); }); + var newElements = namedBindings.elements.filter(function (e) { return isDeclarationUsed(e.name); }); if (newElements.length < namedBindings.elements.length) { namedBindings = newElements.length ? ts.updateNamedImports(namedBindings, newElements) @@ -90416,12 +97234,12 @@ var ts; } return usedImports; function isDeclarationUsed(identifier) { - // The JSX factory symbol is always used. - return jsxContext && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); + // The JSX factory symbol is always used if JSX elements are present - even if they are not allowed. + return jsxElementsPresent && (identifier.text === jsxNamespace) || ts.FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile); } } function getExternalModuleName(specifier) { - return ts.isStringLiteral(specifier) || ts.isNoSubstitutionTemplateLiteral(specifier) + return specifier !== undefined && ts.isStringLiteralLike(specifier) ? specifier.text : undefined; } @@ -90443,16 +97261,16 @@ var ts; if (defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) { // Add the namespace import to the existing default ImportDeclaration. var defaultImport = defaultImports[0]; - coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(defaultImport, defaultImport.importClause.name, namespaceImports[0].importClause.namedBindings)); // TODO: GH#18217 return coalescedImports; } var sortedNamespaceImports = ts.stableSort(namespaceImports, function (i1, i2) { return compareIdentifiers(i1.importClause.namedBindings.name, i2.importClause.namedBindings.name); - }); + }); // TODO: GH#18217 for (var _i = 0, sortedNamespaceImports_1 = sortedNamespaceImports; _i < sortedNamespaceImports_1.length; _i++) { var namespaceImport = sortedNamespaceImports_1[_i]; // Drop the name, if any - coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); + coalescedImports.push(updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause.namedBindings)); // TODO: GH#18217 } if (defaultImports.length === 0 && namedImports.length === 0) { return coalescedImports; @@ -90465,22 +97283,21 @@ var ts; else { for (var _b = 0, defaultImports_1 = defaultImports; _b < defaultImports_1.length; _b++) { var defaultImport = defaultImports_1[_b]; - newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); + newImportSpecifiers.push(ts.createImportSpecifier(ts.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); - var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) { - return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || - compareIdentifiers(s1.name, s2.name); - }); + newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] : namedImports[0]; var newNamedImports = sortedImportSpecifiers.length === 0 - ? undefined + ? newDefaultImport + ? undefined + : ts.createNamedImports(ts.emptyArray) : namedImports.length === 0 ? ts.createNamedImports(sortedImportSpecifiers) - : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); + : ts.updateNamedImports(namedImports[0].importClause.namedBindings, sortedImportSpecifiers); // TODO: GH#18217 coalescedImports.push(updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports)); return coalescedImports; /* @@ -90523,13 +97340,65 @@ var ts; namedImports: namedImports, }; } - function compareIdentifiers(s1, s2) { - return ts.compareStringsCaseSensitive(s1.text, s2.text); - } } OrganizeImports.coalesceImports = coalesceImports; + /* @internal */ // Internal for testing + /** + * @param exportGroup a list of ExportDeclarations, all with the same module name. + */ + function coalesceExports(exportGroup) { + if (exportGroup.length === 0) { + return exportGroup; + } + var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports; + var coalescedExports = []; + if (exportWithoutClause) { + coalescedExports.push(exportWithoutClause); + } + if (namedExports.length === 0) { + return coalescedExports; + } + var newExportSpecifiers = []; + newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; })); + var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers); + var exportDecl = namedExports[0]; + coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier)); + return coalescedExports; + /* + * Returns entire export declarations because they may already have been rewritten and + * may lack parent pointers. The desired parts can easily be recovered based on the + * categorization. + */ + function getCategorizedExports(exportGroup) { + var exportWithoutClause; + var namedExports = []; + for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) { + var exportDeclaration = exportGroup_1[_i]; + if (exportDeclaration.exportClause === undefined) { + // Only the first such export is interesting - the others are redundant. + // Note: Unfortunately, we will lose trivia that was on this node. + exportWithoutClause = exportWithoutClause || exportDeclaration; + } + else { + namedExports.push(exportDeclaration); + } + } + return { + exportWithoutClause: exportWithoutClause, + namedExports: namedExports, + }; + } + } + OrganizeImports.coalesceExports = coalesceExports; function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) { - return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier); + return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), // TODO: GH#18217 + importDeclaration.moduleSpecifier); + } + function sortSpecifiers(specifiers) { + return ts.stableSort(specifiers, function (s1, s2) { + return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) || + compareIdentifiers(s1.name, s2.name); + }); } /* internal */ // Exported for testing function compareModuleSpecifiers(m1, m2) { @@ -90537,9 +97406,12 @@ var ts; var name2 = getExternalModuleName(m2); return ts.compareBooleans(name1 === undefined, name2 === undefined) || ts.compareBooleans(ts.isExternalModuleNameRelative(name1), ts.isExternalModuleNameRelative(name2)) || - ts.compareStringsCaseSensitive(name1, name2); + ts.compareStringsCaseInsensitive(name1, name2); } OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers; + function compareIdentifiers(s1, s2) { + return ts.compareStringsCaseInsensitive(s1.text, s2.text); + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -90556,7 +97428,27 @@ var ts; OutliningElementsCollector.collectElements = collectElements; function addNodeOutliningSpans(sourceFile, cancellationToken, out) { var depthRemaining = 40; - sourceFile.forEachChild(function walk(n) { + var current = 0; + var statements = sourceFile.statements; + var n = statements.length; + while (current < n) { + while (current < n && !ts.isAnyImportSyntax(statements[current])) { + visitNonImportNode(statements[current]); + current++; + } + if (current === n) + break; + var firstImport = current; + while (current < n && ts.isAnyImportSyntax(statements[current])) { + addOutliningForLeadingCommentsForNode(statements[current], sourceFile, cancellationToken, out); + current++; + } + var lastImport = current - 1; + if (lastImport !== firstImport) { + out.push(createOutliningSpanFromBounds(ts.findChildOfKind(statements[firstImport], 91 /* ImportKeyword */, sourceFile).getStart(sourceFile), statements[lastImport].getEnd(), "imports" /* Imports */)); + } + } + function visitNonImportNode(n) { if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); @@ -90567,9 +97459,19 @@ var ts; if (span) out.push(span); depthRemaining--; - n.forEachChild(walk); + if (ts.isIfStatement(n) && n.elseStatement && ts.isIfStatement(n.elseStatement)) { + // Consider an 'else if' to be on the same depth as the 'if'. + visitNonImportNode(n.expression); + visitNonImportNode(n.thenStatement); + depthRemaining++; + visitNonImportNode(n.elseStatement); + depthRemaining--; + } + else { + n.forEachChild(visitNonImportNode); + } depthRemaining++; - }); + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -90578,13 +97480,13 @@ var ts; var currentLineStart = lineStarts[i]; var lineEnd = i + 1 === lineStarts.length ? sourceFile.getEnd() : lineStarts[i + 1] - 1; var lineText = sourceFile.text.substring(currentLineStart, lineEnd); - var result = lineText.match(/^\s*\/\/\s*#(end)?region(?:\s+(.*))?$/); + var result = isRegionDelimiter(lineText); if (!result || ts.isInComment(sourceFile, currentLineStart)) { continue; } if (!result[1]) { - var span_12 = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); - regions.push(createOutliningSpan(span_12, span_12, /*autoCollapse*/ false, result[2] || "#region")); + var span = ts.createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); + regions.push(createOutliningSpan(span, "region" /* Region */, span, /*autoCollapse*/ false, result[2] || "#region")); } else { var region = regions.pop(); @@ -90596,6 +97498,10 @@ var ts; } } } + var regionDelimiterRegExp = /^\s*\/\/\s*#(end)?region(?:\s+(.*))?(?:\r)?$/; + function isRegionDelimiter(lineText) { + return regionDelimiterRegExp.exec(lineText); + } function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { var comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); if (!comments) @@ -90603,11 +97509,19 @@ var ts; var firstSingleLineCommentStart = -1; var lastSingleLineCommentEnd = -1; var singleLineCommentCount = 0; - for (var _i = 0, comments_3 = comments; _i < comments_3.length; _i++) { - var _a = comments_3[_i], kind = _a.kind, pos = _a.pos, end = _a.end; + var sourceText = sourceFile.getFullText(); + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var _a = comments_2[_i], kind = _a.kind, pos = _a.pos, end = _a.end; cancellationToken.throwIfCancellationRequested(); switch (kind) { case 2 /* SingleLineCommentTrivia */: + // never fold region delimiters into single-line comment regions + var commentText = sourceText.slice(pos, end); + if (isRegionDelimiter(commentText)) { + combineAndAddMultipleSingleLineComments(); + singleLineCommentCount = 0; + break; + } // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (singleLineCommentCount === 0) { @@ -90618,7 +97532,7 @@ var ts; break; case 3 /* MultiLineCommentTrivia */: combineAndAddMultipleSingleLineComments(); - out.push(createOutliningSpanFromBounds(pos, end)); + out.push(createOutliningSpanFromBounds(pos, end, "comment" /* Comment */)); singleLineCommentCount = 0; break; default: @@ -90629,33 +97543,33 @@ var ts; function combineAndAddMultipleSingleLineComments() { // Only outline spans of two or more consecutive single line comments if (singleLineCommentCount > 1) { - out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd)); + out.push(createOutliningSpanFromBounds(firstSingleLineCommentStart, lastSingleLineCommentEnd, "comment" /* Comment */)); } } } - function createOutliningSpanFromBounds(pos, end) { - return createOutliningSpan(ts.createTextSpanFromBounds(pos, end)); + function createOutliningSpanFromBounds(pos, end, kind) { + return createOutliningSpan(ts.createTextSpanFromBounds(pos, end), kind); } function getOutliningSpanForNode(n, sourceFile) { switch (n.kind) { - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(n)) { - return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 191 /* ArrowFunction */); + return spanForNode(n.parent, /*autoCollapse*/ n.parent.kind !== 195 /* ArrowFunction */); } // 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. switch (n.parent.kind) { - case 216 /* DoStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 215 /* IfStatement */: - case 217 /* WhileStatement */: - case 224 /* WithStatement */: - case 267 /* CatchClause */: + case 221 /* DoStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 222 /* WhileStatement */: + case 229 /* WithStatement */: + case 272 /* CatchClause */: return spanForNode(n.parent); - case 228 /* TryStatement */: + case 233 /* TryStatement */: // Could be the try-block, or the finally-block. var tryStatement = n.parent; if (tryStatement.tryBlock === n) { @@ -90668,19 +97582,36 @@ var ts; default: // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. - return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile)); + return createOutliningSpan(ts.createTextSpanFromNode(n, sourceFile), "code" /* Code */); } - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanForNode(n.parent); - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 239 /* CaseBlock */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 244 /* CaseBlock */: return spanForNode(n); - case 182 /* ObjectLiteralExpression */: + case 186 /* ObjectLiteralExpression */: return spanForObjectOrArrayLiteral(n); - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return spanForObjectOrArrayLiteral(n, 21 /* OpenBracketToken */); + case 258 /* JsxElement */: + return spanForJSXElement(n); + case 259 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + return spanForJSXAttributes(n.attributes); + } + function spanForJSXElement(node) { + var textSpan = ts.createTextSpanFromBounds(node.openingElement.getStart(sourceFile), node.closingElement.getEnd()); + var tagName = node.openingElement.tagName.getText(sourceFile); + var bannerText = "<" + tagName + ">..."; + return createOutliningSpan(textSpan, "code" /* Code */, textSpan, /*autoCollapse*/ false, bannerText); + } + function spanForJSXAttributes(node) { + if (node.properties.length === 0) { + return undefined; + } + return createOutliningSpanFromBounds(node.getStart(sourceFile), node.getEnd(), "code" /* Code */); } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 17 /* OpenBraceToken */; } @@ -90700,14 +97631,14 @@ var ts; return undefined; } var textSpan = ts.createTextSpanFromBounds(useFullStart ? openToken.getFullStart() : openToken.getStart(sourceFile), closeToken.getEnd()); - return createOutliningSpan(textSpan, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); + return createOutliningSpan(textSpan, "code" /* Code */, ts.createTextSpanFromNode(hintSpanNode, sourceFile), autoCollapse); } } - function createOutliningSpan(textSpan, hintSpan, autoCollapse, bannerText) { + function createOutliningSpan(textSpan, kind, hintSpan, autoCollapse, bannerText) { if (hintSpan === void 0) { hintSpan = textSpan; } if (autoCollapse === void 0) { autoCollapse = false; } if (bannerText === void 0) { bannerText = "..."; } - return { textSpan: textSpan, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; + return { textSpan: textSpan, kind: kind, hintSpan: hintSpan, bannerText: bannerText, autoCollapse: autoCollapse }; } })(OutliningElementsCollector = ts.OutliningElementsCollector || (ts.OutliningElementsCollector = {})); })(ts || (ts = {})); @@ -90722,12 +97653,10 @@ var ts; PatternMatchKind[PatternMatchKind["substring"] = 2] = "substring"; PatternMatchKind[PatternMatchKind["camelCase"] = 3] = "camelCase"; })(PatternMatchKind = ts.PatternMatchKind || (ts.PatternMatchKind = {})); - function createPatternMatch(kind, punctuationStripped, isCaseSensitive, camelCaseWeight) { + function createPatternMatch(kind, isCaseSensitive) { return { kind: kind, - punctuationStripped: punctuationStripped, - isCaseSensitive: isCaseSensitive, - camelCaseWeight: camelCaseWeight + isCaseSensitive: isCaseSensitive }; } function createPatternMatcher(pattern) { @@ -90736,318 +97665,232 @@ var ts; // such, we cache the information we compute about the candidate for the life of this // pattern matcher so we don't have to compute it multiple times. var stringToWordSpans = ts.createMap(); - pattern = pattern.trim(); - var dotSeparatedSegments = pattern.split(".").map(function (p) { return createSegment(p.trim()); }); - var invalidPattern = dotSeparatedSegments.length === 0 || ts.forEach(dotSeparatedSegments, segmentIsInvalid); + var dotSeparatedSegments = pattern.trim().split(".").map(function (p) { return createSegment(p.trim()); }); + // A segment is considered invalid if we couldn't find any words in it. + if (dotSeparatedSegments.some(function (segment) { return !segment.subWordTextChunks.length; })) + return undefined; return { - getMatches: getMatches, - getMatchesForLastSegmentOfPattern: getMatchesForLastSegmentOfPattern, + getFullMatch: function (containers, candidate) { return getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans); }, + getMatchForLastSegmentOfPattern: function (candidate) { return matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); }, patternContainsDots: dotSeparatedSegments.length > 1 }; - // Quick checks so we can bail out when asked to match a candidate. - function skipMatch(candidate) { - return invalidPattern || !candidate; - } - function getMatchesForLastSegmentOfPattern(candidate) { - if (skipMatch(candidate)) { - return undefined; - } - return matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); - } - function getMatches(candidateContainers, candidate) { - if (skipMatch(candidate)) { - return undefined; - } - // First, check that the last part of the dot separated pattern matches the name of the - // candidate. If not, then there's no point in proceeding and doing the more - // expensive work. - var candidateMatch = matchSegment(candidate, ts.lastOrUndefined(dotSeparatedSegments)); - if (!candidateMatch) { - return undefined; - } - candidateContainers = candidateContainers || []; - // -1 because the last part was checked against the name, and only the rest - // of the parts are checked against the container. - if (dotSeparatedSegments.length - 1 > candidateContainers.length) { - // There weren't enough container parts to match against the pattern parts. - // So this definitely doesn't match. - return undefined; - } - // So far so good. Now break up the container for the candidate and check if all - // the dotted parts match up correctly. - var totalMatch = candidateMatch; - for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { - var segment = dotSeparatedSegments[i]; - var containerName = candidateContainers[j]; - var containerMatch = matchSegment(containerName, segment); - if (!containerMatch) { - // This container didn't match the pattern piece. So there's no match at all. - return undefined; - } - ts.addRange(totalMatch, containerMatch); - } - // Success, this symbol's full name matched against the dotted name the user was asking - // about. - return totalMatch; - } - function getWordSpans(word) { - var spans = stringToWordSpans.get(word); - if (!spans) { - stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); - } - return spans; - } - function matchTextChunk(candidate, chunk, punctuationStripped) { - var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); - if (index === 0) { - if (chunk.text.length === candidate.length) { - // a) Check if the part matches the candidate entirely, in an case insensitive or - // sensitive manner. If it does, return that there was an exact match. - return createPatternMatch(PatternMatchKind.exact, punctuationStripped, /*isCaseSensitive:*/ candidate === chunk.text); - } - else { - // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive - // manner. If it does, return that there was a prefix match. - return createPatternMatch(PatternMatchKind.prefix, punctuationStripped, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); - } - } - var isLowercase = chunk.isLowerCase; - if (isLowercase) { - if (index > 0) { - // c) If the part is entirely lowercase, then check if it is contained anywhere in the - // candidate in a case insensitive manner. If so, return that there was a substring - // match. - // - // Note: We only have a substring match if the lowercase part is prefix match of some - // word part. That way we don't match something like 'Class' when the user types 'a'. - // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). - var wordSpans = getWordSpans(candidate); - for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { - var span_13 = wordSpans_1[_i]; - if (partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ true)) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, - /*isCaseSensitive:*/ partStartsWith(candidate, span_13, chunk.text, /*ignoreCase:*/ false)); - } - } - } - } - else { - // d) If the part was not entirely lowercase, then check if it is contained in the - // candidate in a case *sensitive* manner. If so, return that there was a substring - // match. - if (candidate.indexOf(chunk.text) > 0) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ true); - } - } - if (!isLowercase) { - // e) If the part was not entirely lowercase, then attempt a camel cased match as well. - if (chunk.characterSpans.length > 0) { - var candidateParts = getWordSpans(candidate); - var camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false); - if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ true, /*camelCaseWeight:*/ camelCaseWeight); - } - camelCaseWeight = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true); - if (camelCaseWeight !== undefined) { - return createPatternMatch(PatternMatchKind.camelCase, punctuationStripped, /*isCaseSensitive:*/ false, /*camelCaseWeight:*/ camelCaseWeight); - } - } - } - if (isLowercase) { - // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? - // We could check every character boundary start of the candidate for the pattern. However, that's - // an m * n operation in the wost case. Instead, find the first instance of the pattern - // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to - // filter the list based on a substring that starts on a capital letter and also with a lowercase one. - // (Pattern: fogbar, Candidate: quuxfogbarFogBar). - if (chunk.text.length < candidate.length) { - if (index > 0 && isUpperCaseLetter(candidate.charCodeAt(index))) { - return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ false); - } - } - } + } + ts.createPatternMatcher = createPatternMatcher; + function getFullMatch(candidateContainers, candidate, dotSeparatedSegments, stringToWordSpans) { + // First, check that the last part of the dot separated pattern matches the name of the + // candidate. If not, then there's no point in proceeding and doing the more + // expensive work. + var candidateMatch = matchSegment(candidate, ts.last(dotSeparatedSegments), stringToWordSpans); + if (!candidateMatch) { return undefined; } - function containsSpaceOrAsterisk(text) { - for (var i = 0; i < text.length; i++) { - var ch = text.charCodeAt(i); - if (ch === 32 /* space */ || ch === 42 /* asterisk */) { - return true; - } - } - return false; + // -1 because the last part was checked against the name, and only the rest + // of the parts are checked against the container. + if (dotSeparatedSegments.length - 1 > candidateContainers.length) { + // There weren't enough container parts to match against the pattern parts. + // So this definitely doesn't match. + return undefined; } - function matchSegment(candidate, segment) { - // First check if the segment matches as is. This is also useful if the segment contains - // characters we would normally strip when splitting into parts that we also may want to - // match in the candidate. For example if the segment is "@int" and the candidate is - // "@int", then that will show up as an exact match here. - // - // Note: if the segment contains a space or an asterisk then we must assume that it's a - // multi-word segment. - if (!containsSpaceOrAsterisk(segment.totalTextChunk.text)) { - var match = matchTextChunk(candidate, segment.totalTextChunk, /*punctuationStripped:*/ false); - if (match) { - return [match]; - } - } - // The logic for pattern matching is now as follows: - // - // 1) Break the segment passed in into words. Breaking is rather simple and a - // good way to think about it that if gives you all the individual alphanumeric words - // of the pattern. - // - // 2) For each word try to match the word against the candidate value. - // - // 3) Matching is as follows: - // - // a) Check if the word matches the candidate entirely, in an case insensitive or - // sensitive manner. If it does, return that there was an exact match. - // - // b) Check if the word is a prefix of the candidate, in a case insensitive or - // sensitive manner. If it does, return that there was a prefix match. - // - // c) If the word is entirely lowercase, then check if it is contained anywhere in the - // candidate in a case insensitive manner. If so, return that there was a substring - // match. - // - // Note: We only have a substring match if the lowercase part is prefix match of - // some word part. That way we don't match something like 'Class' when the user - // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with - // 'a'). - // - // d) If the word was not entirely lowercase, then check if it is contained in the - // candidate in a case *sensitive* manner. If so, return that there was a substring - // match. - // - // e) If the word was not entirely lowercase, then attempt a camel cased match as - // well. - // - // f) The word is all lower case. Is it a case insensitive substring of the candidate starting - // on a part boundary of the candidate? - // - // Only if all words have some sort of match is the pattern considered matched. - var subWordTextChunks = segment.subWordTextChunks; - var matches; - for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { - var subWordTextChunk = subWordTextChunks_1[_i]; - // Try to match the candidate with this word - var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); - if (!result) { - return undefined; - } - matches = matches || []; - matches.push(result); - } - return matches; + var bestMatch; + for (var i = dotSeparatedSegments.length - 2, j = candidateContainers.length - 1; i >= 0; i -= 1, j -= 1) { + bestMatch = betterMatch(bestMatch, matchSegment(candidateContainers[j], dotSeparatedSegments[i], stringToWordSpans)); } - function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { - var patternPartStart = patternSpan ? patternSpan.start : 0; - var patternPartLength = patternSpan ? patternSpan.length : pattern.length; - if (patternPartLength > candidateSpan.length) { - // Pattern part is longer than the candidate part. There can never be a match. - return false; - } - if (ignoreCase) { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); - if (toLowerCase(ch1) !== toLowerCase(ch2)) { - return false; - } - } - } - else { - for (var i = 0; i < patternPartLength; i++) { - var ch1 = pattern.charCodeAt(patternPartStart + i); - var ch2 = candidate.charCodeAt(candidateSpan.start + i); - if (ch1 !== ch2) { - return false; - } - } - } - return true; + return bestMatch; + } + function getWordSpans(word, stringToWordSpans) { + var spans = stringToWordSpans.get(word); + if (!spans) { + stringToWordSpans.set(word, spans = breakIntoWordSpans(word)); } - function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { - var chunkCharacterSpans = chunk.characterSpans; - // Note: we may have more pattern parts than candidate parts. This is because multiple - // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". - // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U - // and I will both match in UI. - var currentCandidate = 0; - var currentChunkSpan = 0; - var firstMatch; - var contiguous; - while (true) { - // Let's consider our termination cases - if (currentChunkSpan === chunkCharacterSpans.length) { - // We did match! We shall assign a weight to this - var weight = 0; - // Was this contiguous? - if (contiguous) { - weight += 1; - } - // Did we start at the beginning of the candidate? - if (firstMatch === 0) { - weight += 2; - } - return weight; + return spans; + } + function matchTextChunk(candidate, chunk, stringToWordSpans) { + var index = indexOfIgnoringCase(candidate, chunk.textLowerCase); + if (index === 0) { + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + return createPatternMatch(chunk.text.length === candidate.length ? PatternMatchKind.exact : PatternMatchKind.prefix, /*isCaseSensitive:*/ ts.startsWith(candidate, chunk.text)); + } + if (chunk.isLowerCase) { + if (index === -1) + return undefined; + // b) If the part is entirely lowercase, then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of some + // word part. That way we don't match something like 'Class' when the user types 'a'. + // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). + var wordSpans = getWordSpans(candidate, stringToWordSpans); + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; + if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); } - else if (currentCandidate === candidateParts.length) { - // No match, since we still have more of the pattern to hit - return undefined; + } + // c) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries? + // We could check every character boundary start of the candidate for the pattern. However, that's + // an m * n operation in the wost case. Instead, find the first instance of the pattern + // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to + // filter the list based on a substring that starts on a capital letter and also with a lowercase one. + // (Pattern: fogbar, Candidate: quuxfogbarFogBar). + if (chunk.text.length < candidate.length && isUpperCaseLetter(candidate.charCodeAt(index))) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ false); + } + } + else { + // d) If the part was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + if (candidate.indexOf(chunk.text) > 0) { + return createPatternMatch(PatternMatchKind.substring, /*isCaseSensitive:*/ true); + } + // e) If the part was not entirely lowercase, then attempt a camel cased match as well. + if (chunk.characterSpans.length > 0) { + var candidateParts = getWordSpans(candidate, stringToWordSpans); + var isCaseSensitive = tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ false) ? true + : tryCamelCaseMatch(candidate, candidateParts, chunk, /*ignoreCase:*/ true) ? false : undefined; + if (isCaseSensitive !== undefined) { + return createPatternMatch(PatternMatchKind.camelCase, isCaseSensitive); } - var candidatePart = candidateParts[currentCandidate]; - var gotOneMatchThisCandidate = false; - // Consider the case of matching SiUI against SimpleUIElement. The candidate parts - // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' - // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to - // still keep matching pattern parts against that candidate part. - for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { - var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; - if (gotOneMatchThisCandidate) { - // We've already gotten one pattern part match in this candidate. We will - // only continue trying to consumer pattern parts if the last part and this - // part are both upper case. - if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || - !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { - break; - } - } - if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { - break; - } - gotOneMatchThisCandidate = true; - firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; - // If we were contiguous, then keep that value. If we weren't, then keep that - // value. If we don't know, then set the value to 'true' as an initial match is - // obviously contiguous. - contiguous = contiguous === undefined ? true : contiguous; - candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); - } - // Check if we matched anything at all. If we didn't, then we need to unset the - // contiguous bit if we currently had it set. - // If we haven't set the bit yet, then that means we haven't matched anything so - // far, and we don't want to change that. - if (!gotOneMatchThisCandidate && contiguous !== undefined) { - contiguous = false; - } - // Move onto the next candidate. - currentCandidate++; } } } - ts.createPatternMatcher = createPatternMatcher; + function matchSegment(candidate, segment, stringToWordSpans) { + // First check if the segment matches as is. This is also useful if the segment contains + // characters we would normally strip when splitting into parts that we also may want to + // match in the candidate. For example if the segment is "@int" and the candidate is + // "@int", then that will show up as an exact match here. + // + // Note: if the segment contains a space or an asterisk then we must assume that it's a + // multi-word segment. + if (every(segment.totalTextChunk.text, function (ch) { return ch !== 32 /* space */ && ch !== 42 /* asterisk */; })) { + var match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); + if (match) + return match; + } + // The logic for pattern matching is now as follows: + // + // 1) Break the segment passed in into words. Breaking is rather simple and a + // good way to think about it that if gives you all the individual alphanumeric words + // of the pattern. + // + // 2) For each word try to match the word against the candidate value. + // + // 3) Matching is as follows: + // + // a) Check if the word is a prefix of the candidate, in a case insensitive or + // sensitive manner. If it does, return that there was an exact match if the word and candidate are the same length, else a prefix match. + // + // If the word is entirely lowercase: + // b) Then check if it is contained anywhere in the + // candidate in a case insensitive manner. If so, return that there was a substring + // match. + // + // Note: We only have a substring match if the lowercase part is prefix match of + // some word part. That way we don't match something like 'Class' when the user + // types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with + // 'a'). + // + // c) The word is all lower case. Is it a case insensitive substring of the candidate starting + // on a part boundary of the candidate? + // + // Else: + // d) If the word was not entirely lowercase, then check if it is contained in the + // candidate in a case *sensitive* manner. If so, return that there was a substring + // match. + // + // e) If the word was not entirely lowercase, then attempt a camel cased match as + // well. + // + // Only if all words have some sort of match is the pattern considered matched. + var subWordTextChunks = segment.subWordTextChunks; + var bestMatch; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; + bestMatch = betterMatch(bestMatch, matchTextChunk(candidate, subWordTextChunk, stringToWordSpans)); + } + return bestMatch; + } + function betterMatch(a, b) { + return ts.min(a, b, compareMatches); + } + function compareMatches(a, b) { + return a === undefined ? 1 /* GreaterThan */ : b === undefined ? -1 /* LessThan */ + : ts.compareValues(a.kind, b.kind) || ts.compareBooleans(!a.isCaseSensitive, !b.isCaseSensitive); + } + function partStartsWith(candidate, candidateSpan, pattern, ignoreCase, patternSpan) { + if (patternSpan === void 0) { patternSpan = { start: 0, length: pattern.length }; } + return patternSpan.length <= candidateSpan.length // If pattern part is longer than the candidate part there can never be a match. + && everyInRange(0, patternSpan.length, function (i) { return equalChars(pattern.charCodeAt(patternSpan.start + i), candidate.charCodeAt(candidateSpan.start + i), ignoreCase); }); + } + function equalChars(ch1, ch2, ignoreCase) { + return ignoreCase ? toLowerCase(ch1) === toLowerCase(ch2) : ch1 === ch2; + } + function tryCamelCaseMatch(candidate, candidateParts, chunk, ignoreCase) { + var chunkCharacterSpans = chunk.characterSpans; + // Note: we may have more pattern parts than candidate parts. This is because multiple + // pattern parts may match a candidate part. For example "SiUI" against "SimpleUI". + // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U + // and I will both match in UI. + var currentCandidate = 0; + var currentChunkSpan = 0; + var firstMatch; + var contiguous; + while (true) { + // Let's consider our termination cases + if (currentChunkSpan === chunkCharacterSpans.length) { + return true; + } + else if (currentCandidate === candidateParts.length) { + // No match, since we still have more of the pattern to hit + return false; + } + var candidatePart = candidateParts[currentCandidate]; + var gotOneMatchThisCandidate = false; + // Consider the case of matching SiUI against SimpleUIElement. The candidate parts + // will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si' + // against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to + // still keep matching pattern parts against that candidate part. + for (; currentChunkSpan < chunkCharacterSpans.length; currentChunkSpan++) { + var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan]; + if (gotOneMatchThisCandidate) { + // We've already gotten one pattern part match in this candidate. We will + // only continue trying to consumer pattern parts if the last part and this + // part are both upper case. + if (!isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan - 1].start)) || + !isUpperCaseLetter(chunk.text.charCodeAt(chunkCharacterSpans[currentChunkSpan].start))) { + break; + } + } + if (!partStartsWith(candidate, candidatePart, chunk.text, ignoreCase, chunkCharacterSpan)) { + break; + } + gotOneMatchThisCandidate = true; + firstMatch = firstMatch === undefined ? currentCandidate : firstMatch; + // If we were contiguous, then keep that value. If we weren't, then keep that + // value. If we don't know, then set the value to 'true' as an initial match is + // obviously contiguous. + contiguous = contiguous === undefined ? true : contiguous; + candidatePart = ts.createTextSpan(candidatePart.start + chunkCharacterSpan.length, candidatePart.length - chunkCharacterSpan.length); + } + // Check if we matched anything at all. If we didn't, then we need to unset the + // contiguous bit if we currently had it set. + // If we haven't set the bit yet, then that means we haven't matched anything so + // far, and we don't want to change that. + if (!gotOneMatchThisCandidate && contiguous !== undefined) { + contiguous = false; + } + // Move onto the next candidate. + currentCandidate++; + } + } function createSegment(text) { return { totalTextChunk: createTextChunk(text), subWordTextChunks: breakPatternIntoTextChunks(text) }; } - // A segment is considered invalid if we couldn't find any words in it. - function segmentIsInvalid(segment) { - return segment.subWordTextChunks.length === 0; - } function isUpperCaseLetter(ch) { // Fast check for the ascii range. if (ch >= 65 /* A */ && ch <= 90 /* Z */) { @@ -91077,24 +97920,18 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - for (var i = 0; i <= n; i++) { - if (startsWithIgnoringCase(str, value, i)) { - return i; + var _loop_17 = function (start) { + if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { + return { value: start }; } + }; + for (var start = 0; start <= n; start++) { + var state_4 = _loop_17(start); + if (typeof state_4 === "object") + return state_4.value; } return -1; } - // Assumes 'value' is already lowercase. - function startsWithIgnoringCase(str, value, start) { - for (var i = 0; i < value.length; i++) { - var ch1 = toLowerCase(str.charCodeAt(i + start)); - var ch2 = value.charCodeAt(i); - if (ch1 !== ch2) { - return false; - } - } - return true; - } function toLowerCase(ch) { // Fast convert for the ascii range. if (ch >= 65 /* A */ && ch <= 90 /* Z */) { @@ -91162,7 +97999,7 @@ var ts; var lastIsDigit = isDigit(identifier.charCodeAt(i - 1)); var currentIsDigit = isDigit(identifier.charCodeAt(i)); var hasTransitionFromLowerToUpper = transitionFromLowerToUpper(identifier, word, i); - var hasTransitionFromUpperToLower = transitionFromUpperToLower(identifier, word, i, wordStart); + var hasTransitionFromUpperToLower = word && transitionFromUpperToLower(identifier, i, wordStart); if (charIsPunctuation(identifier.charCodeAt(i - 1)) || charIsPunctuation(identifier.charCodeAt(i)) || lastIsDigit !== currentIsDigit || @@ -91209,46 +98046,28 @@ var ts; return false; } function isAllPunctuation(identifier, start, end) { - for (var i = start; i < end; i++) { - var ch = identifier.charCodeAt(i); - // We don't consider _ or $ as punctuation as there may be things with that name. - if (!charIsPunctuation(ch) || ch === 95 /* _ */ || ch === 36 /* $ */) { - return false; - } - } - return true; + return every(identifier, function (ch) { return charIsPunctuation(ch) && ch !== 95 /* _ */; }, start, end); } - function transitionFromUpperToLower(identifier, word, index, wordStart) { - if (word) { - // Cases this supports: - // 1) IDisposable -> I, Disposable - // 2) UIElement -> UI, Element - // 3) HTMLDocument -> HTML, Document - // - // etc. - if (index !== wordStart && - index + 1 < identifier.length) { - var currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index)); - var nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1)); - if (currentIsUpper && nextIsLower) { - // We have a transition from an upper to a lower letter here. But we only - // want to break if all the letters that preceded are uppercase. i.e. if we - // have "Foo" we don't want to break that into "F, oo". But if we have - // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, - // Foo". i.e. the last uppercase letter belongs to the lowercase letters - // that follows. Note: this will make the following not split properly: - // "HELLOthere". However, these sorts of names do not show up in .Net - // programs. - for (var i = wordStart; i < index; i++) { - if (!isUpperCaseLetter(identifier.charCodeAt(i))) { - return false; - } - } - return true; - } - } - } - return false; + function transitionFromUpperToLower(identifier, index, wordStart) { + // Cases this supports: + // 1) IDisposable -> I, Disposable + // 2) UIElement -> UI, Element + // 3) HTMLDocument -> HTML, Document + // + // etc. + // We have a transition from an upper to a lower letter here. But we only + // want to break if all the letters that preceded are uppercase. i.e. if we + // have "Foo" we don't want to break that into "F, oo". But if we have + // "IFoo" or "UIFoo", then we want to break that into "I, Foo" and "UI, + // Foo". i.e. the last uppercase letter belongs to the lowercase letters + // that follows. Note: this will make the following not split properly: + // "HELLOthere". However, these sorts of names do not show up in .Net + // programs. + return index !== wordStart + && index + 1 < identifier.length + && isUpperCaseLetter(identifier.charCodeAt(index)) + && isLowerCaseLetter(identifier.charCodeAt(index + 1)) + && every(identifier, isUpperCaseLetter, wordStart, index); } function transitionFromLowerToUpper(identifier, word, index) { var lastIsUpper = isUpperCaseLetter(identifier.charCodeAt(index - 1)); @@ -91266,10 +98085,20 @@ var ts; // on characters would be: A M // // We break the search string on characters. But we break the symbol name on words. - var transition = word - ? (currentIsUpper && !lastIsUpper) - : currentIsUpper; - return transition; + return currentIsUpper && (!word || !lastIsUpper); + } + function everyInRange(start, end, pred) { + for (var i = start; i < end; i++) { + if (!pred(i)) { + return false; + } + } + return true; + } + function every(s, pred, start, end) { + if (start === void 0) { start = 0; } + if (end === void 0) { end = s.length; } + return everyInRange(start, end, function (i) { return pred(s.charCodeAt(i), i); }); } })(ts || (ts = {})); var ts; @@ -91283,25 +98112,29 @@ var ts; checkJsDirective: undefined, referencedFiles: [], typeReferenceDirectives: [], + libReferenceDirectives: [], amdDependencies: [], hasNoDefaultLib: undefined, moduleName: undefined }; var importedFiles = []; var ambientExternalModules; + var lastToken; + var currentToken; var braceNesting = 0; // assume that text represent an external module if it contains at least one top level import/export // ambient modules that are found inside external modules are interpreted as module augmentations var externalModule = false; function nextToken() { - var token = ts.scanner.scan(); - if (token === 17 /* OpenBraceToken */) { + lastToken = currentToken; + currentToken = ts.scanner.scan(); + if (currentToken === 17 /* OpenBraceToken */) { braceNesting++; } - else if (token === 18 /* CloseBraceToken */) { + else if (currentToken === 18 /* CloseBraceToken */) { braceNesting--; } - return token; + return currentToken; } function getFileReference() { var fileName = ts.scanner.getTokenValue(); @@ -91345,6 +98178,9 @@ var ts; * Returns true if at least one token was consumed from the stream */ function tryConsumeImport() { + if (lastToken === 23 /* DotToken */) { + return false; + } var token = ts.scanner.getToken(); if (token === 91 /* ImportKeyword */) { token = nextToken(); @@ -91364,7 +98200,7 @@ var ts; else { if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import d from "mod"; @@ -91395,7 +98231,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import {a as A} from "mod"; @@ -91411,7 +98247,7 @@ var ts; token = nextToken(); if (token === 71 /* Identifier */ || ts.isKeyword(token)) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // import * as NS from "mod" @@ -91441,7 +98277,7 @@ var ts; } if (token === 18 /* CloseBraceToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export {a as A} from "mod"; @@ -91453,7 +98289,7 @@ var ts; } else if (token === 39 /* AsteriskToken */) { token = nextToken(); - if (token === 142 /* FromKeyword */) { + if (token === 143 /* FromKeyword */) { token = nextToken(); if (token === 9 /* StringLiteral */) { // export * from "mod" @@ -91543,6 +98379,9 @@ var ts; // export {a as b} from "mod" // export import i = require("mod") // (for JavaScript files) require("mod") + // Do not look for: + // AnySymbol.import("mod") + // AnySymbol.nested.import("mod") while (true) { if (ts.scanner.getToken() === 1 /* EndOfFileToken */) { break; @@ -91574,7 +98413,7 @@ var ts; importedFiles.push(decl.ref); } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: undefined }; } else { // for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0 @@ -91593,7 +98432,7 @@ var ts; } } } - return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, importedFiles: importedFiles, isLibFile: pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; + return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles: importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } ts.preProcessFile = preProcessFile; @@ -91603,52 +98442,40 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(typeChecker, defaultLibFileName, getCanonicalFileName, sourceFile, position) { - var getCanonicalDefaultLibName = ts.memoize(function () { return getCanonicalFileName(ts.normalizePath(defaultLibFileName)); }); - var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); + function getRenameInfo(program, sourceFile, position) { + var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); - function isDefinedInLibraryFile(declaration) { - if (!defaultLibFileName) { - return false; - } - var sourceFile = declaration.getSourceFile(); - var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName)); - return canonicalName === getCanonicalDefaultLibName(); - } } Rename.getRenameInfo = getRenameInfo; function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) + return; // Only allow a symbol to be renamed if it actually has at least one declaration. - if (symbol) { - var declarations = symbol.declarations; - if (declarations && declarations.length > 0) { - // Disallow rename for elements that are defined in the standard TypeScript library. - if (declarations.some(isDefinedInLibraryFile)) { - return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); - } - // Cannot rename `default` as in `import { default as foo } from "./someModule"; - if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { - return undefined; - } - var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 146 /* ComputedPropertyName */) - ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) - : undefined; - var displayName = specifierName || typeChecker.symbolToString(symbol); - var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); - return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); - } + var declarations = symbol.declarations; + if (!declarations || declarations.length === 0) + return; + // Disallow rename for elements that are defined in the standard TypeScript library. + if (declarations.some(isDefinedInLibraryFile)) { + return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } - else if (ts.isStringLiteral(node)) { - if (isDefinedInLibraryFile(node)) { - return getRenameInfoError(ts.Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); - } - return getRenameInfoSuccess(node.text, node.text, "var" /* variableElement */, "" /* none */, node, sourceFile); + // Cannot rename `default` as in `import { default as foo } from "./someModule"; + if (ts.isIdentifier(node) && node.originalKeywordKind === 79 /* DefaultKeyword */ && symbol.parent.flags & 1536 /* Module */) { + return undefined; } + // Can't rename a module name. + if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) + return undefined; + var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 147 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } function getRenameInfoSuccess(displayName, fullDisplayName, kind, kindModifiers, node, sourceFile) { return { @@ -91662,6 +98489,7 @@ var ts; }; } function getRenameInfoError(diagnostic) { + // TODO: GH#18217 return { canRename: false, localizedErrorMessage: ts.getLocaleSpecificMessage(diagnostic), @@ -91696,7 +98524,6 @@ var ts; } })(Rename = ts.Rename || (ts.Rename = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -91708,8 +98535,13 @@ var ts; ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; ArgumentListKind[ArgumentListKind["JSXAttributesArguments"] = 3] = "JSXAttributesArguments"; - })(ArgumentListKind = SignatureHelp.ArgumentListKind || (SignatureHelp.ArgumentListKind = {})); - function getSignatureHelpItems(program, sourceFile, position, cancellationToken) { + })(ArgumentListKind || (ArgumentListKind = {})); + var InvocationKind; + (function (InvocationKind) { + InvocationKind[InvocationKind["Call"] = 0] = "Call"; + InvocationKind[InvocationKind["TypeArgs"] = 1] = "TypeArgs"; + })(InvocationKind || (InvocationKind = {})); + function getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken) { var typeChecker = program.getTypeChecker(); // Decide whether to show signature help var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); @@ -91717,66 +98549,135 @@ var ts; // We are at the beginning of the file return undefined; } + // Only need to be careful if the user typed a character and signature help wasn't showing. + var shouldCarefullyCheckContext = !!triggerReason && triggerReason.kind === "characterTyped"; + // Bail out quickly in the middle of a string or comment, don't provide signature help unless the user explicitly requested it. + if (shouldCarefullyCheckContext) { + if (ts.isInString(sourceFile, position, startingToken) || ts.isInComment(sourceFile, position)) { + return undefined; + } + } var argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile); if (!argumentInfo) return undefined; cancellationToken.throwIfCancellationRequested(); - // Semantic filtering of signature help - var call = argumentInfo.invocation; - var candidates = []; - var resolvedSignature = typeChecker.getResolvedSignature(call, candidates, argumentInfo.argumentCount); + // Extra syntactic and semantic filtering of signature help + var candidateInfo = getCandidateInfo(argumentInfo, typeChecker, sourceFile, startingToken, shouldCarefullyCheckContext); cancellationToken.throwIfCancellationRequested(); - if (!candidates.length) { + if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. if (ts.isSourceFileJavaScript(sourceFile)) { - return createJavaScriptSignatureHelpItems(argumentInfo, program); + return createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken); } return undefined; } - return createSignatureHelpItems(candidates, resolvedSignature, argumentInfo, typeChecker); + return typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(candidateInfo.candidates, candidateInfo.resolvedSignature, argumentInfo, sourceFile, typeChecker); }); } SignatureHelp.getSignatureHelpItems = getSignatureHelpItems; - function createJavaScriptSignatureHelpItems(argumentInfo, program) { - if (argumentInfo.invocation.kind !== 185 /* CallExpression */) { - return undefined; + function getCandidateInfo(argumentInfo, checker, sourceFile, startingToken, onlyUseSyntacticOwners) { + var invocation = argumentInfo.invocation; + if (invocation.kind === 0 /* Call */) { + if (onlyUseSyntacticOwners) { + if (ts.isCallOrNewExpression(invocation.node)) { + var invocationChildren = invocation.node.getChildren(sourceFile); + switch (startingToken.kind) { + case 19 /* OpenParenToken */: + if (!ts.contains(invocationChildren, startingToken)) { + return undefined; + } + break; + case 26 /* CommaToken */: + var containingList = ts.findContainingList(startingToken); + if (!containingList || !ts.contains(invocationChildren, ts.findContainingList(startingToken))) { + return undefined; + } + break; + case 27 /* LessThanToken */: + if (!lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.node.expression)) { + return undefined; + } + break; + default: + return undefined; + } + } + else { + return undefined; + } + } + var candidates = []; + var resolvedSignature = checker.getResolvedSignature(invocation.node, candidates, argumentInfo.argumentCount); // TODO: GH#18217 + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: resolvedSignature }; } + else if (invocation.kind === 1 /* TypeArgs */) { + if (onlyUseSyntacticOwners && !lessThanFollowsCalledExpression(startingToken, sourceFile, invocation.called)) { + return undefined; + } + var candidates = ts.getPossibleGenericSignatures(invocation.called, argumentInfo.argumentCount, checker); + return candidates.length === 0 ? undefined : { candidates: candidates, resolvedSignature: ts.first(candidates) }; + } + else { + ts.Debug.assertNever(invocation); + } + } + function createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) { // See if we can find some symbol with the call expression name that has call signatures. - var callExpression = argumentInfo.invocation; - var expression = callExpression.expression; + var expression = getExpressionFromInvocation(argumentInfo.invocation); var name = ts.isIdentifier(expression) ? expression : ts.isPropertyAccessExpression(expression) ? expression.name : undefined; if (!name || !name.escapedText) { return undefined; } var typeChecker = program.getTypeChecker(); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; + var _loop_18 = function (sourceFile) { var nameToDeclarations = sourceFile.getNamedDeclarations(); var declarations = nameToDeclarations.get(name.text); if (declarations) { - for (var _b = 0, declarations_12 = declarations; _b < declarations_12.length; _b++) { - var declaration = declarations_12[_b]; + var _loop_19 = function (declaration) { var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); if (type) { - var callSignatures = type.getCallSignatures(); - if (callSignatures && callSignatures.length) { - return createSignatureHelpItems(callSignatures, callSignatures[0], argumentInfo, typeChecker); + var callSignatures_1 = type.getCallSignatures(); + if (callSignatures_1 && callSignatures_1.length) { + return { value: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return createSignatureHelpItems(callSignatures_1, callSignatures_1[0], argumentInfo, sourceFile, typeChecker); }) }; } } } + }; + for (var _i = 0, declarations_13 = declarations; _i < declarations_13.length; _i++) { + var declaration = declarations_13[_i]; + var state_6 = _loop_19(declaration); + if (typeof state_6 === "object") + return state_6; } } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var state_5 = _loop_18(sourceFile); + if (typeof state_5 === "object") + return state_5.value; } } + function lessThanFollowsCalledExpression(startingToken, sourceFile, calledExpression) { + var precedingToken = ts.Debug.assertDefined(ts.findPrecedingToken(startingToken.getFullStart(), sourceFile, startingToken.parent, /*excludeJsdoc*/ true)); + return ts.rangeContainsRange(calledExpression, precedingToken); + } + function getArgumentInfoForCompletions(node, position, sourceFile) { + var info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return !info || info.kind === 0 /* TypeArguments */ || info.invocation.kind === 1 /* TypeArgs */ ? undefined + : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; + } + SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; /** * Returns relevant information for the argument list and the current argument if we are * in the argument of an invocation; returns undefined otherwise. */ function getImmediatelyContainingArgumentInfo(node, position, sourceFile) { - if (ts.isCallOrNewExpression(node.parent)) { - var invocation = node.parent; + var parent = node.parent; + if (ts.isCallOrNewExpression(parent)) { + var invocation = parent; var list = void 0; var argumentIndex = void 0; // There are 3 cases to handle: @@ -91796,7 +98697,7 @@ var ts; if (node.kind === 27 /* LessThanToken */ || node.kind === 19 /* OpenParenToken */) { // Find the list that starts right *after* the < or ( token. // If the user has just opened a list, consider this item 0. - list = getChildListThatStartsWithOpenerToken(invocation, node, sourceFile); + list = getChildListThatStartsWithOpenerToken(parent, node, sourceFile); ts.Debug.assert(list !== undefined); argumentIndex = 0; } @@ -91812,60 +98713,66 @@ var ts; return undefined; argumentIndex = getArgumentIndex(list, node); } - var kind = invocation.typeArguments && invocation.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; + var kind = parent.typeArguments && parent.typeArguments.pos === list.pos ? 0 /* TypeArguments */ : 1 /* CallArguments */; var argumentCount = getArgumentCount(list); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } var argumentsSpan = getApplicableSpanForArguments(list, sourceFile); - return { kind: kind, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; + return { kind: kind, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - else if (node.kind === 13 /* NoSubstitutionTemplateLiteral */ && node.parent.kind === 187 /* TaggedTemplateExpression */) { + else if (ts.isNoSubstitutionTemplateLiteral(node) && ts.isTaggedTemplateExpression(parent)) { // Check if we're actually inside the template; // otherwise we'll fall out and return undefined. - if (ts.isInsideTemplateLiteral(node, position)) { - return getArgumentListInfoForTemplate(node.parent, /*argumentIndex*/ 0, sourceFile); + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { + return getArgumentListInfoForTemplate(parent, /*argumentIndex*/ 0, sourceFile); } } - else if (node.kind === 14 /* TemplateHead */ && node.parent.parent.kind === 187 /* TaggedTemplateExpression */) { - var templateExpression = node.parent; + else if (ts.isTemplateHead(node) && parent.parent.kind === 191 /* TaggedTemplateExpression */) { + var templateExpression = parent; var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 200 /* TemplateExpression */); - var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; + ts.Debug.assert(templateExpression.kind === 204 /* TemplateExpression */); + var argumentIndex = ts.isInsideTemplateLiteral(node, position, sourceFile) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent.kind === 209 /* TemplateSpan */ && node.parent.parent.parent.kind === 187 /* TaggedTemplateExpression */) { - var templateSpan = node.parent; - var templateExpression = templateSpan.parent; - var tagExpression = templateExpression.parent; - ts.Debug.assert(templateExpression.kind === 200 /* TemplateExpression */); + else if (ts.isTemplateSpan(parent) && ts.isTaggedTemplateExpression(parent.parent.parent)) { + var templateSpan = parent; + var tagExpression = parent.parent.parent; // If we're just after a template tail, don't show signature help. - if (node.kind === 16 /* TemplateTail */ && !ts.isInsideTemplateLiteral(node, position)) { + if (ts.isTemplateTail(node) && !ts.isInsideTemplateLiteral(node, position, sourceFile)) { return undefined; } - var spanIndex = templateExpression.templateSpans.indexOf(templateSpan); - var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position); + var spanIndex = templateSpan.parent.templateSpans.indexOf(templateSpan); + var argumentIndex = getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile); return getArgumentListInfoForTemplate(tagExpression, argumentIndex, sourceFile); } - else if (node.parent && ts.isJsxOpeningLikeElement(node.parent)) { + else if (ts.isJsxOpeningLikeElement(parent)) { // Provide a signature help for JSX opening element or JSX self-closing element. // This is not guarantee that JSX tag-name is resolved into stateless function component. (that is done in "getSignatureHelpItems") // i.e // export function MainButton(props: ButtonProps, context: any): JSX.Element { ... } // 0 && ts.lastOrUndefined(listChildren).kind === 26 /* CommaToken */) { + if (listChildren.length > 0 && ts.last(listChildren).kind === 26 /* CommaToken */) { argumentCount++; } return argumentCount; } // spanIndex is either the index for a given template span. // This does not give appropriate results for a NoSubstitutionTemplateLiteral - function getArgumentIndexForTemplatePiece(spanIndex, node, position) { + function getArgumentIndexForTemplatePiece(spanIndex, node, position, sourceFile) { // Because the TemplateStringsArray is the first argument, we have to offset each substitution expression by 1. // There are three cases we can encounter: // 1. We are precisely in the template literal (argIndex = 0). @@ -91926,8 +98833,8 @@ var ts; // Case: 1 1 3 2 1 3 2 2 1 // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); - if (ts.isTemplateLiteralKind(node.kind)) { - if (ts.isInsideTemplateLiteral(node, position)) { + if (ts.isTemplateLiteralToken(node)) { + if (ts.isInsideTemplateLiteral(node, position, sourceFile)) { return 0; } return spanIndex + 2; @@ -91942,7 +98849,7 @@ var ts; } return { kind: 2 /* TaggedTemplateArguments */, - invocation: tagExpression, + invocation: { kind: 0 /* Call */, node: tagExpression }, argumentsSpan: getApplicableSpanForTaggedTemplate(tagExpression, sourceFile), argumentIndex: argumentIndex, argumentCount: argumentCount @@ -91973,8 +98880,8 @@ var ts; // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. - if (template.kind === 200 /* TemplateExpression */) { - var lastSpan = ts.lastOrUndefined(template.templateSpans); + if (template.kind === 204 /* TemplateExpression */) { + var lastSpan = ts.last(template.templateSpans); if (lastSpan.literal.getFullWidth() === 0) { applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, /*stopAfterLineBreak*/ false); } @@ -91982,39 +98889,40 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile) { - for (var n = node; n.kind !== 272 /* SourceFile */; n = n.parent) { - if (ts.isFunctionBlock(n)) { - return undefined; - } + var _loop_20 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. - if (n.pos < n.parent.pos || n.end > n.parent.end) { - ts.Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind); - } + ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); var argumentInfo = getImmediatelyContainingArgumentInfo(n, position, sourceFile); if (argumentInfo) { - return argumentInfo; + return { value: argumentInfo }; } - // TODO: Handle generic call with incomplete syntax + }; + for (var n = node; !ts.isBlock(n) && !ts.isSourceFile(n); n = n.parent) { + var state_7 = _loop_20(n); + if (typeof state_7 === "object") + return state_7.value; } return undefined; } - SignatureHelp.getContainingArgumentInfo = getContainingArgumentInfo; function getChildListThatStartsWithOpenerToken(parent, openerToken, sourceFile) { var children = parent.getChildren(sourceFile); var indexOfOpenerToken = children.indexOf(openerToken); ts.Debug.assert(indexOfOpenerToken >= 0 && children.length > indexOfOpenerToken + 1); return children[indexOfOpenerToken + 1]; } - var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; - function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, typeChecker) { + function getExpressionFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; + } + var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + function createSignatureHelpItems(candidates, resolvedSignature, argumentListInfo, sourceFile, typeChecker) { var argumentCount = argumentListInfo.argumentCount, applicableSpan = argumentListInfo.argumentsSpan, invocation = argumentListInfo.invocation, argumentIndex = argumentListInfo.argumentIndex; var isTypeParameterList = argumentListInfo.kind === 0 /* TypeArguments */; - var callTarget = ts.getInvokedExpression(invocation); - var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); + var enclosingDeclaration = invocation.kind === 0 /* Call */ ? invocation.node : invocation.called; + var callTargetSymbol = typeChecker.getSymbolAtLocation(getExpressionFromInvocation(invocation)); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); var printer = ts.createPrinter({ removeComments: true }); - var items = ts.map(candidates, function (candidateSignature) { + var items = candidates.map(function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; var suffixDisplayParts = []; @@ -92029,9 +98937,9 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, signatureHelpNodeBuilderFlags)] : []; - var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, signatureHelpNodeBuilderFlags); }))); - printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, enclosingDeclaration, signatureHelpNodeBuilderFlags)] : []; + var params = ts.createNodeArray(thisParameter.concat(candidateSignature.parameters.map(function (param) { return typeChecker.symbolToParameterDeclaration(param, enclosingDeclaration, signatureHelpNodeBuilderFlags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, sourceFile, writer); }); ts.addRange(suffixDisplayParts, parameterParts); } @@ -92039,8 +98947,8 @@ var ts; isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { - var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); - printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var args = ts.createNodeArray(candidateSignature.typeParameters.map(function (p) { return typeChecker.typeParameterToDeclaration(p, enclosingDeclaration); })); + printer.writeList(26896 /* TypeParameters */, args, sourceFile, writer); } }); ts.addRange(prefixDisplayParts, typeParameterParts); @@ -92053,10 +98961,10 @@ var ts; writer.writeSpace(" "); var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); if (predicate) { - typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + typeChecker.writeTypePredicate(predicate, enclosingDeclaration, /*flags*/ undefined, writer); } else { - typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), enclosingDeclaration, /*flags*/ undefined, writer); } }); ts.addRange(suffixDisplayParts, returnTypeParts); @@ -92078,8 +98986,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, signatureHelpNodeBuilderFlags); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.symbolToParameterDeclaration(parameter, enclosingDeclaration, signatureHelpNodeBuilderFlags); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: parameter.name, @@ -92090,8 +98998,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); - printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + var param = typeChecker.typeParameterToDeclaration(typeParameter, enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, param, sourceFile, writer); }); return { name: typeParameter.symbol.name, @@ -92106,59 +99014,225 @@ var ts; /* @internal */ var ts; (function (ts) { - function computeSuggestionDiagnostics(sourceFile, program) { - program.getSemanticDiagnostics(sourceFile); - var checker = program.getDiagnosticsProducingTypeChecker(); + // Sometimes tools can sometimes see the following line as a source mapping url comment, so we mangle it a bit (the [M]) + var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; + var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; + function getSourceMapper(getCanonicalFileName, currentDirectory, log, host, getProgram) { + var sourcemappedFileCache; + return { tryGetOriginalLocation: tryGetOriginalLocation, tryGetGeneratedLocation: tryGetGeneratedLocation, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; + function scanForSourcemapURL(fileName) { + var mappedFile = sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + if (!mappedFile) { + return; + } + var starts = ts.getLineStarts(mappedFile); + for (var index = starts.length - 1; index >= 0; index--) { + var lineText = mappedFile.text.substring(starts[index], starts[index + 1]); + var comment = sourceMapCommentRegExp.exec(lineText); + if (comment) { + return comment[1]; + } + // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file + else if (!lineText.match(whitespaceOrMapCommentRegExp)) { + break; + } + } + } + function convertDocumentToSourceMapper(file, contents, mapFileName) { + var maps; + try { + maps = JSON.parse(contents); + } + catch (_a) { + // swallow error + } + if (!maps || !maps.sources || !maps.file || !maps.mappings) { + // obviously invalid map + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + return file.sourceMapper = ts.sourcemaps.decode({ + readFile: function (s) { return host.readFile(s); }, + fileExists: function (s) { return host.fileExists(s); }, + getCanonicalFileName: getCanonicalFileName, + log: log, + }, mapFileName, maps, getProgram(), sourcemappedFileCache); + } + function getSourceMapper(fileName, file) { + if (!host.readFile || !host.fileExists) { + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + if (file.sourceMapper) { + return file.sourceMapper; + } + var mapFileName = scanForSourcemapURL(fileName); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); + } + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(fileName + ".map"); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); + if (host.fileExists(mapPath)) { + return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 + } + } + return file.sourceMapper = ts.sourcemaps.identitySourceMapper; + } + function tryGetOriginalLocation(info) { + if (!ts.isDeclarationFileName(info.fileName)) + return undefined; + var file = getFile(info.fileName); + if (!file) + return undefined; + var newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); + return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + } + function tryGetGeneratedLocation(info) { + var program = getProgram(); + var declarationPath = ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + if (declarationPath === undefined) + return undefined; + var declarationFile = getFile(declarationPath); + if (!declarationFile) + return undefined; + var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + return newLoc === info ? undefined : newLoc; + } + function getFile(fileName) { + return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); + } + function toLineColumnOffset(fileName, position) { + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var file = getProgram().getSourceFile(path) || sourcemappedFileCache.get(path); // TODO: GH#18217 + return file.getLineAndCharacterOfPosition(position); + } + function clearCache() { + sourcemappedFileCache = ts.createSourceFileLikeCache(host); + } + } + ts.getSourceMapper = getSourceMapper; +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { + program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; - if (sourceFile.commonJsModuleIndicator) { - diags.push(ts.createDiagnosticForNode(sourceFile.commonJsModuleIndicator, ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); + if (sourceFile.commonJsModuleIndicator && + (ts.programContainsEs6Modules(program) || ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) && + containsTopLevelCommonjs(sourceFile)) { + diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJavaScript(sourceFile); - function check(node) { - switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - if (isJsFile) { - var symbol = node.symbol; - if (symbol.members && (symbol.members.size > 0)) { - diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); - } - } - break; - } - if (!isJsFile && ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { - diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); - } - node.forEachChild(check); - } check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importNode = _a[_i]; - var name = importNameForConvertToDefaultImport(importNode.parent); + var moduleSpecifier = _a[_i]; + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + var name = importNameForConvertToDefaultImport(importNode); if (!name) continue; - var module = ts.getResolvedModule(sourceFile, importNode.text); - var resolvedFile = module && program.getSourceFile(module.resolvedFileName); + var module_2 = ts.getResolvedModule(sourceFile, moduleSpecifier.text); + var resolvedFile = module_2 && program.getSourceFile(module_2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && ts.isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(ts.createDiagnosticForNode(name, ts.Diagnostics.Import_may_be_converted_to_a_default_import)); } } } - return diags.concat(checker.getSuggestionDiagnostics(sourceFile)); + ts.addRange(diags, sourceFile.bindSuggestionDiagnostics); + ts.addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + return diags.sort(function (d1, d2) { return d1.start - d2.start; }); + function check(node) { + if (isJsFile) { + switch (node.kind) { + case 194 /* FunctionExpression */: + var decl = ts.getDeclarationOfJSInitializer(node); + if (decl) { + var symbol_3 = decl.symbol; + if (symbol_3 && (symbol_3.exports && symbol_3.exports.size || symbol_3.members && symbol_3.members.size)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + break; + } + } + // falls through if no diagnostic was created + case 237 /* FunctionDeclaration */: + var symbol = node.symbol; + if (symbol.members && (symbol.members.size > 0)) { + diags.push(ts.createDiagnosticForNode(ts.isVariableDeclaration(node.parent) ? node.parent.name : node, ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration)); + } + break; + } + } + else { + if (ts.isVariableStatement(node) && + node.parent === sourceFile && + node.declarationList.flags & 2 /* Const */ && + node.declarationList.declarations.length === 1) { + var init = node.declarationList.declarations[0].initializer; + if (init && ts.isRequireCall(init, /*checkArgumentIsStringLiteralLike*/ true)) { + diags.push(ts.createDiagnosticForNode(init, ts.Diagnostics.require_call_may_be_converted_to_an_import)); + } + } + if (ts.codefix.parameterShouldGetTypeFromJSDoc(node)) { + diags.push(ts.createDiagnosticForNode(node.name || node, ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types)); + } + } + node.forEachChild(check); + } } ts.computeSuggestionDiagnostics = computeSuggestionDiagnostics; + // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes. + function containsTopLevelCommonjs(sourceFile) { + return sourceFile.statements.some(function (statement) { + switch (statement.kind) { + case 217 /* VariableStatement */: + return statement.declarationList.declarations.some(function (decl) { + return ts.isRequireCall(propertyAccessLeftHandSide(decl.initializer), /*checkArgumentIsStringLiteralLike*/ true); + }); // TODO: GH#18217 + case 219 /* ExpressionStatement */: { + var expression = statement.expression; + if (!ts.isBinaryExpression(expression)) + return ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); + var kind = ts.getSpecialPropertyAssignmentKind(expression); + return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; + } + default: + return false; + } + }); + } + function propertyAccessLeftHandSide(node) { + return ts.isPropertyAccessExpression(node) ? propertyAccessLeftHandSide(node.expression) : node; + } function importNameForConvertToDefaultImport(node) { - if (ts.isExternalModuleReference(node)) { - return node.parent.name; - } - if (ts.isImportDeclaration(node)) { - var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; - return importClause && !importClause.name && importClause.namedBindings.kind === 244 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) - ? importClause.namedBindings.name - : undefined; + switch (node.kind) { + case 247 /* ImportDeclaration */: + var importClause = node.importClause, moduleSpecifier = node.moduleSpecifier; + return importClause && !importClause.name && importClause.namedBindings && importClause.namedBindings.kind === 249 /* NamespaceImport */ && ts.isStringLiteral(moduleSpecifier) + ? importClause.namedBindings.name + : undefined; + case 246 /* ImportEqualsDeclaration */: + return node.name; + default: + return undefined; } } + function getErrorNodeFromCommonJsIndicator(commonJsModuleIndicator) { + return ts.isBinaryExpression(commonJsModuleIndicator) ? commonJsModuleIndicator.left : commonJsModuleIndicator; + } })(ts || (ts = {})); /* @internal */ var ts; @@ -92173,7 +99247,7 @@ var ts; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); if (flags & 32 /* Class */) { - return ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */) ? + return ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } if (flags & 384 /* Enum */) @@ -92196,6 +99270,14 @@ var ts; } SymbolDisplay.getSymbolKind = getSymbolKind; function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { + var roots = typeChecker.getRootSymbols(symbol); + // If this is a method from a mapped type, leave as a method so long as it still has a call signature. + if (roots.length === 1 + && ts.first(roots).flags & 8192 /* Method */ + // Ensure the mapped version is still a method, as opposed to `{ [K in keyof I]: number }`. + && typeChecker.getTypeOfSymbolAtLocation(symbol, location).getNonNullableType().getCallSignatures().length !== 0) { + return "method" /* memberFunctionElement */; + } if (typeChecker.isUndefinedSymbol(symbol)) { return "var" /* variableElement */; } @@ -92210,7 +99292,7 @@ var ts; if (ts.isFirstDeclarationOfSymbolParameter(symbol)) { return "parameter" /* parameterElement */; } - else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { + else if (symbol.valueDeclaration && ts.isVarConst(symbol.valueDeclaration)) { return "const" /* constElement */; } else if (ts.forEach(symbol.declarations, ts.isLet)) { @@ -92253,11 +99335,11 @@ var ts; // If we requested completions after `x.` at the top-level, we may be at a source file location. switch (location.parent && location.parent.kind) { // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 255 /* JsxOpeningElement */: - case 253 /* JsxElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 258 /* JsxElement */: + case 259 /* JsxSelfClosingElement */: return location.kind === 71 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 260 /* JsxAttribute */: + case 265 /* JsxAttribute */: return "JSX attribute" /* jsxAttribute */; default: return "property" /* memberVariableElement */; @@ -92283,11 +99365,12 @@ var ts; var tags; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); - var hasAddedSymbolInfo; + var hasAddedSymbolInfo = false; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; var printer; var documentationFromAlias; + var tagsFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -92296,7 +99379,7 @@ var ts; } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol.exportSymbol || symbol, location); - if (location.parent && location.parent.kind === 183 /* PropertyAccessExpression */) { + if (location.parent && location.parent.kind === 187 /* 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)) { @@ -92316,8 +99399,8 @@ var ts; } if (callExpressionLike) { var candidateSignatures = []; - signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); - var useConstructSignatures = callExpressionLike.kind === 186 /* NewExpression */ || (ts.isCallExpression(callExpressionLike) && callExpressionLike.expression.kind === 97 /* SuperKeyword */); + signature = typeChecker.getResolvedSignature(callExpressionLike, candidateSignatures); // TODO: GH#18217 + var useConstructSignatures = callExpressionLike.kind === 190 /* 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 @@ -92332,7 +99415,7 @@ var ts; } else if (symbolFlags & 2097152 /* Alias */) { symbolKind = "alias" /* alias */; - pushTypePart(symbolKind); + pushSymbolKind(symbolKind); displayParts.push(ts.spacePart()); if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); @@ -92354,7 +99437,7 @@ var ts; // If it is call or construct signature of lambda's write type name displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); - if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { + if (!(ts.getObjectFlags(type) & 16 /* Anonymous */) && type.symbol) { ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } @@ -92372,7 +99455,7 @@ var ts; } } else if ((ts.isNameOfFunctionDeclaration(location) && !(symbolFlags & 98304 /* Accessor */)) || // name of function declaration - (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 154 /* Constructor */)) { // At constructor keyword of constructor declaration + (location.kind === 123 /* ConstructorKeyword */ && location.parent.kind === 155 /* Constructor */)) { // At constructor keyword of constructor declaration // 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 @@ -92380,21 +99463,21 @@ var ts; return declaration === (location.kind === 123 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { - var allSignatures = functionDeclaration_1.kind === 154 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); + var allSignatures = functionDeclaration_1.kind === 155 /* Constructor */ ? type.getNonNullableType().getConstructSignatures() : type.getNonNullableType().getCallSignatures(); if (!typeChecker.isImplementationOfOverload(functionDeclaration_1)) { - signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); + signature = typeChecker.getSignatureFromDeclaration(functionDeclaration_1); // TODO: GH#18217 } else { signature = allSignatures[0]; } - if (functionDeclaration_1.kind === 154 /* Constructor */) { + if (functionDeclaration_1.kind === 155 /* Constructor */) { // show (constructor) Type(...) signature symbolKind = "constructor" /* constructorImplementationElement */; addPrefixForAnyFunctionOrVar(type.symbol, symbolKind); } else { // (function/method) symbol(..signature) - addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 157 /* CallSignature */ && + addPrefixForAnyFunctionOrVar(functionDeclaration_1.kind === 158 /* CallSignature */ && !(type.symbol.flags & 2048 /* TypeLiteral */ || type.symbol.flags & 4096 /* ObjectLiteral */) ? type.symbol : symbol, symbolKind); } addSignatureDisplayParts(signature, allSignatures); @@ -92404,11 +99487,11 @@ var ts; } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { addAliasPrefixIfNecessary(); - if (ts.getDeclarationOfKind(symbol, 203 /* ClassExpression */)) { + if (ts.getDeclarationOfKind(symbol, 207 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) // (local class) class - pushTypePart("local class" /* localClassElement */); + pushSymbolKind("local class" /* localClassElement */); } else { // Class declaration has name which is not local. @@ -92438,7 +99521,7 @@ var ts; } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); - if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { + if (ts.some(symbol.declarations, function (d) { return ts.isEnumDeclaration(d) && ts.isEnumConst(d); })) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } @@ -92448,7 +99531,7 @@ var ts; } if (symbolFlags & 1536 /* Module */) { prefixNextMeaning(); - var declaration = ts.getDeclarationOfKind(symbol, 237 /* ModuleDeclaration */); + var declaration = ts.getDeclarationOfKind(symbol, 242 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 130 /* NamespaceKeyword */ : 129 /* ModuleKeyword */)); displayParts.push(ts.spacePart()); @@ -92469,23 +99552,24 @@ var ts; } else { // Method/function type parameter - var decl = ts.getDeclarationOfKind(symbol, 147 /* TypeParameter */); - ts.Debug.assert(decl !== undefined); + var decl = ts.getDeclarationOfKind(symbol, 148 /* TypeParameter */); + if (decl === undefined) + return ts.Debug.fail(); var declaration = decl.parent; if (declaration) { if (ts.isFunctionLikeKind(declaration.kind)) { addInPrefix(); - var signature = typeChecker.getSignatureFromDeclaration(declaration); - if (declaration.kind === 158 /* ConstructSignature */) { + var signature = typeChecker.getSignatureFromDeclaration(declaration); // TODO: GH#18217 + if (declaration.kind === 159 /* ConstructSignature */) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - else if (declaration.kind !== 157 /* CallSignature */ && declaration.name) { + else if (declaration.kind !== 158 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } - else if (declaration.kind === 235 /* TypeAliasDeclaration */) { + else if (declaration.kind === 240 /* TypeAliasDeclaration */) { // Type alias type parameter // For example // type list = T[]; // Both T will go through same code path @@ -92502,7 +99586,7 @@ var ts; symbolKind = "enum member" /* enumMemberElement */; addPrefixForAnyFunctionOrVar(symbol, "enum member"); var declaration = symbol.declarations[0]; - if (declaration.kind === 271 /* EnumMember */) { + if (declaration.kind === 276 /* EnumMember */) { var constantValue = typeChecker.getConstantValue(declaration); if (constantValue !== undefined) { displayParts.push(ts.spacePart()); @@ -92527,27 +99611,31 @@ var ts; displayParts.push.apply(displayParts, resolvedInfo.displayParts); displayParts.push(ts.lineBreakPart()); documentationFromAlias = resolvedInfo.documentation; + tagsFromAlias = resolvedInfo.tags; } } } switch (symbol.declarations[0].kind) { - case 240 /* NamespaceExportDeclaration */: + case 245 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(130 /* NamespaceKeyword */)); break; - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(symbol.declarations[0].isExportEquals ? 58 /* EqualsToken */ : 79 /* DefaultKeyword */)); break; + case 255 /* ExportSpecifier */: + displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); + break; default: displayParts.push(ts.keywordPart(91 /* ImportKeyword */)); } displayParts.push(ts.spacePart()); addFullSymbolName(symbol); ts.forEach(symbol.declarations, function (declaration) { - if (declaration.kind === 241 /* ImportEqualsDeclaration */) { + if (declaration.kind === 246 /* ImportEqualsDeclaration */) { var importEqualsDeclaration = declaration; if (ts.isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { displayParts.push(ts.spacePart()); @@ -92625,10 +99713,10 @@ var ts; // For some special property access expressions like `exports.foo = foo` or `module.exports.foo = foo` // there documentation comments might be attached to the right hand side symbol of their declarations. // The pattern of such special property access is that the parent symbol is the symbol of the file. - if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 272 /* SourceFile */; })) { + if (symbol.parent && ts.forEach(symbol.parent.declarations, function (declaration) { return declaration.kind === 277 /* SourceFile */; })) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; - if (!declaration.parent || declaration.parent.kind !== 198 /* BinaryExpression */) { + if (!declaration.parent || declaration.parent.kind !== 202 /* BinaryExpression */) { continue; } var rhsSymbol = typeChecker.getSymbolAtLocation(declaration.parent.right); @@ -92647,6 +99735,9 @@ var ts; if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; } + if (tags.length === 0 && tagsFromAlias) { + tags = tagsFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; function getPrinter() { if (!printer) { @@ -92662,7 +99753,7 @@ var ts; } function addAliasPrefixIfNecessary() { if (alias) { - pushTypePart("alias" /* alias */); + pushSymbolKind("alias" /* alias */); displayParts.push(ts.spacePart()); } } @@ -92677,18 +99768,21 @@ var ts; } var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); + if (symbol.flags & 16777216 /* Optional */) { + displayParts.push(ts.punctuationPart(55 /* QuestionToken */)); + } } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { prefixNextMeaning(); if (symbolKind) { - pushTypePart(symbolKind); + pushSymbolKind(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { displayParts.push(ts.spacePart()); addFullSymbolName(symbol); } } } - function pushTypePart(symbolKind) { + function pushSymbolKind(symbolKind) { switch (symbolKind) { case "var" /* variableElement */: case "function" /* functionElement */: @@ -92705,6 +99799,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { + if (flags === void 0) { flags = 0 /* None */; } ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); @@ -92733,16 +99828,16 @@ var ts; } return ts.forEach(symbol.declarations, function (declaration) { // Function expressions are local - if (declaration.kind === 190 /* FunctionExpression */) { + if (declaration.kind === 194 /* FunctionExpression */) { return true; } - if (declaration.kind !== 230 /* VariableDeclaration */ && declaration.kind !== 232 /* FunctionDeclaration */) { + if (declaration.kind !== 235 /* VariableDeclaration */ && declaration.kind !== 237 /* FunctionDeclaration */) { return false; } // If the parent is not sourceFile or module block it is local variable for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { // Reached source file or module block - if (parent.kind === 272 /* SourceFile */ || parent.kind === 238 /* ModuleBlock */) { + if (parent.kind === 277 /* SourceFile */ || parent.kind === 243 /* ModuleBlock */) { return false; } } @@ -92790,7 +99885,7 @@ var ts; options.noResolve = true; // if jsx is specified then treat file as .tsx var inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); - var sourceFile = ts.createSourceFile(inputFileName, input, options.target); + var sourceFile = ts.createSourceFile(inputFileName, input, options.target); // TODO: GH#18217 if (transpileOptions.moduleName) { sourceFile.moduleName = transpileOptions.moduleName; } @@ -92831,7 +99926,8 @@ var ts; } // Emit program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); - ts.Debug.assert(outputText !== undefined, "Output generation failed"); + if (outputText === undefined) + return ts.Debug.fail("Output generation failed"); return { outputText: outputText, diagnostics: diagnostics, sourceMapText: sourceMapText }; } ts.transpileModule = transpileModule; @@ -92854,7 +99950,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_9 = function (opt) { + var _loop_21 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -92873,7 +99969,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_9(opt); + _loop_21(opt); } return options; } @@ -92969,8 +100065,6 @@ var ts; formatting.FormattingContext = FormattingContext; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// /* @internal */ var ts; (function (ts) { @@ -93012,7 +100106,7 @@ var ts; lastTokenInfo = undefined; var isStarted = scanner.getStartPos() !== startPos; if (isStarted) { - wasNewLine = trailingTrivia && ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; + wasNewLine = !!trailingTrivia && ts.last(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { scanner.scan(); @@ -93052,10 +100146,10 @@ var ts; function shouldRescanJsxIdentifier(node) { if (node.parent) { switch (node.parent.kind) { - case 260 /* JsxAttribute */: - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 265 /* JsxAttribute */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ts.isKeyword(node.kind) || node.kind === 71 /* Identifier */; } @@ -93232,7 +100326,7 @@ var ts; (function (formatting) { function getAllRules() { var allTokens = []; - for (var token = 0 /* FirstToken */; token <= 144 /* LastToken */; token++) { + for (var token = 0 /* FirstToken */; token <= 145 /* LastToken */; token++) { allTokens.push(token); } function anyTokenExcept() { @@ -93244,9 +100338,9 @@ var ts; } var anyToken = { tokens: allTokens, isSpecific: false }; var anyTokenIncludingMultilineComments = tokenRangeFrom(allTokens.concat([3 /* MultiLineCommentTrivia */])); - var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 144 /* LastKeyword */); + var keywords = tokenRangeFromRange(72 /* FirstKeyword */, 145 /* LastKeyword */); var binaryOperators = tokenRangeFromRange(27 /* FirstBinaryOperator */, 70 /* LastBinaryOperator */); - var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 144 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; + var binaryKeywordOperators = [92 /* InKeyword */, 93 /* InstanceOfKeyword */, 145 /* OfKeyword */, 118 /* AsKeyword */, 127 /* IsKeyword */]; var unaryPrefixOperators = [43 /* PlusPlusToken */, 44 /* MinusMinusToken */, 52 /* TildeToken */, 51 /* ExclamationToken */]; var unaryPrefixExpressions = [ 8 /* NumericLiteral */, 71 /* Identifier */, 19 /* OpenParenToken */, 21 /* OpenBracketToken */, @@ -93279,6 +100373,7 @@ var ts; rule("NoSpaceAfterQuestionMark", 55 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeDot", anyToken, 23 /* DotToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceAfterDot", 23 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), + rule("NoSpaceBetweenImportParenInImportType", 91 /* ImportKeyword */, 19 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 8 /* Delete */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between // them and their target unary expression. @@ -93333,8 +100428,8 @@ var ts; // Async-await rule("SpaceBetweenAsyncAndOpenParen", 120 /* AsyncKeyword */, 19 /* OpenParenToken */, [isArrowFunctionContext, isNonJsxSameLineTokenContext], 2 /* Space */), rule("SpaceBetweenAsyncAndFunctionKeyword", 120 /* AsyncKeyword */, 89 /* FunctionKeyword */, [isNonJsxSameLineTokenContext], 2 /* Space */), - // template string - rule("NoSpaceBetweenTagAndTemplateString", 71 /* Identifier */, [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), + // Template string + rule("NoSpaceBetweenTagAndTemplateString", [71 /* Identifier */, 20 /* CloseParenToken */], [13 /* NoSubstitutionTemplateLiteral */, 14 /* TemplateHead */], [isNonJsxSameLineTokenContext], 8 /* Delete */), // JSX opening elements rule("SpaceBeforeJsxAttribute", anyToken, 71 /* Identifier */, [isNextTokenParentJsxAttribute, isNonJsxSameLineTokenContext], 2 /* Space */), rule("SpaceBeforeSlashInJsxOpeningElement", anyToken, 41 /* SlashToken */, [isJsxSelfClosingElementContext, isNonJsxSameLineTokenContext], 2 /* Space */), @@ -93366,11 +100461,11 @@ var ts; 136 /* SetKeyword */, 115 /* StaticKeyword */, 139 /* TypeKeyword */, - 142 /* FromKeyword */, + 143 /* FromKeyword */, 128 /* KeyOfKeyword */, 126 /* InferKeyword */, ], anyToken, [isNonJsxSameLineTokenContext], 2 /* Space */), - rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 142 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), + rule("SpaceBeforeCertainTypeScriptKeywords", anyToken, [85 /* ExtendsKeyword */, 108 /* ImplementsKeyword */, 143 /* FromKeyword */], [isNonJsxSameLineTokenContext], 2 /* Space */), // Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" { rule("SpaceAfterModuleName", 9 /* StringLiteral */, 17 /* OpenBraceToken */, [isModuleDeclContext], 2 /* Space */), // Lambda expressions @@ -93386,7 +100481,7 @@ var ts; rule("NoSpaceBetweenCloseParenAndAngularBracket", 20 /* CloseParenToken */, 27 /* LessThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceAfterOpenAngularBracket", 27 /* LessThanToken */, anyToken, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), rule("NoSpaceBeforeCloseAngularBracket", anyToken, 29 /* GreaterThanToken */, [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), - rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext], 8 /* Delete */), + rule("NoSpaceAfterCloseAngularBracket", 29 /* GreaterThanToken */, [19 /* OpenParenToken */, 21 /* OpenBracketToken */, 29 /* GreaterThanToken */, 26 /* CommaToken */], [isNonJsxSameLineTokenContext, isTypeArgumentOrParameterOrAssertionContext, isNotFunctionDeclContext /*To prevent an interference with the SpaceBeforeOpenParenInFuncDecl rule*/], 8 /* Delete */), // decorators rule("SpaceBeforeAt", [20 /* CloseParenToken */, 71 /* Identifier */], 57 /* AtToken */, [isNonJsxSameLineTokenContext], 2 /* Space */), rule("NoSpaceAfterAt", 57 /* AtToken */, anyToken, [isNonJsxSameLineTokenContext], 8 /* Delete */), @@ -93535,45 +100630,45 @@ var ts; return function (context) { return !context.options || !context.options.hasOwnProperty(optionName) || !!context.options[optionName]; }; } function isForContext(context) { - return context.contextNode.kind === 218 /* ForStatement */; + return context.contextNode.kind === 223 /* ForStatement */; } function isNotForContext(context) { return !isForContext(context); } function isBinaryOpContext(context) { switch (context.contextNode.kind) { - case 198 /* BinaryExpression */: - case 199 /* ConditionalExpression */: - case 170 /* ConditionalType */: - case 206 /* AsExpression */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 160 /* TypePredicate */: - case 168 /* UnionType */: - case 169 /* IntersectionType */: + case 202 /* BinaryExpression */: + case 203 /* ConditionalExpression */: + case 173 /* ConditionalType */: + case 210 /* AsExpression */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 161 /* TypePredicate */: + case 171 /* UnionType */: + case 172 /* IntersectionType */: return true; // equals in binding elements: function foo([[x, y] = [1, 2]]) - case 180 /* BindingElement */: + case 184 /* BindingElement */: // equals in type X = ... - case 235 /* TypeAliasDeclaration */: + case 240 /* TypeAliasDeclaration */: // equal in import a = module('a'); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // equal in let a = 0; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: // equal in p = 0; - case 148 /* Parameter */: - case 271 /* EnumMember */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 149 /* Parameter */: + case 276 /* EnumMember */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return context.currentTokenSpan.kind === 58 /* EqualsToken */ || context.nextTokenSpan.kind === 58 /* EqualsToken */; // "in" keyword in for (let x in []) { } - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: // "in" keyword in [P in keyof T]: T[P] - case 147 /* TypeParameter */: + case 148 /* TypeParameter */: return context.currentTokenSpan.kind === 92 /* InKeyword */ || context.nextTokenSpan.kind === 92 /* InKeyword */; // Technically, "of" is not a binary operator, but format it the same way as "in" - case 220 /* ForOfStatement */: - return context.currentTokenSpan.kind === 144 /* OfKeyword */ || context.nextTokenSpan.kind === 144 /* OfKeyword */; + case 225 /* ForOfStatement */: + return context.currentTokenSpan.kind === 145 /* OfKeyword */ || context.nextTokenSpan.kind === 145 /* OfKeyword */; } return false; } @@ -93585,22 +100680,22 @@ var ts; } function isTypeAnnotationContext(context) { var contextKind = context.contextNode.kind; - return contextKind === 151 /* PropertyDeclaration */ || - contextKind === 150 /* PropertySignature */ || - contextKind === 148 /* Parameter */ || - contextKind === 230 /* VariableDeclaration */ || + return contextKind === 152 /* PropertyDeclaration */ || + contextKind === 151 /* PropertySignature */ || + contextKind === 149 /* Parameter */ || + contextKind === 235 /* VariableDeclaration */ || ts.isFunctionLikeKind(contextKind); } function isConditionalOperatorContext(context) { - return context.contextNode.kind === 199 /* ConditionalExpression */ || - context.contextNode.kind === 170 /* ConditionalType */; + return context.contextNode.kind === 203 /* ConditionalExpression */ || + context.contextNode.kind === 173 /* ConditionalType */; } function isSameLineTokenOrBeforeBlockContext(context) { return context.TokensAreOnSameLine() || isBeforeBlockContext(context); } function isBraceWrappedContext(context) { - return context.contextNode.kind === 178 /* ObjectBindingPattern */ || - context.contextNode.kind === 176 /* MappedType */ || + return context.contextNode.kind === 182 /* ObjectBindingPattern */ || + context.contextNode.kind === 179 /* MappedType */ || isSingleLineBlockContext(context); } // This check is done before an open brace in a control construct, a function, or a typescript block declaration @@ -93626,70 +100721,73 @@ var ts; return true; } switch (node.kind) { - case 211 /* Block */: - case 239 /* CaseBlock */: - case 182 /* ObjectLiteralExpression */: - case 238 /* ModuleBlock */: + case 216 /* Block */: + case 244 /* CaseBlock */: + case 186 /* ObjectLiteralExpression */: + case 243 /* ModuleBlock */: return true; } return false; } function isFunctionDeclContext(context) { switch (context.contextNode.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: // case SyntaxKind.MemberFunctionDeclaration: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // case SyntaxKind.MethodSignature: - case 157 /* CallSignature */: - case 190 /* FunctionExpression */: - case 154 /* Constructor */: - case 191 /* ArrowFunction */: + case 158 /* CallSignature */: + case 194 /* FunctionExpression */: + case 155 /* Constructor */: + case 195 /* ArrowFunction */: // case SyntaxKind.ConstructorDeclaration: // case SyntaxKind.SimpleArrowFunctionExpression: // case SyntaxKind.ParenthesizedArrowFunctionExpression: - case 234 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one + case 239 /* InterfaceDeclaration */: // This one is not truly a function, but for formatting purposes, it acts just like one return true; } return false; } + function isNotFunctionDeclContext(context) { + return !isFunctionDeclContext(context); + } function isFunctionDeclarationOrFunctionExpressionContext(context) { - return context.contextNode.kind === 232 /* FunctionDeclaration */ || context.contextNode.kind === 190 /* FunctionExpression */; + return context.contextNode.kind === 237 /* FunctionDeclaration */ || context.contextNode.kind === 194 /* FunctionExpression */; } function isTypeScriptDeclWithBlockContext(context) { return nodeIsTypeScriptDeclWithBlockContext(context.contextNode); } function nodeIsTypeScriptDeclWithBlockContext(node) { switch (node.kind) { - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 165 /* TypeLiteral */: - case 237 /* ModuleDeclaration */: - case 248 /* ExportDeclaration */: - case 249 /* NamedExports */: - case 242 /* ImportDeclaration */: - case 245 /* NamedImports */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 166 /* TypeLiteral */: + case 242 /* ModuleDeclaration */: + case 253 /* ExportDeclaration */: + case 254 /* NamedExports */: + case 247 /* ImportDeclaration */: + case 250 /* NamedImports */: return true; } return false; } function isAfterCodeBlockContext(context) { switch (context.currentTokenParent.kind) { - case 233 /* ClassDeclaration */: - case 237 /* ModuleDeclaration */: - case 236 /* EnumDeclaration */: - case 267 /* CatchClause */: - case 238 /* ModuleBlock */: - case 225 /* SwitchStatement */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 272 /* CatchClause */: + case 243 /* ModuleBlock */: + case 230 /* SwitchStatement */: return true; - case 211 /* Block */: { + case 216 /* Block */: { var blockParent = context.currentTokenParent.parent; // In a codefix scenario, we can't rely on parents being set. So just always return true. - if (!blockParent || blockParent.kind !== 191 /* ArrowFunction */ && blockParent.kind !== 190 /* FunctionExpression */) { + if (!blockParent || blockParent.kind !== 195 /* ArrowFunction */ && blockParent.kind !== 194 /* FunctionExpression */) { return true; } } @@ -93698,31 +100796,31 @@ var ts; } function isControlDeclContext(context) { switch (context.contextNode.kind) { - case 215 /* IfStatement */: - case 225 /* SwitchStatement */: - case 218 /* ForStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 217 /* WhileStatement */: - case 228 /* TryStatement */: - case 216 /* DoStatement */: - case 224 /* WithStatement */: + case 220 /* IfStatement */: + case 230 /* SwitchStatement */: + case 223 /* ForStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 222 /* WhileStatement */: + case 233 /* TryStatement */: + case 221 /* DoStatement */: + case 229 /* WithStatement */: // TODO // case SyntaxKind.ElseClause: - case 267 /* CatchClause */: + case 272 /* CatchClause */: return true; default: return false; } } function isObjectContext(context) { - return context.contextNode.kind === 182 /* ObjectLiteralExpression */; + return context.contextNode.kind === 186 /* ObjectLiteralExpression */; } function isFunctionCallContext(context) { - return context.contextNode.kind === 185 /* CallExpression */; + return context.contextNode.kind === 189 /* CallExpression */; } function isNewContext(context) { - return context.contextNode.kind === 186 /* NewExpression */; + return context.contextNode.kind === 190 /* NewExpression */; } function isFunctionCallOrNewContext(context) { return isFunctionCallContext(context) || isNewContext(context); @@ -93734,32 +100832,35 @@ var ts; return context.nextTokenSpan.kind !== 22 /* CloseBracketToken */; } function isArrowFunctionContext(context) { - return context.contextNode.kind === 191 /* ArrowFunction */; + return context.contextNode.kind === 195 /* ArrowFunction */; + } + function isImportTypeContext(context) { + return context.contextNode.kind === 181 /* ImportType */; } function isNonJsxSameLineTokenContext(context) { return context.TokensAreOnSameLine() && context.contextNode.kind !== 10 /* JsxText */; } function isNonJsxElementOrFragmentContext(context) { - return context.contextNode.kind !== 253 /* JsxElement */ && context.contextNode.kind !== 257 /* JsxFragment */; + return context.contextNode.kind !== 258 /* JsxElement */ && context.contextNode.kind !== 262 /* JsxFragment */; } function isJsxExpressionContext(context) { - return context.contextNode.kind === 263 /* JsxExpression */ || context.contextNode.kind === 262 /* JsxSpreadAttribute */; + return context.contextNode.kind === 268 /* JsxExpression */ || context.contextNode.kind === 267 /* JsxSpreadAttribute */; } function isNextTokenParentJsxAttribute(context) { - return context.nextTokenParent.kind === 260 /* JsxAttribute */; + return context.nextTokenParent.kind === 265 /* JsxAttribute */; } function isJsxAttributeContext(context) { - return context.contextNode.kind === 260 /* JsxAttribute */; + return context.contextNode.kind === 265 /* JsxAttribute */; } function isJsxSelfClosingElementContext(context) { - return context.contextNode.kind === 254 /* JsxSelfClosingElement */; + return context.contextNode.kind === 259 /* JsxSelfClosingElement */; } function isNotBeforeBlockInFunctionDeclarationContext(context) { return !isFunctionDeclContext(context) && !isBeforeBlockContext(context); } function isEndOfDecoratorContextOnSameLine(context) { return context.TokensAreOnSameLine() && - context.contextNode.decorators && + !!context.contextNode.decorators && nodeIsInDecoratorContext(context.currentTokenParent) && !nodeIsInDecoratorContext(context.nextTokenParent); } @@ -93767,45 +100868,45 @@ var ts; while (ts.isExpressionNode(node)) { node = node.parent; } - return node.kind === 149 /* Decorator */; + return node.kind === 150 /* Decorator */; } function isStartOfVariableDeclarationList(context) { - return context.currentTokenParent.kind === 231 /* VariableDeclarationList */ && + return context.currentTokenParent.kind === 236 /* VariableDeclarationList */ && context.currentTokenParent.getStart(context.sourceFile) === context.currentTokenSpan.pos; } function isNotFormatOnEnter(context) { return context.formattingRequestKind !== 2 /* FormatOnEnter */; } function isModuleDeclContext(context) { - return context.contextNode.kind === 237 /* ModuleDeclaration */; + return context.contextNode.kind === 242 /* ModuleDeclaration */; } function isObjectTypeContext(context) { - return context.contextNode.kind === 165 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; + return context.contextNode.kind === 166 /* TypeLiteral */; // && context.contextNode.parent.kind !== SyntaxKind.InterfaceDeclaration; } function isConstructorSignatureContext(context) { - return context.contextNode.kind === 158 /* ConstructSignature */; + return context.contextNode.kind === 159 /* ConstructSignature */; } function isTypeArgumentOrParameterOrAssertion(token, parent) { if (token.kind !== 27 /* LessThanToken */ && token.kind !== 29 /* GreaterThanToken */) { return false; } switch (parent.kind) { - case 161 /* TypeReference */: - case 188 /* TypeAssertionExpression */: - case 235 /* TypeAliasDeclaration */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 205 /* ExpressionWithTypeArguments */: + case 162 /* TypeReference */: + case 192 /* TypeAssertionExpression */: + case 240 /* TypeAliasDeclaration */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 209 /* ExpressionWithTypeArguments */: return true; default: return false; @@ -93816,20 +100917,19 @@ var ts; isTypeArgumentOrParameterOrAssertion(context.nextTokenSpan, context.nextTokenParent); } function isTypeAssertionContext(context) { - return context.contextNode.kind === 188 /* TypeAssertionExpression */; + return context.contextNode.kind === 192 /* TypeAssertionExpression */; } function isVoidOpContext(context) { - return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 194 /* VoidExpression */; + return context.currentTokenSpan.kind === 105 /* VoidKeyword */ && context.currentTokenParent.kind === 198 /* VoidExpression */; } function isYieldOrYieldStarWithOperand(context) { - return context.contextNode.kind === 201 /* YieldExpression */ && context.contextNode.expression !== undefined; + return context.contextNode.kind === 205 /* YieldExpression */ && context.contextNode.expression !== undefined; } function isNonNullAssertionContext(context) { - return context.contextNode.kind === 207 /* NonNullExpression */; + return context.contextNode.kind === 211 /* NonNullExpression */; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// /* @internal */ var ts; (function (ts) { @@ -93877,12 +100977,12 @@ var ts; return map; } function getRuleBucketIndex(row, column) { - ts.Debug.assert(row <= 144 /* LastKeyword */ && column <= 144 /* LastKeyword */, "Must compute formatting context from tokens"); + ts.Debug.assert(row <= 145 /* LastKeyword */ && column <= 145 /* LastKeyword */, "Must compute formatting context from tokens"); return (row * mapRowLength) + column; } var maskBitSize = 5; var mask = 31; // MaskBitSize bits - var mapRowLength = 144 /* LastToken */ + 1; + var mapRowLength = 145 /* LastToken */ + 1; var RulesPosition; (function (RulesPosition) { RulesPosition[RulesPosition["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; @@ -93932,10 +101032,6 @@ var ts; } })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); -/// -/// -/// -/// /* @internal */ var ts; (function (ts) { @@ -94064,17 +101160,17 @@ var ts; // i.e. parent is class declaration with the list of members and node is one of members. function isListElement(parent, node) { switch (parent.kind) { - case 233 /* ClassDeclaration */: - case 234 /* InterfaceDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: return ts.rangeContainsRange(parent.members, node); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 238 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); - case 272 /* SourceFile */: - case 211 /* Block */: - case 238 /* ModuleBlock */: + return !!body && body.kind === 243 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); + case 277 /* SourceFile */: + case 216 /* Block */: + case 243 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return ts.rangeContainsRange(parent.block.statements, node); } return false; @@ -94103,7 +101199,7 @@ var ts; } // pick only errors that fall in range var sorted = errors - .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) + .filter(function (d) { return ts.rangeOverlapsWithStartEnd(originalRange, d.start, d.start + d.length); }) // TODO: GH#18217 .sort(function (e1, e2) { return e1.start - e2.start; }); if (!sorted.length) { return rangeHasNoErrors; @@ -94178,7 +101274,7 @@ var ts; if (previousLine !== -1 /* Unknown */ && line !== previousLine) { break; } - if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { + if (formatting.SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) { return options.indentSize; } previousLine = line; @@ -94231,7 +101327,7 @@ var ts; if (!formattingScanner.isOnToken()) { var leadingTrivia = formattingScanner.getCurrentLeadingTrivia(); if (leadingTrivia) { - processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); + processTrivia(leadingTrivia, enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined); // TODO: GH#18217 trimTrailingWhitespacesForRemainingRange(); } } @@ -94265,7 +101361,7 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -94297,20 +101393,23 @@ var ts; return node.modifiers[0].kind; } switch (node.kind) { - case 233 /* ClassDeclaration */: return 75 /* ClassKeyword */; - case 234 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; - case 232 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; - case 236 /* EnumDeclaration */: return 236 /* EnumDeclaration */; - case 155 /* GetAccessor */: return 125 /* GetKeyword */; - case 156 /* SetAccessor */: return 136 /* SetKeyword */; - case 153 /* MethodDeclaration */: + case 238 /* ClassDeclaration */: return 75 /* ClassKeyword */; + case 239 /* InterfaceDeclaration */: return 109 /* InterfaceKeyword */; + case 237 /* FunctionDeclaration */: return 89 /* FunctionKeyword */; + case 241 /* EnumDeclaration */: return 241 /* EnumDeclaration */; + case 156 /* GetAccessor */: return 125 /* GetKeyword */; + case 157 /* SetAccessor */: return 136 /* SetKeyword */; + case 154 /* MethodDeclaration */: if (node.asteriskToken) { return 39 /* AsteriskToken */; } // falls through - case 151 /* PropertyDeclaration */: - case 148 /* Parameter */: - return ts.getNameOfDeclaration(node).kind; + case 152 /* PropertyDeclaration */: + case 149 /* Parameter */: + var name = ts.getNameOfDeclaration(node); + if (name) { + return name.kind; + } } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -94334,9 +101433,9 @@ var ts; getIndentation: function () { return indentation; }, getDelta: getDelta, recomputeIndentation: function (lineAdded) { - if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { + if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(options, node.parent, node, sourceFile)) { indentation += lineAdded ? options.indentSize : -options.indentSize; - delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; + delta = formatting.SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize : 0; } } }; @@ -94354,15 +101453,15 @@ var ts; case 41 /* SlashToken */: case 29 /* GreaterThanToken */: switch (container.kind) { - case 255 /* JsxOpeningElement */: - case 256 /* JsxClosingElement */: - case 254 /* JsxSelfClosingElement */: + case 260 /* JsxOpeningElement */: + case 261 /* JsxClosingElement */: + case 259 /* JsxSelfClosingElement */: return false; } break; case 21 /* OpenBracketToken */: case 22 /* CloseBracketToken */: - if (container.kind !== 176 /* MappedType */) { + if (container.kind !== 179 /* MappedType */) { return false; } break; @@ -94374,7 +101473,7 @@ var ts; } function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node - return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; + return formatting.SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0; } } function processNode(node, contextNode, nodeStartLine, undecoratedNodeStartLine, indentation, delta) { @@ -94454,7 +101553,7 @@ var ts; consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child); return inheritedIndentation; } - var effectiveParentStartLine = child.kind === 149 /* Decorator */ ? childStartLine : undecoratedParentStartLine; + var effectiveParentStartLine = child.kind === 150 /* Decorator */ ? childStartLine : undecoratedParentStartLine; var childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine); processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta); if (child.kind === 10 /* JsxText */) { @@ -94462,7 +101561,7 @@ var ts; indentMultilineCommentOrJsxText(range, childIndentation.indentation, /*firstLineIsIndented*/ true, /*indentFinalLine*/ false); } childContextNode = node; - if (isFirstListItem && parent.kind === 181 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { + if (isFirstListItem && parent.kind === 185 /* ArrayLiteralExpression */ && inheritedIndentation === -1 /* Unknown */) { inheritedIndentation = childIndentation.indentation; } return inheritedIndentation; @@ -94470,7 +101569,6 @@ var ts; function processChildNodes(nodes, parent, parentStartLine, parentDynamicIndentation) { ts.Debug.assert(ts.isNodeArray(nodes)); var listStartToken = getOpenTokenForList(parent, nodes); - var listEndToken = getCloseTokenForOpenToken(listStartToken); var listDynamicIndentation = parentDynamicIndentation; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { @@ -94484,8 +101582,8 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); - listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); + var indentation_2 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); + listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_2.indentation, indentation_2.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } else { @@ -94499,17 +101597,20 @@ var ts; var child = nodes[i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } - if (listEndToken !== 0 /* Unknown */) { - if (formattingScanner.isOnToken()) { - var tokenInfo = formattingScanner.readTokenInfo(parent); - // consume the list end token only if it is still belong to the parent - // there might be the case when current token matches end token but does not considered as one - // function (x: function) <-- - // without this check close paren will be interpreted as list end token for function expression which is wrong - if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { - // consume list end token - consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); - } + var listEndToken = getCloseTokenForOpenToken(listStartToken); + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + var tokenInfo = formattingScanner.readTokenInfo(parent); + if (tokenInfo.token.kind === 26 /* CommaToken */ && ts.isCallLikeExpression(parent)) { + formattingScanner.advance(); + tokenInfo = formattingScanner.readTokenInfo(parent); + } + // consume the list end token only if it is still belong to the parent + // there might be the case when current token matches end token but does not considered as one + // function (x: function) <-- + // without this check close paren will be interpreted as list end token for function expression which is wrong + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { + // consume list end token + consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent); } } } @@ -94592,6 +101693,7 @@ var ts; } } } + // TODO: GH#18217 use an enum instead of `boolean | undefined` function processRange(range, rangeStart, parent, contextNode, dynamicIndentation) { var rangeHasError = rangeContainsError(range); var lineAction = 0 /* None */; @@ -94684,7 +101786,6 @@ var ts; // split comment in lines var startLine = sourceFile.getLineAndCharacterOfPosition(commentRange.pos).line; var endLine = sourceFile.getLineAndCharacterOfPosition(commentRange.end).line; - var parts; if (startLine === endLine) { if (!firstLineIsIndented) { // treat as single line comment @@ -94692,18 +101793,18 @@ var ts; } return; } - else { - parts = []; - var startPos = commentRange.pos; - for (var line = startLine; line < endLine; line++) { - var endOfLine = ts.getEndLinePosition(line, sourceFile); - parts.push({ pos: startPos, end: endOfLine }); - startPos = ts.getStartPositionOfLine(line + 1, sourceFile); - } - if (indentFinalLine) { - parts.push({ pos: startPos, end: commentRange.end }); - } + var parts = []; + var startPos = commentRange.pos; + for (var line = startLine; line < endLine; line++) { + var endOfLine = ts.getEndLinePosition(line, sourceFile); + parts.push({ pos: startPos, end: endOfLine }); + startPos = ts.getStartPositionOfLine(line + 1, sourceFile); } + if (indentFinalLine) { + parts.push({ pos: startPos, end: commentRange.end }); + } + if (parts.length === 0) + return; var startLinePos = ts.getStartPositionOfLine(startLine, sourceFile); var nonWhitespaceColumnInFirstPart = formatting.SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); if (indentation === nonWhitespaceColumnInFirstPart.column) { @@ -94829,56 +101930,47 @@ 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); } + function getRangeOfEnclosingComment(sourceFile, position, precedingToken, // tslint:disable-line:no-null-keyword + tokenAtPosition) { + if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position); } + var jsdoc = ts.findAncestor(tokenAtPosition, ts.isJSDoc); + if (jsdoc) + tokenAtPosition = jsdoc.parent; var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { return undefined; } - if (precedingToken === undefined) { - precedingToken = ts.findPrecedingToken(position, sourceFile); - } + precedingToken = precedingToken === null ? undefined : precedingToken === undefined ? ts.findPrecedingToken(position, sourceFile) : precedingToken; // 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; + var commentRanges = ts.concatenate(trailingRangesOfPreviousToken, leadingCommentRangesOfNextToken); + return commentRanges && ts.find(commentRanges, function (range) { return ts.rangeContainsPositionExclusive(range, position) || + // 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. + // + position === range.end && (range.kind === 2 /* SingleLineCommentTrivia */ || position === sourceFile.getFullWidth()); }); } formatting.getRangeOfEnclosingComment = getRangeOfEnclosingComment; function getOpenTokenForList(node, list) { switch (node.kind) { - case 154 /* Constructor */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 191 /* ArrowFunction */: + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 195 /* ArrowFunction */: if (node.typeParameters === list) { return 27 /* LessThanToken */; } @@ -94886,8 +101978,8 @@ var ts; return 19 /* OpenParenToken */; } break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -94895,7 +101987,7 @@ var ts; return 19 /* OpenParenToken */; } break; - case 161 /* TypeReference */: + case 162 /* TypeReference */: if (node.typeArguments === list) { return 27 /* LessThanToken */; } @@ -94992,9 +102084,9 @@ var ts; if (options.indentStyle === ts.IndentStyle.None) { 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 precedingToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*excludeJsdoc*/ true); + var enclosingCommentRange = formatting.getRangeOfEnclosingComment(sourceFile, position, precedingToken || null); // tslint:disable-line:no-null-keyword + if (enclosingCommentRange && enclosingCommentRange.kind === 3 /* MultiLineCommentTrivia */) { return getCommentIndent(sourceFile, position, options, enclosingCommentRange); } if (!precedingToken) { @@ -95012,7 +102104,7 @@ var ts; if (options.indentStyle === ts.IndentStyle.Block) { return getBlockIndent(sourceFile, position, options); } - if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 198 /* BinaryExpression */) { + if (precedingToken.kind === 26 /* CommaToken */ && precedingToken.parent.kind !== 202 /* BinaryExpression */) { // previous token is comma that separates items in list - find the previous item and try to derive indentation from it var actualIndentation = getActualIndentationForListItemBeforeComma(precedingToken, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { @@ -95057,14 +102149,14 @@ var ts; var previous; var current = precedingToken; while (current) { - if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(current, previous, /*isNextChild*/ true)) { + if (ts.positionBelongsToNode(current, position, sourceFile) && shouldIndentChildNode(options, current, previous, sourceFile, /*isNextChild*/ true)) { var currentStart = getStartLineAndCharacterForNode(current, sourceFile); var nextTokenKind = nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile); var indentationDelta = nextTokenKind !== 0 /* Unknown */ // handle cases when codefix is about to be inserted before the close brace ? assumeNewLineBeforeCloseBrace && nextTokenKind === 2 /* CloseBrace */ ? options.indentSize : 0 : lineAtPosition !== currentStart.line ? options.indentSize : 0; - return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); + return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, /*isNextChild*/ true, options); // TODO: GH#18217 } // check if current node is a list item - if yes, take indentation from it var actualIndentation = getActualIndentationForListItem(current, sourceFile, options); @@ -95073,7 +102165,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.indentSize; + return actualIndentation + options.indentSize; // TODO: GH#18217 } previous = current; current = current.parent; @@ -95123,7 +102215,7 @@ var ts; } } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line - if (shouldIndentChildNode(parent, current, isNextChild) && !parentAndChildShareLine) { + if (shouldIndentChildNode(options, parent, current, sourceFile, isNextChild) && !parentAndChildShareLine) { indentationDelta += options.indentSize; } // In our AST, a call argument's `parent` is the call-expression, not the argument list. @@ -95168,7 +102260,7 @@ var ts; // - parent is SourceFile - by default immediate children of SourceFile are not indented except when user indents them manually // - parent and child are not on the same line var useActualIndentation = (ts.isDeclaration(current) || ts.isStatementButNotDeclaration(current)) && - (parent.kind === 272 /* SourceFile */ || !parentAndChildShareLine); + (parent.kind === 277 /* SourceFile */ || !parentAndChildShareLine); if (!useActualIndentation) { return -1 /* Unknown */; } @@ -95181,7 +102273,7 @@ var ts; NextTokenKind[NextTokenKind["CloseBrace"] = 2] = "CloseBrace"; })(NextTokenKind || (NextTokenKind = {})); function nextTokenIsCurlyBraceOnSameLineAsCursor(precedingToken, current, lineAtPosition, sourceFile) { - var nextToken = ts.findNextToken(precedingToken, current); + var nextToken = ts.findNextToken(precedingToken, current, sourceFile); if (!nextToken) { return 0 /* Unknown */; } @@ -95216,7 +102308,7 @@ var ts; } SmartIndenter.isArgumentAndStartLineOverlapsExpressionBeingCalled = isArgumentAndStartLineOverlapsExpressionBeingCalled; function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 215 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 220 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 82 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -95230,39 +102322,46 @@ var ts; } function getContainingList(node, sourceFile) { if (node.parent) { + var end = node.end; switch (node.parent.kind) { - case 161 /* TypeReference */: - return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), node.getEnd()); - case 182 /* ObjectLiteralExpression */: + case 162 /* TypeReference */: + return getListIfStartEndIsInListRange(node.parent.typeArguments, node.getStart(sourceFile), end); + case 186 /* ObjectLiteralExpression */: return node.parent.properties; - case 181 /* ArrayLiteralExpression */: + case 185 /* ArrayLiteralExpression */: return node.parent.elements; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 154 /* Constructor */: - case 163 /* ConstructorType */: - case 158 /* ConstructSignature */: { + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 155 /* Constructor */: + case 164 /* ConstructorType */: + case 159 /* ConstructSignature */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeParameters, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.parameters, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeParameters, start, end) || + getListIfStartEndIsInListRange(node.parent.parameters, start, end); } - case 233 /* ClassDeclaration */: - return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), node.getEnd()); - case 186 /* NewExpression */: - case 185 /* CallExpression */: { + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + return getListIfStartEndIsInListRange(node.parent.typeParameters, node.getStart(sourceFile), end); + case 190 /* NewExpression */: + case 189 /* CallExpression */: { var start = node.getStart(sourceFile); - return getListIfStartEndIsInListRange(node.parent.typeArguments, start, node.getEnd()) || - getListIfStartEndIsInListRange(node.parent.arguments, start, node.getEnd()); + return getListIfStartEndIsInListRange(node.parent.typeArguments, start, end) || + getListIfStartEndIsInListRange(node.parent.arguments, start, end); } - case 231 /* VariableDeclarationList */: - return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), node.getEnd()); - case 245 /* NamedImports */: - case 249 /* NamedExports */: - return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), node.getEnd()); + case 236 /* VariableDeclarationList */: + return getListIfStartEndIsInListRange(node.parent.declarations, node.getStart(sourceFile), end); + case 250 /* NamedImports */: + case 254 /* NamedExports */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: + return getListIfStartEndIsInListRange(node.parent.elements, node.getStart(sourceFile), end); } } return undefined; @@ -95301,10 +102400,10 @@ var ts; function getStartingExpression(node) { while (true) { switch (node.kind) { - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 183 /* PropertyAccessExpression */: - case 184 /* ElementAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 187 /* PropertyAccessExpression */: + case 188 /* ElementAccessExpression */: node = node.expression; break; default: @@ -95366,84 +102465,89 @@ var ts; return findFirstNonWhitespaceCharacterAndColumn(startPos, endPos, sourceFile, options).column; } SmartIndenter.findFirstNonWhitespaceColumn = findFirstNonWhitespaceColumn; - function nodeContentIsAlwaysIndented(kind) { - switch (kind) { - case 214 /* ExpressionStatement */: - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 236 /* EnumDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 181 /* ArrayLiteralExpression */: - case 211 /* Block */: - case 238 /* ModuleBlock */: - case 182 /* ObjectLiteralExpression */: - case 165 /* TypeLiteral */: - case 176 /* MappedType */: - case 167 /* TupleType */: - case 239 /* CaseBlock */: - case 265 /* DefaultClause */: - case 264 /* CaseClause */: - case 189 /* ParenthesizedExpression */: - case 183 /* PropertyAccessExpression */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 212 /* VariableStatement */: - case 230 /* VariableDeclaration */: - case 247 /* ExportAssignment */: - case 223 /* ReturnStatement */: - case 199 /* ConditionalExpression */: - case 179 /* ArrayBindingPattern */: - case 178 /* ObjectBindingPattern */: - case 255 /* JsxOpeningElement */: - case 258 /* JsxOpeningFragment */: - case 254 /* JsxSelfClosingElement */: - case 263 /* JsxExpression */: - case 152 /* MethodSignature */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 148 /* Parameter */: - case 162 /* FunctionType */: - case 163 /* ConstructorType */: - case 172 /* ParenthesizedType */: - case 187 /* TaggedTemplateExpression */: - case 195 /* AwaitExpression */: - case 249 /* NamedExports */: - case 245 /* NamedImports */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 268 /* PropertyAssignment */: - case 151 /* PropertyDeclaration */: - return true; - } - return false; - } - function nodeWillIndentChild(parent, child, indentByDefault) { + function nodeWillIndentChild(settings, parent, child, sourceFile, indentByDefault) { var childKind = child ? child.kind : 0 /* Unknown */; switch (parent.kind) { - case 216 /* DoStatement */: - case 217 /* WhileStatement */: - case 219 /* ForInStatement */: - case 220 /* ForOfStatement */: - case 218 /* ForStatement */: - case 215 /* IfStatement */: - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 191 /* ArrowFunction */: - case 154 /* Constructor */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - return childKind !== 211 /* Block */; - case 248 /* ExportDeclaration */: - return childKind !== 249 /* NamedExports */; - case 242 /* ImportDeclaration */: - return childKind !== 243 /* ImportClause */ || - (!!child.namedBindings && child.namedBindings.kind !== 245 /* NamedImports */); - case 253 /* JsxElement */: - return childKind !== 256 /* JsxClosingElement */; - case 257 /* JsxFragment */: - return childKind !== 259 /* JsxClosingFragment */; + case 219 /* ExpressionStatement */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 185 /* ArrayLiteralExpression */: + case 216 /* Block */: + case 243 /* ModuleBlock */: + case 186 /* ObjectLiteralExpression */: + case 166 /* TypeLiteral */: + case 179 /* MappedType */: + case 168 /* TupleType */: + case 244 /* CaseBlock */: + case 270 /* DefaultClause */: + case 269 /* CaseClause */: + case 193 /* ParenthesizedExpression */: + case 187 /* PropertyAccessExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 217 /* VariableStatement */: + case 252 /* ExportAssignment */: + case 228 /* ReturnStatement */: + case 203 /* ConditionalExpression */: + case 183 /* ArrayBindingPattern */: + case 182 /* ObjectBindingPattern */: + case 260 /* JsxOpeningElement */: + case 263 /* JsxOpeningFragment */: + case 259 /* JsxSelfClosingElement */: + case 268 /* JsxExpression */: + case 153 /* MethodSignature */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 149 /* Parameter */: + case 163 /* FunctionType */: + case 164 /* ConstructorType */: + case 175 /* ParenthesizedType */: + case 191 /* TaggedTemplateExpression */: + case 199 /* AwaitExpression */: + case 254 /* NamedExports */: + case 250 /* NamedImports */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 152 /* PropertyDeclaration */: + return true; + case 235 /* VariableDeclaration */: + case 273 /* PropertyAssignment */: + if (!settings.indentMultiLineObjectLiteralBeginningOnBlankLine && sourceFile && childKind === 186 /* ObjectLiteralExpression */) { // TODO: GH#18217 + return rangeIsOnOneLine(sourceFile, child); + } + return true; + case 221 /* DoStatement */: + case 222 /* WhileStatement */: + case 224 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 223 /* ForStatement */: + case 220 /* IfStatement */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 195 /* ArrowFunction */: + case 155 /* Constructor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + return childKind !== 216 /* Block */; + case 253 /* ExportDeclaration */: + return childKind !== 254 /* NamedExports */; + case 247 /* ImportDeclaration */: + return childKind !== 248 /* ImportClause */ || + (!!child.namedBindings && child.namedBindings.kind !== 250 /* NamedImports */); + case 258 /* JsxElement */: + return childKind !== 261 /* JsxClosingElement */; + case 262 /* JsxFragment */: + return childKind !== 264 /* JsxClosingFragment */; + case 172 /* IntersectionType */: + case 171 /* UnionType */: + if (childKind === 166 /* TypeLiteral */) { + return false; + } + // falls through } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; @@ -95451,18 +102555,11 @@ var ts; SmartIndenter.nodeWillIndentChild = nodeWillIndentChild; function isControlFlowEndingStatement(kind, parent) { switch (kind) { - case 223 /* ReturnStatement */: - case 227 /* ThrowStatement */: { - if (parent.kind !== 211 /* Block */) { - return true; - } - var grandParent = parent.parent; - // In a function, we may want to write inner functions after this. - return !(grandParent && grandParent.kind === 190 /* FunctionExpression */ || grandParent.kind === 232 /* FunctionDeclaration */); - } - case 221 /* ContinueStatement */: - case 222 /* BreakStatement */: - return true; + case 228 /* ReturnStatement */: + case 232 /* ThrowStatement */: + case 226 /* ContinueStatement */: + case 227 /* BreakStatement */: + return parent.kind !== 216 /* Block */; default: return false; } @@ -95471,12 +102568,18 @@ var ts; * True when the parent node should indent the given child by an explicit rule. * @param isNextChild If true, we are judging indent of a hypothetical child *after* this one, not the current child. */ - function shouldIndentChildNode(parent, child, isNextChild) { + function shouldIndentChildNode(settings, parent, child, sourceFile, isNextChild) { if (isNextChild === void 0) { isNextChild = false; } - return (nodeContentIsAlwaysIndented(parent.kind) || nodeWillIndentChild(parent, child, /*indentByDefault*/ false)) + return nodeWillIndentChild(settings, parent, child, sourceFile, /*indentByDefault*/ false) && !(isNextChild && child && isControlFlowEndingStatement(child.kind, parent)); } SmartIndenter.shouldIndentChildNode = shouldIndentChildNode; + function rangeIsOnOneLine(sourceFile, range) { + var rangeStart = ts.skipTrivia(sourceFile.text, range.pos); + var startLine = sourceFile.getLineAndCharacterOfPosition(rangeStart).line; + var endLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; + return startLine === endLine; + } })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); @@ -95484,7 +102587,7 @@ var ts; var ts; (function (ts) { var textChanges; - (function (textChanges_1) { + (function (textChanges_3) { /** * Currently for simplicity we store recovered positions on the node itself. * It can be changed to side-table later if we decide that current design is too invasive. @@ -95511,7 +102614,7 @@ var ts; (function (Position) { Position[Position["FullStart"] = 0] = "FullStart"; Position[Position["Start"] = 1] = "Start"; - })(Position = textChanges_1.Position || (textChanges_1.Position = {})); + })(Position = textChanges_3.Position || (textChanges_3.Position = {})); function skipWhitespacesAndLineBreaks(text, start) { return ts.skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } @@ -95527,7 +102630,7 @@ var ts; } return false; } - textChanges_1.useNonAdjustedPositions = { + textChanges_3.useNonAdjustedPositions = { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true, }; @@ -95536,11 +102639,11 @@ var ts; ChangeKind[ChangeKind["Remove"] = 0] = "Remove"; ChangeKind[ChangeKind["ReplaceWithSingleNode"] = 1] = "ReplaceWithSingleNode"; ChangeKind[ChangeKind["ReplaceWithMultipleNodes"] = 2] = "ReplaceWithMultipleNodes"; + ChangeKind[ChangeKind["Text"] = 3] = "Text"; })(ChangeKind || (ChangeKind = {})); - function getSeparatorCharacter(separator) { - return ts.tokenToString(separator.kind); + function getAdjustedRange(sourceFile, startNode, endNode, options) { + return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - textChanges_1.getSeparatorCharacter = getSeparatorCharacter; function getAdjustedStartPosition(sourceFile, node, options, position) { if (options.useNonAdjustedStartPosition) { return node.getStart(sourceFile); @@ -95570,23 +102673,21 @@ var ts; adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition); return ts.getStartPositionOfLine(ts.getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile); } - textChanges_1.getAdjustedStartPosition = getAdjustedStartPosition; function getAdjustedEndPosition(sourceFile, node, options) { + var end = node.end; if (options.useNonAdjustedEndPosition || ts.isExpression(node)) { - return node.getEnd(); + return end; } - var end = node.getEnd(); var newEnd = ts.skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); return newEnd !== end && ts.isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) ? newEnd : end; } - textChanges_1.getAdjustedEndPosition = getAdjustedEndPosition; /** * Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element */ function isSeparator(node, candidate) { - return candidate && node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 182 /* ObjectLiteralExpression */)); + return !!candidate && !!node.parent && (candidate.kind === 26 /* CommaToken */ || (candidate.kind === 25 /* SemicolonToken */ && node.parent.kind === 186 /* ObjectLiteralExpression */)); } function spaces(count) { var s = ""; @@ -95601,9 +102702,9 @@ var ts; this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.deletedNodesInLists = []; // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - // Map from class id to nodes to insert at the start - this.nodesInsertedAtClassStarts = ts.createMap(); + this.newFiles = []; + this.classesWithNodesInsertedAtStart = ts.createMap(); // Set implemented as Map + this.deletedNodes = []; } ChangeTracker.fromContext = function (context) { return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext); @@ -95617,13 +102718,11 @@ var ts; this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); return this; }; - /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ - 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.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - return this; + ChangeTracker.prototype.delete = function (sourceFile, node) { + this.deletedNodes.push({ sourceFile: sourceFile, node: node, }); + }; + ChangeTracker.prototype.deleteModifier = function (sourceFile, modifier) { + this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: ts.skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); }; ChangeTracker.prototype.deleteNodeRange = function (sourceFile, startNode, endNode, options) { if (options === void 0) { options = {}; } @@ -95632,92 +102731,49 @@ var ts; this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); return this; }; - ChangeTracker.prototype.deleteNodeInList = function (sourceFile, node) { - var containingList = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); - if (!containingList) { - ts.Debug.fail("node is not a list element"); - return this; - } - var index = ts.indexOfNode(containingList, node); - if (index < 0) { - return this; - } - if (containingList.length === 1) { - this.deleteNode(sourceFile, node); - return this; - } - var id = ts.getNodeId(node); - ts.Debug.assert(!this.deletedNodesInLists[id], "Deleting a node twice"); - this.deletedNodesInLists[id] = true; - if (index !== containingList.length - 1) { - var nextToken = ts.getTokenAtPosition(sourceFile, node.end, /*includeJsDocComment*/ false); - if (nextToken && isSeparator(node, nextToken)) { - // find first non-whitespace position in the leading trivia of the node - var startPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var nextElement = containingList[index + 1]; - /// find first non-whitespace position in the leading trivia of the next node - var endPosition = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, nextElement, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - // shift next node so its first non-whitespace position will be moved to the first non-whitespace position of the deleted node - this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); - } - } - else { - var prev = containingList[index - 1]; - if (this.deletedNodesInLists[ts.getNodeId(prev)]) { - var pos = ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); - var end = getAdjustedEndPosition(sourceFile, node, {}); - this.deleteRange(sourceFile, { pos: pos, end: end }); - } - else { - var previousToken = ts.getTokenAtPosition(sourceFile, containingList[index - 1].end, /*includeJsDocComment*/ false); - if (previousToken && isSeparator(node, previousToken)) { - this.deleteNodeRange(sourceFile, previousToken, node); - } - } - } - return this; + ChangeTracker.prototype.deleteNodeRangeExcludingEnd = function (sourceFile, startNode, afterEndNode, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + var endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceRange = function (sourceFile, range, newNode, options) { if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, range: range, options: options, node: newNode }); return this; }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNode = function (sourceFile, oldNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options); }; - // TODO (https://github.com/Microsoft/TypeScript/issues/21246): default should probably be useNonAdjustedPositions ChangeTracker.prototype.replaceNodeRange = function (sourceFile, startNode, endNode, newNode, options) { - if (options === void 0) { options = {}; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRange(sourceFile, { pos: pos, end: end }, newNode, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options); }; ChangeTracker.prototype.replaceRangeWithNodes = function (sourceFile, range, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } + if (options === void 0) { options = {}; } this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile: sourceFile, range: range, options: options, nodes: newNodes }); return this; }; ChangeTracker.prototype.replaceNodeWithNodes = function (sourceFile, oldNode, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, oldNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, oldNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options); }; ChangeTracker.prototype.replaceNodeRangeWithNodes = function (sourceFile, startNode, endNode, newNodes, options) { - if (options === void 0) { options = textChanges_1.useNonAdjustedPositions; } - var pos = getAdjustedStartPosition(sourceFile, startNode, options, Position.Start); - var end = getAdjustedEndPosition(sourceFile, endNode, options); - return this.replaceRangeWithNodes(sourceFile, { pos: pos, end: end }, newNodes, options); + if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } + return this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options); + }; + ChangeTracker.prototype.nextCommaToken = function (sourceFile, node) { + var next = ts.findNextToken(node, node.parent, sourceFile); + return next && next.kind === 26 /* CommaToken */ ? next : undefined; + }; + ChangeTracker.prototype.replacePropertyAssignment = function (sourceFile, oldNode, newNode) { + var suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter); + return this.replaceNode(sourceFile, oldNode, newNode, { suffix: suffix }); }; ChangeTracker.prototype.insertNodeAt = function (sourceFile, pos, newNode, options) { if (options === void 0) { options = {}; } - this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile: sourceFile, options: options, node: newNode, range: { pos: pos, end: pos } }); - return this; + this.replaceRange(sourceFile, ts.createTextRange(pos), newNode, options); }; ChangeTracker.prototype.insertNodesAt = function (sourceFile, pos, newNodes, options) { if (options === void 0) { options = {}; } @@ -95732,20 +102788,47 @@ var ts; }; ChangeTracker.prototype.insertNodeBefore = function (sourceFile, before, newNode, blankLineBetween) { if (blankLineBetween === void 0) { blankLineBetween = false; } - var pos = getAdjustedStartPosition(sourceFile, before, {}, Position.Start); - return this.replaceRange(sourceFile, { pos: pos, end: pos }, newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); }; ChangeTracker.prototype.insertModifierBefore = function (sourceFile, modifier, before) { var pos = before.getStart(sourceFile); this.replaceRange(sourceFile, { pos: pos, end: pos }, ts.createToken(modifier), { suffix: " " }); }; + ChangeTracker.prototype.insertCommentBeforeLine = function (sourceFile, lineNumber, position, commentText) { + var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); + var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); + // First try to see if we can put the comment on the previous line. + // We need to make sure that we are not in the middle of a string literal or a comment. + // If so, we do not want to separate the node from its comment if we can. + // Otherwise, add an extra new line immediately before the error span. + var insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition); + var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position); + var indent = sourceFile.text.slice(lineStartPosition, startPosition); + var text = (insertAtLineStart ? "" : this.newLineCharacter) + "//" + commentText + this.newLineCharacter + indent; + this.insertText(sourceFile, token.getStart(sourceFile), text); + }; + ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { + this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); + }; + ChangeTracker.prototype.insertText = function (sourceFile, pos, text) { + this.replaceRangeWithText(sourceFile, ts.createTextRange(pos), text); + }; /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ - ChangeTracker.prototype.insertTypeAnnotation = function (sourceFile, node, type) { - var end = (ts.isFunctionLike(node) - // If no `)`, is an arrow function `x => x`, so use the end of the first parameter - ? ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile) || ts.first(node.parameters) - : node.kind !== 230 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name).end; - this.insertNodeAt(sourceFile, end, type, { prefix: ": " }); + ChangeTracker.prototype.tryInsertTypeAnnotation = function (sourceFile, node, type) { + var endNode; + if (ts.isFunctionLike(node)) { + endNode = ts.findChildOfKind(node, 20 /* CloseParenToken */, sourceFile); + if (!endNode) { + if (!ts.isArrowFunction(node)) + return; // Function missing parentheses, give up + // If no `)`, is an arrow function `x => x`, so use the end of the first parameter + endNode = ts.first(node.parameters); + } + } + else { + endNode = node.kind !== 235 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; + } + this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); }; ChangeTracker.prototype.insertTypeParameters = function (sourceFile, node, typeParameters) { // If no `(`, is an arrow function `x => x`, so use the pos of the first parameter @@ -95762,6 +102845,9 @@ var ts; else if (ts.isParameter(before)) { return {}; } + else if (ts.isStringLiteral(before) && ts.isImportDeclaration(before.parent) || ts.isNamedImports(before)) { + return { suffix: ", " }; + } return ts.Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it }; ChangeTracker.prototype.insertNodeAtConstructorStart = function (sourceFile, ctr, newStatement) { @@ -95783,7 +102869,7 @@ var ts; } }; ChangeTracker.prototype.replaceConstructorBody = function (sourceFile, ctr, statements) { - this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true), { useNonAdjustedEndPosition: true }); + this.replaceNode(sourceFile, ctr.body, ts.createBlock(statements, /*multiLine*/ true)); }; ChangeTracker.prototype.insertNodeAtEndOfScope = function (sourceFile, scope, newNode) { var pos = getAdjustedStartPosition(sourceFile, scope.getLastToken(), {}, Position.Start); @@ -95793,64 +102879,113 @@ var ts; }); }; ChangeTracker.prototype.insertNodeAtClassStart = function (sourceFile, cls, newElement) { - var firstMember = ts.firstOrUndefined(cls.members); - if (!firstMember) { - var id = ts.getNodeId(cls).toString(); - var newMembers = this.nodesInsertedAtClassStarts.get(id); - if (newMembers) { - ts.Debug.assert(newMembers.sourceFile === sourceFile && newMembers.cls === cls); - newMembers.members.push(newElement); + var clsStart = cls.getStart(sourceFile); + var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + this.formatContext.options.indentSize; + this.insertNodeAt(sourceFile, cls.members.pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtClassStartPrefixSuffix(sourceFile, cls))); + }; + ChangeTracker.prototype.getInsertNodeAtClassStartPrefixSuffix = function (sourceFile, cls) { + if (cls.members.length === 0) { + if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), cls)) { + // For `class C {\n}`, don't add the trailing "\n" + var shouldSuffix = ts.positionsAreOnSameLine.apply(void 0, getClassBraceEnds(cls, sourceFile).concat([sourceFile])); // TODO: GH#4130 remove 'as any' + return { prefix: this.newLineCharacter, suffix: shouldSuffix ? this.newLineCharacter : "" }; } else { - this.nodesInsertedAtClassStarts.set(id, { sourceFile: sourceFile, cls: cls, members: [newElement] }); + return { prefix: "", suffix: this.newLineCharacter }; } } else { - this.insertNodeBefore(sourceFile, firstMember, newElement); + return { prefix: this.newLineCharacter, suffix: "" }; } }; + ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { + var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; ChangeTracker.prototype.insertNodeAfter = function (sourceFile, after, newNode) { - if (ts.isStatementButNotDeclaration(after) || - after.kind === 151 /* PropertyDeclaration */ || - after.kind === 150 /* PropertySignature */ || - after.kind === 152 /* MethodSignature */) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode); + this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAtEndOfList = function (sourceFile, list, newNode) { + this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " }); + }; + ChangeTracker.prototype.insertNodesAfter = function (sourceFile, after, newNodes) { + var endPosition = this.insertNodeAfterWorker(sourceFile, after, ts.first(newNodes)); + this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after)); + }; + ChangeTracker.prototype.insertNodeAfterWorker = function (sourceFile, after, newNode) { + if (needSemicolonBetween(after, newNode)) { // check if previous statement ends with semicolon // if not - insert semicolon to preserve the code from changing the meaning due to ASI if (sourceFile.text.charCodeAt(after.end - 1) !== 59 /* semicolon */) { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - options: {}, - range: { pos: after.end, end: after.end }, - node: ts.createToken(25 /* SemicolonToken */) - }); + this.replaceRange(sourceFile, ts.createTextRange(after.end), ts.createToken(25 /* SemicolonToken */)); } } var endPosition = getAdjustedEndPosition(sourceFile, after, {}); - return this.replaceRange(sourceFile, { pos: endPosition, end: endPosition }, newNode, this.getInsertNodeAfterOptions(after)); + return endPosition; }; - ChangeTracker.prototype.getInsertNodeAfterOptions = function (node) { - if (ts.isClassDeclaration(node) || ts.isModuleDeclaration(node)) { - return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + ChangeTracker.prototype.getInsertNodeAfterOptions = function (sourceFile, after) { + var options = this.getInsertNodeAfterOptionsWorker(after); + return __assign({}, options, { prefix: after.end === sourceFile.end && ts.isStatement(after) ? (options.prefix ? "\n" + options.prefix : "\n") : options.prefix }); + }; + ChangeTracker.prototype.getInsertNodeAfterOptionsWorker = function (node) { + switch (node.kind) { + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + return { prefix: this.newLineCharacter, suffix: this.newLineCharacter }; + case 235 /* VariableDeclaration */: + case 9 /* StringLiteral */: + case 71 /* Identifier */: + return { prefix: ", " }; + case 273 /* PropertyAssignment */: + return { suffix: "," + this.newLineCharacter }; + case 84 /* ExportKeyword */: + return { prefix: " " }; + case 149 /* Parameter */: + return {}; + default: + ts.Debug.assert(ts.isStatement(node) || ts.isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it + return { suffix: this.newLineCharacter }; } - else if (ts.isStatement(node) || ts.isClassElement(node) || ts.isTypeElement(node)) { - return { suffix: this.newLineCharacter }; + }; + ChangeTracker.prototype.insertName = function (sourceFile, node, name) { + ts.Debug.assert(!node.name); + if (node.kind === 195 /* ArrowFunction */) { + var arrow = ts.findChildOfKind(node, 36 /* EqualsGreaterThanToken */, sourceFile); + var lparen = ts.findChildOfKind(node, 19 /* OpenParenToken */, sourceFile); + if (lparen) { + // `() => {}` --> `function f() {}` + this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [ts.createToken(89 /* FunctionKeyword */), ts.createIdentifier(name)], { joiner: " " }); + deleteNode(this, sourceFile, arrow); + } + else { + // `x => {}` -> `function f(x) {}` + this.insertText(sourceFile, ts.first(node.parameters).getStart(sourceFile), "function " + name + "("); + // Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)` + this.replaceRange(sourceFile, arrow, ts.createToken(20 /* CloseParenToken */)); + } + if (node.body.kind !== 216 /* Block */) { + // `() => 0` => `function f() { return 0; }` + this.insertNodesAt(sourceFile, node.body.getStart(sourceFile), [ts.createToken(17 /* OpenBraceToken */), ts.createToken(96 /* ReturnKeyword */)], { joiner: " ", suffix: " " }); + this.insertNodesAt(sourceFile, node.body.end, [ts.createToken(25 /* SemicolonToken */), ts.createToken(18 /* CloseBraceToken */)], { joiner: " " }); + } } - else if (ts.isVariableDeclaration(node)) { - return { prefix: ", " }; + else { + var pos = ts.findChildOfKind(node, node.kind === 194 /* FunctionExpression */ ? 89 /* FunctionKeyword */ : 75 /* ClassKeyword */, sourceFile).end; + this.insertNodeAt(sourceFile, pos, ts.createIdentifier(name), { prefix: " " }); } - else if (ts.isParameter(node)) { - return {}; - } - return ts.Debug.failBadSyntaxKind(node); // We haven't handled this kind of node yet -- add it + }; + ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { + this.insertText(sourceFile, node.getStart(sourceFile), "export "); }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. * Note that separators are part of the node in statements and class elements. */ - ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode) { - var containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); + ChangeTracker.prototype.insertNodeInListAfter = function (sourceFile, after, newNode, containingList) { + if (containingList === void 0) { containingList = ts.formatting.SmartIndenter.getContainingList(after, sourceFile); } if (!containingList) { ts.Debug.fail("node is not a list element"); return this; @@ -95863,7 +102998,7 @@ var ts; if (index !== containingList.length - 1) { // any element except the last one // use next sibling as an anchor - var nextToken = ts.getTokenAtPosition(sourceFile, after.end, /*includeJsDocComment*/ false); + var nextToken = ts.getTokenAtPosition(sourceFile, after.end); if (nextToken && isSeparator(after, nextToken)) { // for list // a, b, c @@ -95907,17 +103042,9 @@ var ts; // let insert position be the beginning of the line that contains next element 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, - options: { - prefix: prefix, - // write separator and leading trivia of the next element as suffix - suffix: "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)) - } - }); + // write separator and leading trivia of the next element as suffix + var suffix = "" + ts.tokenToString(nextToken.kind) + sourceFile.text.substring(nextToken.end, containingList[index + 1].getStart(sourceFile)); + this.replaceRange(sourceFile, ts.createTextRange(startPos, containingList[index + 1].getStart(sourceFile)), newNode, { prefix: prefix, suffix: suffix }); } } else { @@ -95949,13 +103076,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), - options: {} - }); + this.replaceRange(sourceFile, ts.createTextRange(end), ts.createToken(separator)); // use the same indentation as 'after' item var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(afterStartLinePosition, afterStart, sourceFile, this.formatContext.options); // insert element before the line break on the line that contains 'after' element @@ -95963,34 +103084,47 @@ var ts; if (insertPos !== end && ts.isLineBreak(sourceFile.text.charCodeAt(insertPos - 1))) { insertPos--; } - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: insertPos, end: insertPos }, - node: newNode, - options: { indentation: indentation, prefix: this.newLineCharacter } - }); + this.replaceRange(sourceFile, ts.createTextRange(insertPos), newNode, { indentation: indentation, prefix: this.newLineCharacter }); } else { - this.changes.push({ - kind: ChangeKind.ReplaceWithSingleNode, - sourceFile: sourceFile, - range: { pos: end, end: end }, - node: newNode, - options: { prefix: ts.tokenToString(separator) + " " } - }); + this.replaceRange(sourceFile, ts.createTextRange(end), newNode, { prefix: ts.tokenToString(separator) + " " }); } } return this; }; - ChangeTracker.prototype.finishInsertNodeAtClassStart = function () { + ChangeTracker.prototype.finishClassesWithNodesInsertedAtStart = function () { var _this = this; - this.nodesInsertedAtClassStarts.forEach(function (_a) { - var sourceFile = _a.sourceFile, cls = _a.cls, members = _a.members; - var newCls = cls.kind === 233 /* ClassDeclaration */ - ? ts.updateClassDeclaration(cls, cls.decorators, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members) - : ts.updateClassExpression(cls, cls.modifiers, cls.name, cls.typeParameters, cls.heritageClauses, members); - _this.replaceNode(sourceFile, cls, newCls, { useNonAdjustedEndPosition: true }); + this.classesWithNodesInsertedAtStart.forEach(function (cls) { + var sourceFile = cls.getSourceFile(); + var _a = getClassBraceEnds(cls, sourceFile), openBraceEnd = _a[0], closeBraceEnd = _a[1]; + // For `class C { }` remove the whitespace inside the braces. + if (ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { + _this.deleteRange(sourceFile, ts.createTextRange(openBraceEnd, closeBraceEnd - 1)); + } + }); + }; + ChangeTracker.prototype.finishDeleteDeclarations = function () { + var _this = this; + var deletedNodesInLists = new ts.NodeSet(); // Stores ids of nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. + var _loop_22 = function (sourceFile, node) { + if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { + deleteDeclaration.deleteDeclaration(this_1, deletedNodesInLists, sourceFile, node); + } + }; + var this_1 = this; + for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { + var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; + _loop_22(sourceFile, node); + } + deletedNodesInLists.forEach(function (node) { + var sourceFile = node.getSourceFile(); + var list = ts.formatting.SmartIndenter.getContainingList(node, sourceFile); + if (node !== ts.last(list)) + return; + var lastNonDeletedIndex = ts.findLastIndex(list, function (n) { return !deletedNodesInLists.has(n); }, list.length - 2); + if (lastNonDeletedIndex !== -1) { + _this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); + } }); }; /** @@ -96000,27 +103134,44 @@ var ts; * so we can only call this once and can't get the non-formatted text separately. */ ChangeTracker.prototype.getChanges = function (validate) { - this.finishInsertNodeAtClassStart(); - return changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + this.finishDeleteDeclarations(); + this.finishClassesWithNodesInsertedAtStart(); + var changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); + for (var _i = 0, _a = this.newFiles; _i < _a.length; _i++) { + var _b = _a[_i], oldFile = _b.oldFile, fileName = _b.fileName, statements = _b.statements; + changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + } + return changes; + }; + ChangeTracker.prototype.createNewFile = function (oldFile, fileName, statements) { + this.newFiles.push({ oldFile: oldFile, fileName: fileName, statements: statements }); }; return ChangeTracker; }()); - textChanges_1.ChangeTracker = ChangeTracker; + textChanges_3.ChangeTracker = ChangeTracker; + // find first non-whitespace position in the leading trivia of the node + function startPositionToDeleteNodeInList(sourceFile, node) { + return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + } + function getClassBraceEnds(cls, sourceFile) { + return [ts.findChildOfKind(cls, 17 /* OpenBraceToken */, sourceFile).end, ts.findChildOfKind(cls, 18 /* CloseBraceToken */, sourceFile).end]; + } var changesToText; (function (changesToText) { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { return ts.group(changes, function (c) { return c.sourceFile.path; }).map(function (changesInFile) { var sourceFile = changesInFile[0].sourceFile; // order changes by start position - var normalized = ts.stableSort(changesInFile, function (a, b) { return a.range.pos - b.range.pos; }); - var _loop_10 = function (i) { + // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. + var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); + var _loop_23 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. - for (var i = 0; i < normalized.length - 2; i++) { - _loop_10(i); + for (var i = 0; i < normalized.length - 1; i++) { + _loop_23(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -96029,35 +103180,44 @@ var ts; }); } changesToText.getTextChangesFromChanges = getTextChangesFromChanges; + function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { + // TODO: this emits the file, parses it back, then formats it that -- may be a less roundabout way to do this + var nonFormattedText = statements.map(function (s) { return getNonformattedText(s, oldFile, newLineCharacter).text; }).join(newLineCharacter); + var sourceFile = ts.createSourceFile(fileName, nonFormattedText, 6 /* ESNext */, /*setParentNodes*/ true); + var changes = ts.formatting.formatDocument(sourceFile, formatContext); + var text = applyChanges(nonFormattedText, changes); + return { fileName: fileName, textChanges: [ts.createTextChange(ts.createTextSpan(0, 0), text)], isNewFile: true }; + } + changesToText.newFileChanges = newFileChanges; function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { if (change.kind === ChangeKind.Remove) { return ""; } + if (change.kind === ChangeKind.Text) { + return change.text; + } var _a = change.options, options = _a === void 0 ? {} : _a, pos = change.range.pos; var format = function (n) { return getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); }; var text = change.kind === ChangeKind.ReplaceWithMultipleNodes - ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(newLineCharacter) + ? change.nodes.map(function (n) { return ts.removeSuffix(format(n), newLineCharacter); }).join(change.options.joiner || newLineCharacter) // TODO: GH#18217 : format(change.node); // strip initial indentation (spaces or tabs) if text will be inserted in the middle of the line var noIndent = (options.preserveLeadingWhitespace || options.indentation !== undefined || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (options.suffix || ""); } /** Note: this may mutate `nodeIn`. */ - function getFormattedTextOfNode(nodeIn, sourceFile, pos, options, newLineCharacter, formatContext, validate) { - var _a = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _a.node, text = _a.text; + function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { + var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; + var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; if (validate) validate(node, text); var formatOptions = formatContext.options; - var initialIndentation = options.indentation !== undefined - ? options.indentation - : (options.useIndentationFromFile !== false) - ? ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, options.prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos) - : 0; - var delta = options.delta !== undefined - ? options.delta - : ts.formatting.SmartIndenter.shouldIndentChildNode(nodeIn) - ? (formatOptions.indentSize || 0) - : 0; + var initialIndentation = indentation !== undefined + ? indentation + : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); + if (delta === undefined) { + delta = ts.formatting.SmartIndenter.shouldIndentChildNode(formatContext.options, nodeIn) ? (formatOptions.indentSize || 0) : 0; + } var file = { text: text, getLineAndCharacterOfPosition: function (pos) { return ts.getLineAndCharacterOfPosition(this, pos); } }; var changes = ts.formatting.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, formatContext); return applyChanges(text, changes); @@ -96072,17 +103232,17 @@ var ts; })(changesToText || (changesToText = {})); function applyChanges(text, changes) { for (var i = changes.length - 1; i >= 0; i--) { - var change = changes[i]; - text = "" + text.substring(0, change.span.start) + change.newText + text.substring(ts.textSpanEnd(change.span)); + var _a = changes[i], span = _a.span, newText = _a.newText; + text = "" + text.substring(0, span.start) + newText + text.substring(ts.textSpanEnd(span)); } return text; } - textChanges_1.applyChanges = applyChanges; + textChanges_3.applyChanges = applyChanges; function isTrivia(s) { return ts.skipTrivia(s, 0) === s.length; } function assignPositionsToNode(node) { - var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); + var visited = ts.visitEachChild(node, assignPositionsToNode, ts.nullTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // TODO: GH#18217 // create proxy node for non synthesized nodes var newNode = ts.nodeIsSynthesized(visited) ? visited : Object.create(visited); newNode.pos = getPos(node); @@ -96239,7 +103399,7 @@ var ts; if (!ranges) return position; // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0])) { + if (ranges.length && ranges[0].kind === 3 /* MultiLineCommentTrivia */ && ts.isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); @@ -96267,6 +103427,201 @@ var ts; } } } + function isValidLocationToAddComment(sourceFile, position) { + return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); + } + textChanges_3.isValidLocationToAddComment = isValidLocationToAddComment; + function needSemicolonBetween(a, b) { + return (ts.isPropertySignature(a) || ts.isPropertyDeclaration(a)) && ts.isClassOrTypeElement(b) && b.name.kind === 147 /* ComputedPropertyName */ + || ts.isStatementButNotDeclaration(a) && ts.isStatementButNotDeclaration(b); // TODO: only if b would start with a `(` or `[` + } + var deleteDeclaration; + (function (deleteDeclaration_1) { + function deleteDeclaration(changes, deletedNodesInLists, sourceFile, node) { + switch (node.kind) { + case 149 /* Parameter */: { + var oldFunction = node.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, // TODO: GH#18217 + oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceNode(sourceFile, oldFunction, newFunction); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + } + case 247 /* ImportDeclaration */: + deleteNode(changes, sourceFile, node, + // For first import, leave header comment in place + node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + break; + case 184 /* BindingElement */: + var pattern = node.parent; + var preserveComma = pattern.kind === 183 /* ArrayBindingPattern */ && node !== ts.last(pattern.elements); + if (preserveComma) { + deleteNode(changes, sourceFile, node); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 235 /* VariableDeclaration */: + deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node); + break; + case 148 /* TypeParameter */: { + var typeParam = node; + switch (typeParam.parent.kind) { + case 300 /* JSDocTemplateTag */: + changes.deleteRange(sourceFile, getRangeToDeleteJsDocTag(typeParam.parent, sourceFile)); + break; + case 174 /* InferType */: + // TODO: GH#25594 + break; + default: { + var typeParameters = ts.getEffectiveTypeParameterDeclarations(typeParam.parent); + if (typeParameters.length === 1) { + var _a = ts.cast(typeParameters, ts.isNodeArray), pos = _a.pos, end = _a.end; + var previousToken = ts.getTokenAtPosition(sourceFile, pos - 1); + var nextToken = ts.getTokenAtPosition(sourceFile, end); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + changes.deleteNodeRange(sourceFile, previousToken, nextToken); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + } + } + break; + } + case 251 /* ImportSpecifier */: + var namedImports = node.parent; + if (namedImports.elements.length === 1) { + deleteImportBinding(changes, sourceFile, namedImports); + } + else { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + break; + case 249 /* NamespaceImport */: + deleteImportBinding(changes, sourceFile, node); + break; + default: + if (ts.isImportClause(node.parent) && node.parent.name === node) { + deleteDefaultImport(changes, sourceFile, node.parent); + } + else if (ts.isCallLikeExpression(node.parent)) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + } + else { + deleteNode(changes, sourceFile, node, node.kind === 25 /* SemicolonToken */ ? { useNonAdjustedEndPosition: true } : undefined); + } + } + } + deleteDeclaration_1.deleteDeclaration = deleteDeclaration; + function deleteDefaultImport(changes, sourceFile, importClause) { + if (!importClause.namedBindings) { + // Delete the whole import + deleteNode(changes, sourceFile, importClause.parent); + } + else { + // import |d,| * as ns from './file' + var start = importClause.name.getStart(sourceFile); + var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end); + if (nextToken && nextToken.kind === 26 /* CommaToken */) { + // shift first non-whitespace position after comma to the start position of the node + var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); + changes.deleteRange(sourceFile, { pos: start, end: end }); + } + else { + deleteNode(changes, sourceFile, importClause.name); + } + } + } + function deleteImportBinding(changes, sourceFile, node) { + if (node.parent.name) { + // Delete named imports while preserving the default import + // import d|, * as ns| from './file' + // import d|, { a }| from './file' + var previousToken = ts.Debug.assertDefined(ts.getTokenAtPosition(sourceFile, node.pos - 1)); + changes.deleteRange(sourceFile, { pos: previousToken.getStart(sourceFile), end: node.end }); + } + else { + // Delete the entire import declaration + // |import * as ns from './file'| + // |import { a } from './file'| + var importDecl = ts.getAncestor(node, 247 /* ImportDeclaration */); + deleteNode(changes, sourceFile, importDecl); + } + } + function deleteVariableDeclaration(changes, deletedNodesInLists, sourceFile, node) { + var parent = node.parent; + if (parent.kind === 272 /* CatchClause */) { + // TODO: There's currently no unused diagnostic for this, could be a suggestion + changes.deleteNodeRange(sourceFile, ts.findChildOfKind(parent, 19 /* OpenParenToken */, sourceFile), ts.findChildOfKind(parent, 20 /* CloseParenToken */, sourceFile)); + return; + } + if (parent.declarations.length !== 1) { + deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); + return; + } + var gp = parent.parent; + switch (gp.kind) { + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: + changes.replaceNode(sourceFile, node, ts.createObjectLiteral()); + break; + case 223 /* ForStatement */: + deleteNode(changes, sourceFile, parent); + break; + case 217 /* VariableStatement */: + deleteNode(changes, sourceFile, gp); + break; + default: + ts.Debug.assertNever(gp); + } + } + function getRangeToDeleteJsDocTag(node, sourceFile) { + var parent = node.parent; + var toDelete = parent.kind === 289 /* JSDocComment */ && parent.comment === undefined && parent.tags.length === 1 ? parent : node; + return ts.createTextRangeFromNode(toDelete, sourceFile); + } + })(deleteDeclaration || (deleteDeclaration = {})); + /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ + // Exported for tests only! (TODO: improve tests to not need this) + function deleteNode(changes, sourceFile, node, options) { + if (options === void 0) { options = {}; } + var startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + var endPosition = getAdjustedEndPosition(sourceFile, node, options); + changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); + } + textChanges_3.deleteNode = deleteNode; + function deleteNodeInList(changes, deletedNodesInLists, sourceFile, node) { + var containingList = ts.Debug.assertDefined(ts.formatting.SmartIndenter.getContainingList(node, sourceFile)); + var index = ts.indexOfNode(containingList, node); + ts.Debug.assert(index !== -1); + if (containingList.length === 1) { + deleteNode(changes, sourceFile, node); + return; + } + // Note: We will only delete a comma *after* a node. This will leave a trailing comma if we delete the last node. + // That's handled in the end by `finishTrailingCommaAfterDeletingNodesInList`. + ts.Debug.assert(!deletedNodesInLists.has(node), "Deleting a node twice"); + deletedNodesInLists.add(node); + changes.deleteRange(sourceFile, { + pos: startPositionToDeleteNodeInList(sourceFile, node), + end: index === containingList.length - 1 ? getAdjustedEndPosition(sourceFile, node, {}) : startPositionToDeleteNodeInList(sourceFile, containingList[index + 1]), + }); + } })(textChanges = ts.textChanges || (ts.textChanges = {})); })(ts || (ts = {})); /* @internal */ @@ -96274,17 +103629,28 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var codeFixRegistrations = []; + var errorCodeToFixes = ts.createMultiMap(); var fixIdToRegistration = ts.createMap(); + function diagnosticToString(diag) { + return ts.isArray(diag) + ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) + : ts.getLocaleSpecificMessage(diag); + } + function createCodeFixActionNoFixId(fixName, changes, description) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); + } + codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { + return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); + } + codefix.createCodeFixAction = createCodeFixAction; + function createCodeFixActionWorker(fixName, description, changes, fixId, fixAllDescription, command) { + return { fixName: fixName, description: description, changes: changes, fixId: fixId, fixAllDescription: fixAllDescription, commands: command ? [command] : undefined }; + } function registerCodeFix(reg) { for (var _i = 0, _a = reg.errorCodes; _i < _a.length; _i++) { var error = _a[_i]; - var registrations = codeFixRegistrations[error]; - if (!registrations) { - registrations = []; - codeFixRegistrations[error] = registrations; - } - registrations.push(reg); + errorCodeToFixes.add(String(error), reg); } if (reg.fixIds) { for (var _b = 0, _c = reg.fixIds; _b < _c.length; _b++) { @@ -96296,27 +103662,11 @@ var ts; } codefix.registerCodeFix = registerCodeFix; function getSupportedErrorCodes() { - return Object.keys(codeFixRegistrations); + return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; function getFixes(context) { - var fixes = codeFixRegistrations[context.errorCode]; - var allActions = []; - ts.forEach(fixes, function (f) { - var actions = f.getCodeActions(context); - if (actions && actions.length > 0) { - for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) { - var action = actions_1[_i]; - if (action === undefined) { - context.host.log("Action for error code " + context.errorCode + " added an invalid action entry; please log a bug"); - } - else { - allActions.push(action); - } - } - } - }); - return allActions; + return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -96327,27 +103677,27 @@ var ts; function createCombinedCodeActions(changes, commands) { return { changes: changes, commands: commands }; } + codefix.createCombinedCodeActions = createCombinedCodeActions; function createFileTextChanges(fileName, textChanges) { return { fileName: fileName, textChanges: textChanges }; } codefix.createFileTextChanges = createFileTextChanges; function codeFixAll(context, errorCodes, use) { var commands = []; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); - }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return eachDiagnostic(context, errorCodes, function (diag) { return use(t, diag, commands); }); }); return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile).concat(ts.computeSuggestionDiagnostics(sourceFile, program)); _i < _b.length; _i++) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { var diag = _b[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } + codefix.eachDiagnostic = eachDiagnostic; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -96375,10 +103725,11 @@ var ts; } refactor_1.getEditsForRefactor = getEditsForRefactor; })(refactor = ts.refactor || (ts.refactor = {})); - function getRefactorContextLength(context) { - return context.endPosition === undefined ? 0 : context.endPosition - context.startPosition; + function getRefactorContextSpan(_a) { + var startPosition = _a.startPosition, endPosition = _a.endPosition; + return ts.createTextSpanFromBounds(startPosition, endPosition === undefined ? startPosition : endPosition); } - ts.getRefactorContextLength = getRefactorContextLength; + ts.getRefactorContextSpan = getRefactorContextSpan; })(ts || (ts = {})); /* @internal */ var ts; @@ -96391,13 +103742,13 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Call_decorator_expression), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, }); function makeChange(changeTracker, sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var decorator = ts.findAncestor(token, ts.isDecorator); ts.Debug.assert(!!decorator, "Expected position to be owned by a decorator."); var replacement = ts.createCall(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); @@ -96418,9 +103769,8 @@ var ts; var decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Annotate_with_type_from_JSDoc); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, decl); }); - return [{ description: description, changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Annotate_with_type_from_JSDoc, fixId, ts.Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -96430,7 +103780,7 @@ var ts; }); }, }); function getDeclaration(file, pos) { - var name = ts.getTokenAtPosition(file, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(file, pos); // For an arrow function with no name, 'name' lands on the first parameter. return ts.tryCast(ts.isParameter(name.parent) ? name.parent.parent : name.parent, parameterShouldGetTypeFromJSDoc); } @@ -96447,7 +103797,7 @@ var ts; if (ts.isFunctionLikeDeclaration(decl) && (ts.getJSDocReturnType(decl) || decl.parameters.some(function (p) { return !!ts.getJSDocType(p); }))) { if (!decl.typeParameters) { var typeParameters = ts.getJSDocTypeParameterDeclarations(decl); - if (typeParameters) + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } var needParens = ts.isArrowFunction(decl) && !ts.findChildOfKind(decl, 19 /* OpenParenToken */, sourceFile); @@ -96458,7 +103808,7 @@ var ts; if (!param.type) { var paramType = ts.getJSDocType(param); if (paramType) - changes.insertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); + changes.tryInsertTypeAnnotation(sourceFile, param, transformJSDocType(paramType)); } } if (needParens) @@ -96466,40 +103816,40 @@ var ts; if (!decl.type) { var returnType = ts.getJSDocReturnType(decl); if (returnType) - changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(returnType)); } } else { var jsdocType = ts.Debug.assertDefined(ts.getJSDocType(decl)); // If not defined, shouldn't have been an error to fix ts.Debug.assert(!decl.type); // If defined, shouldn't have been an error to fix. - changes.insertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); + changes.tryInsertTypeAnnotation(sourceFile, decl, transformJSDocType(jsdocType)); } } function isDeclarationWithType(node) { return ts.isFunctionLikeDeclaration(node) || - node.kind === 230 /* VariableDeclaration */ || - node.kind === 150 /* PropertySignature */ || - node.kind === 151 /* PropertyDeclaration */; + node.kind === 235 /* VariableDeclaration */ || + node.kind === 151 /* PropertySignature */ || + node.kind === 152 /* PropertyDeclaration */; } function transformJSDocType(node) { switch (node.kind) { - case 275 /* JSDocAllType */: - case 276 /* JSDocUnknownType */: + case 282 /* JSDocAllType */: + case 283 /* JSDocUnknownType */: return ts.createTypeReferenceNode("any", ts.emptyArray); - case 279 /* JSDocOptionalType */: + case 286 /* JSDocOptionalType */: return transformJSDocOptionalType(node); - case 278 /* JSDocNonNullableType */: + case 285 /* JSDocNonNullableType */: return transformJSDocType(node.type); - case 277 /* JSDocNullableType */: + case 284 /* JSDocNullableType */: return transformJSDocNullableType(node); - case 281 /* JSDocVariadicType */: + case 288 /* JSDocVariadicType */: return transformJSDocVariadicType(node); - case 280 /* JSDocFunctionType */: + case 287 /* JSDocFunctionType */: return transformJSDocFunctionType(node); - case 161 /* TypeReference */: + case 162 /* TypeReference */: return transformJSDocTypeReference(node); default: - var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); + var visited = ts.visitEachChild(node, transformJSDocType, /*context*/ undefined); // TODO: GH#18217 ts.setEmitFlags(visited, 1 /* SingleLine */); return visited; } @@ -96518,7 +103868,7 @@ var ts; } function transformJSDocParameter(node) { var index = node.parent.parameters.indexOf(node); - var isRest = node.type.kind === 281 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; + var isRest = node.type.kind === 288 /* JSDocVariadicType */ && index === node.parent.parameters.length - 1; // TODO: GH#18217 var name = node.name || (isRest ? "rest" : "arg" + index); var dotdotdot = isRest ? ts.createToken(24 /* DotDotDotToken */) : node.dotDotDotToken; return ts.createParameter(node.decorators, node.modifiers, dotdotdot, name, node.questionToken, ts.visitNode(node.type, transformJSDocType), node.initializer); @@ -96578,15 +103928,13 @@ var ts; errorCodes: errorCodes, getCodeActions: function (context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program.getTypeChecker()); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_function_to_an_ES2015_class), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_function_to_an_ES2015_class, fixId, ts.Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, err) { return doChange(changes, err.file, err.start, context.program.getTypeChecker()); }); }, }); function doChange(changes, sourceFile, position, checker) { - var deletedNodes = []; - var deletes = []; - var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false)); + var ctorSymbol = checker.getSymbolAtLocation(ts.getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { // Bad input return undefined; @@ -96595,46 +103943,29 @@ var ts; var precedingNode; var newClassDeclaration; switch (ctorDeclaration.kind) { - case 232 /* FunctionDeclaration */: + case 237 /* FunctionDeclaration */: precedingNode = ctorDeclaration; - deleteNode(ctorDeclaration); + changes.delete(sourceFile, ctorDeclaration); newClassDeclaration = createClassFromFunctionDeclaration(ctorDeclaration); break; - case 230 /* VariableDeclaration */: + case 235 /* VariableDeclaration */: precedingNode = ctorDeclaration.parent.parent; + newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); if (ctorDeclaration.parent.declarations.length === 1) { - deleteNode(precedingNode); + ts.copyComments(precedingNode, newClassDeclaration, sourceFile); // TODO: GH#18217 + changes.delete(sourceFile, precedingNode); } else { - deleteNode(ctorDeclaration, /*inList*/ true); + changes.delete(sourceFile, ctorDeclaration); } - newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration); break; } if (!newClassDeclaration) { return undefined; } - copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + ts.copyComments(ctorDeclaration, newClassDeclaration, sourceFile); // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode, newClassDeclaration); - for (var _i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) { - var deleteCallback = deletes_1[_i]; - deleteCallback(); - } - 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 changes.deleteNodeInList(sourceFile, node); }); - } - else { - deletes.push(function () { return changes.deleteNode(sourceFile, node); }); - } - } function createClassElementsFromSymbol(symbol) { var memberElements = []; // all instance members are stored in the "member" array of symbol @@ -96662,8 +103993,8 @@ var ts; return ts.isFunctionLike(source); } function createClassElement(symbol, modifiers) { - // both properties and methods are bound as property symbols - if (!(symbol.flags & 4 /* Property */)) { + // Right now the only thing we can convert are function expressions, which are marked as methods + if (!(symbol.flags & 8192 /* Method */)) { return; } var memberDeclaration = symbol.valueDeclaration; @@ -96672,28 +104003,28 @@ var ts; 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 === 214 /* ExpressionStatement */ + var nodeToDelete = assignmentBinaryExpression.parent && assignmentBinaryExpression.parent.kind === 219 /* ExpressionStatement */ ? assignmentBinaryExpression.parent : assignmentBinaryExpression; - deleteNode(nodeToDelete); + changes.delete(sourceFile, nodeToDelete); if (!assignmentBinaryExpression.right) { return ts.createProperty([], modifiers, symbol.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); } switch (assignmentBinaryExpression.right.kind) { - case 190 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var functionExpression = assignmentBinaryExpression.right; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(functionExpression, 120 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } - case 191 /* ArrowFunction */: { + case 195 /* ArrowFunction */: { var arrowFunction = assignmentBinaryExpression.right; var arrowFunctionBody = arrowFunction.body; var bodyBlock = void 0; // case 1: () => { return [1,2,3] } - if (arrowFunctionBody.kind === 211 /* Block */) { + if (arrowFunctionBody.kind === 216 /* Block */) { bodyBlock = arrowFunctionBody; } // case 2: () => [1,2,3] @@ -96703,7 +104034,7 @@ var ts; var fullModifiers = ts.concatenate(modifiers, getModifierKindFromSource(arrowFunction, 120 /* AsyncKeyword */)); var method = ts.createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method, sourceFile); + ts.copyComments(assignmentBinaryExpression, method, sourceFile); return method; } default: { @@ -96713,7 +104044,7 @@ var ts; } var prop = ts.createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + ts.copyComments(assignmentBinaryExpression.parent, prop, sourceFile); return prop; } } @@ -96721,13 +104052,13 @@ var ts; } function createClassFromVariableDeclaration(node) { var initializer = node.initializer; - if (!initializer || initializer.kind !== 190 /* FunctionExpression */) { + if (!initializer || initializer.kind !== 194 /* FunctionExpression */) { return undefined; } if (node.name.kind !== 71 /* Identifier */) { return undefined; } - var memberElements = createClassElementsFromSymbol(initializer.symbol); + var memberElements = createClassElementsFromSymbol(node.symbol); if (initializer.body) { memberElements.unshift(ts.createConstructor(/*decorators*/ undefined, /*modifiers*/ undefined, initializer.parameters, initializer.body)); } @@ -96749,21 +104080,6 @@ var ts; return cls; } } - function copyComments(sourceNode, targetNode, sourceFile) { - 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 getModifierKindFromSource(source, kind) { return ts.filter(source.modifiers, function (modifier) { return modifier.kind === kind; }); } @@ -96777,54 +104093,49 @@ var ts; codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module.code], getCodeActions: function (context) { - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); - var sourceFile = context.sourceFile, program = context.program; + var sourceFile = context.sourceFile, program = context.program, preferences = context.preferences; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { - var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target); + var moduleExportsChangedToDefault = convertFileToEs6Module(sourceFile, program.getTypeChecker(), changes, program.getCompilerOptions().target, ts.getQuotePreference(sourceFile, preferences)); if (moduleExportsChangedToDefault) { for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var importingFile = _a[_i]; - fixImportOfModuleExports(importingFile, sourceFile, changes); + fixImportOfModuleExports(importingFile, sourceFile, changes, ts.getQuotePreference(importingFile, preferences)); } } }); // No support for fix-all since this applies to the whole file at once anyway. - return [{ description: description, changes: changes, fixId: undefined }]; + return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); - function fixImportOfModuleExports(importingFile, exportingFile, changes) { + function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { for (var _i = 0, _a = importingFile.imports; _i < _a.length; _i++) { var moduleSpecifier = _a[_i]; var imported = ts.getResolvedModule(importingFile, moduleSpecifier.text); if (!imported || imported.resolvedFileName !== exportingFile.fileName) { continue; } - var parent = moduleSpecifier.parent; - switch (parent.kind) { - case 252 /* ExternalModuleReference */: { - var importEq = parent.parent; - changes.replaceNode(importingFile, importEq, makeImport(importEq.name, /*namedImports*/ undefined, moduleSpecifier.text)); + var importNode = ts.importFromModuleSpecifier(moduleSpecifier); + switch (importNode.kind) { + case 246 /* ImportEqualsDeclaration */: + changes.replaceNode(importingFile, importNode, ts.makeImport(importNode.name, /*namedImports*/ undefined, moduleSpecifier, quotePreference)); break; - } - case 185 /* CallExpression */: { - var call = parent; - if (ts.isRequireCall(call, /*checkArgumentIsStringLiteral*/ false)) { - changes.replaceNode(importingFile, parent, ts.createPropertyAccess(ts.getSynthesizedDeepClone(call), "default")); + case 189 /* CallExpression */: + if (ts.isRequireCall(importNode, /*checkArgumentIsStringLiteralLike*/ false)) { + changes.replaceNode(importingFile, importNode, ts.createPropertyAccess(ts.getSynthesizedDeepClone(importNode), "default")); } break; - } } } } /** @returns Whether we converted a `module.exports =` to a default export. */ - function convertFileToEs6Module(sourceFile, checker, changes, target) { + function convertFileToEs6Module(sourceFile, checker, changes, target, quotePreference) { var identifiers = { original: collectFreeIdentifiers(sourceFile), additional: ts.createMap() }; var exports = collectExportRenames(sourceFile, checker, identifiers); convertExportsAccesses(sourceFile, exports, changes); var moduleExportsChangedToDefault = false; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports); + var moduleExportsChanged = convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference); moduleExportsChangedToDefault = moduleExportsChangedToDefault || moduleExportsChanged; } return moduleExportsChangedToDefault; @@ -96859,24 +104170,24 @@ var ts; node.forEachChild(recur); }); } - function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports) { + function convertStatement(sourceFile, statement, checker, changes, identifiers, target, exports, quotePreference) { switch (statement.kind) { - case 212 /* VariableStatement */: - convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target); + case 217 /* VariableStatement */: + convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference); return false; - case 214 /* ExpressionStatement */: { + case 219 /* ExpressionStatement */: { var expression = statement.expression; switch (expression.kind) { - case 185 /* CallExpression */: { - if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteral*/ true)) { + case 189 /* CallExpression */: { + if (ts.isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true)) { // For side-effecting require() call, just make a side-effecting import. - changes.replaceNode(sourceFile, statement, makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0].text)); + changes.replaceNode(sourceFile, statement, ts.makeImport(/*name*/ undefined, /*namedImports*/ undefined, expression.arguments[0], quotePreference)); } return false; } - case 198 /* BinaryExpression */: { - var _a = expression, left = _a.left, operatorToken = _a.operatorToken, right = _a.right; - return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, statement, left, right, changes, exports); + case 202 /* BinaryExpression */: { + var operatorToken = expression.operatorToken; + return operatorToken.kind === 58 /* EqualsToken */ && convertAssignment(sourceFile, checker, expression, changes, exports); } } } @@ -96885,28 +104196,28 @@ var ts; return false; } } - function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target) { + function convertVariableStatement(sourceFile, statement, changes, checker, identifiers, target, quotePreference) { var declarationList = statement.declarationList; var foundImport = false; var newNodes = ts.flatMap(declarationList.declarations, function (decl) { var name = decl.name, initializer = decl.initializer; - if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { - // `const alias = module.exports;` can be removed. - foundImport = true; - return []; - } - if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertSingleImport(sourceFile, name, initializer.arguments[0].text, changes, checker, identifiers, target); - } - else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteral*/ true)) { - foundImport = true; - return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0].text, identifiers); - } - else { - // Move it out to its own variable statement. - return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); + if (initializer) { + if (ts.isExportsOrModuleExportsOrAlias(sourceFile, initializer)) { + // `const alias = module.exports;` can be removed. + foundImport = true; + return []; + } + else if (ts.isRequireCall(initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertSingleImport(sourceFile, name, initializer.arguments[0], changes, checker, identifiers, target, quotePreference); + } + else if (ts.isPropertyAccessExpression(initializer) && ts.isRequireCall(initializer.expression, /*checkArgumentIsStringLiteralLike*/ true)) { + foundImport = true; + return convertPropertyAccessImport(name, initializer.name.text, initializer.expression.arguments[0], identifiers, quotePreference); + } } + // Move it out to its own variable statement. (This will not be used if `!foundImport`) + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([decl], declarationList.flags)); }); if (foundImport) { // useNonAdjustedEndPosition to ensure we don't eat the newline after the statement. @@ -96914,74 +104225,79 @@ var ts; } } /** Converts `const name = require("moduleSpecifier").propertyName` */ - function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers) { + function convertPropertyAccessImport(name, propertyName, moduleSpecifier, identifiers, quotePreference) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: { + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: { // `const [a, b] = require("c").d` --> `import { d } from "c"; const [a, b] = d;` var tmp = makeUniqueName(propertyName, identifiers); return [ - makeSingleImport(tmp, propertyName, moduleSpecifier), + makeSingleImport(tmp, propertyName, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, name, ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: // `const a = require("b").c` --> `import { c as a } from "./b"; - return [makeSingleImport(name.text, propertyName, moduleSpecifier)]; + return [makeSingleImport(name.text, propertyName, moduleSpecifier, quotePreference)]; default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } - function convertAssignment(sourceFile, checker, statement, left, right, changes, exports) { + function convertAssignment(sourceFile, checker, assignment, changes, exports) { + var left = assignment.left, right = assignment.right; if (!ts.isPropertyAccessExpression(left)) { return false; } if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left)) { if (ts.isExportsOrModuleExportsOrAlias(sourceFile, right)) { // `const alias = module.exports;` or `module.exports = alias;` can be removed. - changes.deleteNode(sourceFile, statement); + changes.delete(sourceFile, assignment.parent); } else { - var newNodes = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) : undefined; - var changedToDefaultExport = false; - if (!newNodes) { - (_a = convertModuleExportsToExportDefault(right, checker), newNodes = _a[0], changedToDefaultExport = _a[1]); + var replacement = ts.isObjectLiteralExpression(right) ? tryChangeModuleExportsObject(right) + : ts.isRequireCall(right, /*checkArgumentIsStringLiteralLike*/ true) ? convertReExportAll(right.arguments[0], checker) + : undefined; + if (replacement) { + changes.replaceNodeWithNodes(sourceFile, assignment.parent, replacement[0]); + return replacement[1]; + } + else { + changes.replaceRangeWithText(sourceFile, ts.createTextRange(left.getStart(sourceFile), right.pos), "export default"); + return true; } - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); - return changedToDefaultExport; } } else if (ts.isExportsOrModuleExportsOrAlias(sourceFile, left.expression)) { - convertNamedExport(sourceFile, statement, left.name, right, changes, exports); + convertNamedExport(sourceFile, assignment, changes, exports); } return false; - var _a; } /** * Convert `module.exports = { ... }` to individual exports.. * We can't always do this if the module has interesting members -- then it will be a default export instead. */ function tryChangeModuleExportsObject(object) { - return ts.mapAllOrFail(object.properties, function (prop) { + var statements = ts.mapAllOrFail(object.properties, function (prop) { switch (prop.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. - case 269 /* ShorthandPropertyAssignment */: - case 270 /* SpreadAssignment */: + case 274 /* ShorthandPropertyAssignment */: + case 275 /* SpreadAssignment */: return undefined; - case 268 /* PropertyAssignment */: - return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals(prop.name.text, prop.initializer); - case 153 /* MethodDeclaration */: + case 273 /* PropertyAssignment */: + return !ts.isIdentifier(prop.name) ? undefined : convertExportsDotXEquals_replaceNode(prop.name.text, prop.initializer); + case 154 /* MethodDeclaration */: return !ts.isIdentifier(prop.name) ? undefined : functionExpressionToDeclaration(prop.name.text, [ts.createToken(84 /* ExportKeyword */)], prop); default: ts.Debug.assertNever(prop); } }); + return statements && [statements, false]; } - function convertNamedExport(sourceFile, statement, propertyName, right, changes, exports) { + function convertNamedExport(sourceFile, assignment, changes, exports) { // If "originalKeywordKind" was set, this is e.g. `exports. - var text = propertyName.text; + var text = assignment.left.name.text; var rename = exports.get(text); if (rename !== undefined) { /* @@ -96989,37 +104305,13 @@ var ts; export { _class as class }; */ var newNodes = [ - makeConst(/*modifiers*/ undefined, rename, right), + makeConst(/*modifiers*/ undefined, rename, assignment.right), makeExportDeclaration([ts.createExportSpecifier(rename, text)]), ]; - changes.replaceNodeWithNodes(sourceFile, statement, newNodes); + changes.replaceNodeWithNodes(sourceFile, assignment.parent, newNodes); } else { - changes.replaceNode(sourceFile, statement, convertExportsDotXEquals(text, right), { useNonAdjustedEndPosition: true }); - } - } - function convertModuleExportsToExportDefault(exported, checker) { - var modifiers = [ts.createToken(84 /* ExportKeyword */), ts.createToken(79 /* DefaultKeyword */)]; - switch (exported.kind) { - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: { - // `module.exports = function f() {}` --> `export default function f() {}` - var fn = exported; - return [[functionExpressionToDeclaration(fn.name && fn.name.text, modifiers, fn)], true]; - } - case 203 /* ClassExpression */: { - // `module.exports = class C {}` --> `export default class C {}` - var cls = exported; - return [[classExpressionToDeclaration(cls.name && cls.name.text, modifiers, cls)], true]; - } - case 185 /* CallExpression */: - if (ts.isRequireCall(exported, /*checkArgumentIsStringLiteral*/ true)) { - return convertReExportAll(exported.arguments[0], checker); - } - // falls through - default: - // `module.exports = 0;` --> `export default 0;` - return [[ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, exported)], true]; + convertExportsPropertyAssignment(assignment, sourceFile, changes); } } function convertReExportAll(reExported, checker) { @@ -97040,10 +104332,28 @@ var ts; function reExportDefault(moduleSpecifier) { return makeExportDeclaration([ts.createExportSpecifier(/*propertyName*/ undefined, "default")], moduleSpecifier); } - function convertExportsDotXEquals(name, exported) { + function convertExportsPropertyAssignment(_a, sourceFile, changes) { + var left = _a.left, right = _a.right, parent = _a.parent; + var name = left.name.text; + if ((ts.isFunctionExpression(right) || ts.isArrowFunction(right) || ts.isClassExpression(right)) && (!right.name || right.name.text === name)) { + // `exports.f = function() {}` -> `export function f() {}` -- Replace `exports.f = ` with `export `, and insert the name after `function`. + changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, ts.createToken(84 /* ExportKeyword */), { suffix: " " }); + if (!right.name) + changes.insertName(sourceFile, right, name); + var semi = ts.findChildOfKind(parent, 25 /* SemicolonToken */, sourceFile); + if (semi) + changes.delete(sourceFile, semi); + } + else { + // `exports.f = function g() {}` -> `export const f = function g() {}` -- just replace `exports.` with `export const ` + changes.replaceNodeRangeWithNodes(sourceFile, left.expression, ts.findChildOfKind(left, 23 /* DotToken */, sourceFile), [ts.createToken(84 /* ExportKeyword */), ts.createToken(76 /* ConstKeyword */)], { joiner: " ", suffix: " " }); + } + } + // TODO: GH#22492 this will cause an error if a change has been made inside the body of the node. + function convertExportsDotXEquals_replaceNode(name, exported) { var modifiers = [ts.createToken(84 /* ExportKeyword */)]; switch (exported.kind) { - case 190 /* FunctionExpression */: { + case 194 /* FunctionExpression */: { var expressionName = exported.name; if (expressionName && expressionName.text !== name) { // `exports.f = function g() {}` -> `export const f = function g() {}` @@ -97051,10 +104361,10 @@ var ts; } } // falls through - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: // `exports.f = function() {}` --> `export function f() {}` return functionExpressionToDeclaration(name, modifiers, exported); - case 203 /* ClassExpression */: + case 207 /* ClassExpression */: // `exports.C = class {}` --> `export class C {}` return classExpressionToDeclaration(name, modifiers, exported); default: @@ -97062,7 +104372,7 @@ var ts; } function exportConst() { // `exports.x = 0;` --> `export const x = 0;` - return makeConst(modifiers, ts.createIdentifier(name), exported); + return makeConst(modifiers, ts.createIdentifier(name), exported); // TODO: GH#18217 } } /** @@ -97070,41 +104380,41 @@ var ts; * Returns nodes that will replace the variable declaration for the commonjs import. * May also make use `changes` to remove qualifiers at the use sites of imports, to change `mod.x` to `x`. */ - function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target) { + function convertSingleImport(file, name, moduleSpecifier, changes, checker, identifiers, target, quotePreference) { switch (name.kind) { - case 178 /* ObjectBindingPattern */: { + case 182 /* ObjectBindingPattern */: { var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); - }); + }); // tslint:disable-line no-unnecessary-type-assertion (TODO: GH#18217) if (importSpecifiers) { - return [makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier)]; + return [ts.makeImport(/*name*/ undefined, importSpecifiers, moduleSpecifier, quotePreference)]; } } // falls through -- object destructuring has an interesting pattern and must be a variable declaration - case 179 /* ArrayBindingPattern */: { + case 183 /* ArrayBindingPattern */: { /* import x from "x"; const [a, b, c] = x; */ - var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + var tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return [ - makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), + ts.makeImport(ts.createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier, quotePreference), makeConst(/*modifiers*/ undefined, ts.getSynthesizedDeepClone(name), ts.createIdentifier(tmp)), ]; } case 71 /* Identifier */: - return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers); + return convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference); default: - ts.Debug.assertNever(name); + return ts.Debug.assertNever(name); } } /** * Convert `import x = require("x").` * Also converts uses like `x.y()` to `y()` and uses a named import. */ - function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers) { + function convertSingleIdentifierImport(file, name, moduleSpecifier, changes, checker, identifiers, quotePreference) { var nameSymbol = checker.getSymbolAtLocation(name); // Maps from module property name to name actually used. (The same if there isn't shadowing.) var namedBindingsNames = ts.createMap(); @@ -97139,7 +104449,7 @@ var ts; // If it was unused, ensure that we at least import *something*. needDefaultImport = true; } - return [makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier)]; + return [ts.makeImport(needDefaultImport ? ts.getSynthesizedDeepClone(name) : undefined, namedBindings, moduleSpecifier, quotePreference)]; } // Identifiers helpers function makeUniqueName(name, identifiers) { @@ -97151,20 +104461,26 @@ var ts; } function collectFreeIdentifiers(file) { var map = ts.createMultiMap(); - file.forEachChild(function recur(node) { - if (ts.isIdentifier(node) && isFreeIdentifier(node)) { - map.add(node.text, node); - } - node.forEachChild(recur); - }); + forEachFreeIdentifier(file, function (id) { return map.add(id.text, id); }); return map; } + /** + * A free identifier is an identifier that can be accessed through name lookup as a local variable. + * In the expression `x.y`, `x` is a free identifier, but `y` is not. + */ + function forEachFreeIdentifier(node, cb) { + if (ts.isIdentifier(node) && isFreeIdentifier(node)) + cb(node); + node.forEachChild(function (child) { return forEachFreeIdentifier(child, cb); }); + } function isFreeIdentifier(node) { var parent = node.parent; switch (parent.kind) { - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: return parent.name !== node; - case 180 /* BindingElement */: + case 184 /* BindingElement */: + return parent.propertyName !== node; + case 251 /* ImportSpecifier */: return parent.propertyName !== node; default: return true; @@ -97179,19 +104495,11 @@ var ts; return ts.createClassDeclaration(ts.getSynthesizedDeepClones(cls.decorators), // TODO: GH#19915 Don't think this is even legal. ts.concatenate(additionalModifiers, ts.getSynthesizedDeepClones(cls.modifiers)), name, ts.getSynthesizedDeepClones(cls.typeParameters), ts.getSynthesizedDeepClones(cls.heritageClauses), ts.getSynthesizedDeepClones(cls.members)); } - function makeSingleImport(localName, propertyName, moduleSpecifier) { + function makeSingleImport(localName, propertyName, moduleSpecifier, quotePreference) { return propertyName === "default" - ? makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier) - : makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier); + ? ts.makeImport(ts.createIdentifier(localName), /*namedImports*/ undefined, moduleSpecifier, quotePreference) + : ts.makeImport(/*name*/ undefined, [makeImportSpecifier(propertyName, localName)], moduleSpecifier, quotePreference); } - function makeImport(name, namedImports, moduleSpecifier) { - return makeImportDeclaration(name, namedImports, ts.createLiteral(moduleSpecifier)); - } - function makeImportDeclaration(name, namedImports, moduleSpecifier) { - var importClause = (name || namedImports) && ts.createImportClause(name, namedImports && ts.createNamedImports(namedImports)); - return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, importClause, moduleSpecifier); - } - codefix.makeImportDeclaration = makeImportDeclaration; function makeImportSpecifier(propertyName, name) { return ts.createImportSpecifier(propertyName !== undefined && propertyName !== name ? ts.createIdentifier(propertyName) : undefined, ts.createIdentifier(name)); } @@ -97219,8 +104527,8 @@ var ts; if (!qualifiedName) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, qualifiedName); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Rewrite_as_the_indexed_access_type_0), [qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"]); - return [{ description: description, changes: changes, fixId: fixId }]; + var newText = qualifiedName.left.text + "[\"" + qualifiedName.right.text + "\"]"; + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId, ts.Diagnostics.Rewrite_all_as_indexed_access_types)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97231,7 +104539,7 @@ var ts; }); }, }); function getQualifiedName(sourceFile, pos) { - var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ true), ts.isQualifiedName); + var qualifiedName = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), ts.isQualifiedName); ts.Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return ts.isIdentifier(qualifiedName.left) ? qualifiedName : undefined; } @@ -97257,11 +104565,8 @@ var ts; var classDeclaration = getClass(sourceFile, span.start); var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); - return { description: description, changes: changes, fixId: fixId }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, fixIds: [fixId], @@ -97272,29 +104577,33 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes); + addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); }, }); function getClass(sourceFile, pos) { - return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false))); + return ts.Debug.assertDefined(ts.getContainingClass(ts.getTokenAtPosition(sourceFile, pos))); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker) { + function symbolPointsToNonPrivateMember(symbol) { + return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); + } + function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var implementedType = checker.getTypeAtLocation(implementedTypeNode); var implementedTypeSymbols = checker.getPropertiesOfType(implementedType); - var nonPrivateMembers = implementedTypeSymbols.filter(function (symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); }); + var nonPrivateAndNotExistedInHeritageClauseMembers = implementedTypeSymbols.filter(ts.and(symbolPointsToNonPrivateMember, function (symbol) { return !maybeHeritageClauseSymbol.has(symbol.escapedName); })); var classType = checker.getTypeAtLocation(classDeclaration); - if (!checker.getIndexTypeOfType(classType, 1 /* Number */)) { + if (!classType.getNumberIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 1 /* Number */); } - if (!checker.getIndexTypeOfType(classType, 0 /* String */)) { + if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { @@ -97302,6 +104611,14 @@ var ts; } } } + function getHeritageClauseSymbolTable(classDeclaration, checker) { + var heritageClauseNode = ts.getEffectiveBaseTypeNode(classDeclaration); + if (!heritageClauseNode) + return ts.createSymbolTable(); + var heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); + var heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); + return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -97309,6 +104626,594 @@ var ts; (function (ts) { var codefix; (function (codefix) { + codefix.importFixId = "fixMissingImport"; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Cannot_find_namespace_0.code, + ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, + ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var errorCode = context.errorCode, preferences = context.preferences, sourceFile = context.sourceFile, span = context.span; + var info = getFixesInfo(context, errorCode, span.start); + if (!info) + return undefined; + var fixes = info.fixes, symbolName = info.symbolName; + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); + }, + fixIds: [codefix.importFixId], + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, preferences = context.preferences; + // Namespace fixes don't conflict, so just build a list. + var addToNamespace = []; + // Keys are import clause node IDs. + var addToExisting = ts.createMap(); + // Keys are module specifiers. + var newImports = ts.createMap(); + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getFixesInfo(context, diag.code, diag.start); + if (!info || !info.fixes.length) + return; + var fixes = info.fixes, symbolName = info.symbolName; + var fix = ts.first(fixes); + switch (fix.kind) { + case 0 /* UseNamespace */: + addToNamespace.push(fix); + break; + case 1 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + var key = String(ts.getNodeId(importClause)); + var entry = addToExisting.get(key); + if (!entry) { + addToExisting.set(key, entry = { importClause: importClause, defaultImport: undefined, namedImports: [] }); + } + if (importKind === 0 /* Named */) { + ts.pushIfUnique(entry.namedImports, symbolName); + } + else { + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + } + break; + } + case 2 /* AddNew */: { + var moduleSpecifier = fix.moduleSpecifier, importKind = fix.importKind; + var entry = newImports.get(moduleSpecifier); + if (!entry) { + newImports.set(moduleSpecifier, entry = { defaultImport: undefined, namedImports: [], namespaceLikeImport: undefined }); + } + switch (importKind) { + case 1 /* Default */: + ts.Debug.assert(entry.defaultImport === undefined || entry.defaultImport === symbolName); + entry.defaultImport = symbolName; + break; + case 0 /* Named */: + ts.pushIfUnique(entry.namedImports, symbolName); + break; + case 3 /* Equals */: + case 2 /* Namespace */: + ts.Debug.assert(entry.namespaceLikeImport === undefined || entry.namespaceLikeImport.name === symbolName); + entry.namespaceLikeImport = { importKind: importKind, name: symbolName }; + break; + } + break; + } + default: + ts.Debug.assertNever(fix); + } + }); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + for (var _i = 0, addToNamespace_1 = addToNamespace; _i < addToNamespace_1.length; _i++) { + var fix = addToNamespace_1[_i]; + addNamespaceQualifier(changes, sourceFile, fix); + } + addToExisting.forEach(function (_a) { + var importClause = _a.importClause, defaultImport = _a.defaultImport, namedImports = _a.namedImports; + doAddExistingFix(changes, sourceFile, importClause, defaultImport, namedImports); + }); + var quotePreference = ts.getQuotePreference(sourceFile, preferences); + newImports.forEach(function (imports, moduleSpecifier) { + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, imports); + }); + })); + }, + }); + // Sorted with the preferred fix coming first. + var ImportFixKind; + (function (ImportFixKind) { + ImportFixKind[ImportFixKind["UseNamespace"] = 0] = "UseNamespace"; + ImportFixKind[ImportFixKind["AddToExisting"] = 1] = "AddToExisting"; + ImportFixKind[ImportFixKind["AddNew"] = 2] = "AddNew"; + })(ImportFixKind || (ImportFixKind = {})); + var ImportKind; + (function (ImportKind) { + ImportKind[ImportKind["Named"] = 0] = "Named"; + ImportKind[ImportKind["Default"] = 1] = "Default"; + ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; + ImportKind[ImportKind["Equals"] = 3] = "Equals"; + })(ImportKind || (ImportKind = {})); + function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, allSourceFiles, formatContext, symbolToken, preferences) { + var exportInfos = getAllReExportingModules(exportedSymbol, moduleSymbol, symbolName, sourceFile, checker, allSourceFiles); + ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); + // We sort the best codefixes first, so taking `first` is best for completions. + var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, host, preferences)).moduleSpecifier; + var fix = ts.first(getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences)); + return { moduleSpecifier: moduleSpecifier, codeAction: codeActionForFix({ host: host, formatContext: formatContext }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences)) }; + } + codefix.getImportCompletionAction = getImportCompletionAction; + function getAllReExportingModules(exportedSymbol, exportingModuleSymbol, symbolName, sourceFile, checker, allSourceFiles) { + var result = []; + forEachExternalModule(checker, allSourceFiles, function (moduleSymbol, moduleFile) { + // Don't import from a re-export when looking "up" like to `./index` or `../index`. + if (moduleFile && moduleSymbol !== exportingModuleSymbol && ts.startsWith(sourceFile.fileName, ts.getDirectoryPath(moduleFile.fileName))) { + return; + } + for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { + var exported = _a[_i]; + if ((exported.escapedName === "default" /* Default */ || exported.name === symbolName) && ts.skipAlias(exported, checker) === exportedSymbol) { + var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; + result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); + } + } + }); + return result; + } + function getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences) { + var checker = program.getTypeChecker(); + var existingImports = ts.flatMap(exportInfos, function (info) { return getExistingImportDeclarations(info, checker, sourceFile); }); + var useNamespace = tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker); + var addToExisting = tryAddToExistingImport(existingImports); + // Don't bother providing an action to add a new import if we can add to an existing one. + var addImport = addToExisting ? [addToExisting] : getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences); + return (useNamespace ? [useNamespace] : ts.emptyArray).concat(addImport); + } + function tryUseExistingNamespaceImport(existingImports, symbolName, symbolToken, checker) { + // It is possible that multiple import statements with the same specifier exist in the file. + // e.g. + // + // import * as ns from "foo"; + // import { member1, member2 } from "foo"; + // + // member3/**/ <-- cusor here + // + // in this case we should provie 2 actions: + // 1. change "member3" to "ns.member3" + // 2. add "member3" to the second import statement's import list + // and it is up to the user to decide which one fits best. + return !symbolToken || !ts.isIdentifier(symbolToken) ? undefined : ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration; + var namespace = getNamespaceImportName(declaration); + if (namespace) { + var moduleSymbol = checker.getAliasedSymbol(checker.getSymbolAtLocation(namespace)); + if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(symbolName))) { + return { kind: 0 /* UseNamespace */, namespacePrefix: namespace.text, symbolToken: symbolToken }; + } + } + }); + } + function tryAddToExistingImport(existingImports) { + return ts.firstDefined(existingImports, function (_a) { + var declaration = _a.declaration, importKind = _a.importKind; + if (declaration.kind !== 247 /* ImportDeclaration */) + return undefined; + var importClause = declaration.importClause; + if (!importClause) + return undefined; + var name = importClause.name, namedBindings = importClause.namedBindings; + return importKind === 1 /* Default */ && !name || importKind === 0 /* Named */ && (!namedBindings || namedBindings.kind === 250 /* NamedImports */) + ? { kind: 1 /* AddToExisting */, importClause: importClause, importKind: importKind } + : undefined; + }); + } + function getNamespaceImportName(declaration) { + if (declaration.kind === 247 /* ImportDeclaration */) { + var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; + return namedBindings && namedBindings.kind === 249 /* NamespaceImport */ ? namedBindings.name : undefined; + } + else { + return declaration.name; + } + } + function getExistingImportDeclarations(_a, checker, _b) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; + var imports = _b.imports; + return ts.mapDefined(imports, function (moduleSpecifier) { + var i = ts.importFromModuleSpecifier(moduleSpecifier); + return (i.kind === 247 /* ImportDeclaration */ || i.kind === 246 /* ImportEqualsDeclaration */) + && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind: importKind } : undefined; + }); + } + function getNewImportInfos(program, sourceFile, moduleSymbols, host, preferences) { + var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { + var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; + var modulePathsGroups = ts.moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences); + return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ kind: 2 /* AddNew */, moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); + }); + // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together + return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); + } + function getFixesForAddImport(exportInfos, existingImports, program, sourceFile, host, preferences) { + var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); + return existingDeclaration ? [existingDeclaration] : getNewImportInfos(program, sourceFile, exportInfos, host, preferences); + } + function newImportInfoFromExistingSpecifier(_a) { + var declaration = _a.declaration, importKind = _a.importKind; + var expression = declaration.kind === 247 /* ImportDeclaration */ + ? declaration.moduleSpecifier + : declaration.moduleReference.kind === 257 /* ExternalModuleReference */ + ? declaration.moduleReference.expression + : undefined; + return expression && ts.isStringLiteral(expression) ? { kind: 2 /* AddNew */, moduleSpecifier: expression.text, importKind: importKind } : undefined; + } + function getFixesInfo(context, errorCode, pos) { + var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); + var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code + ? getFixesInfoForUMDImport(context, symbolToken) + : getFixesInfoForNonUMDImport(context, symbolToken); + return info && __assign({}, info, { fixes: ts.sort(info.fixes, function (a, b) { return a.kind - b.kind; }) }); + } + function getFixesInfoForUMDImport(_a, token) { + var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; + var checker = program.getTypeChecker(); + var umdSymbol = getUmdSymbol(token, checker); + if (!umdSymbol) + return undefined; + var symbol = checker.getAliasedSymbol(umdSymbol); + var symbolName = umdSymbol.name; + var exportInfos = [{ moduleSymbol: symbol, importKind: getUmdImportKind(program.getCompilerOptions()) }]; + var fixes = getFixForImport(exportInfos, symbolName, token, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName }; + } + function getUmdSymbol(token, checker) { + // try the identifier to see if it is the umd symbol + var umdSymbol = ts.isIdentifier(token) ? checker.getSymbolAtLocation(token) : undefined; + if (ts.isUMDExportSymbol(umdSymbol)) + return umdSymbol; + // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. + var parent = token.parent; + return (ts.isJsxOpeningLikeElement(parent) && parent.tagName === token) || ts.isJsxOpeningFragment(parent) + ? ts.tryCast(checker.resolveName(checker.getJsxNamespace(parent), ts.isJsxOpeningLikeElement(parent) ? token : parent, 67216319 /* Value */, /*excludeGlobals*/ false), ts.isUMDExportSymbol) + : undefined; + } + function getUmdImportKind(compilerOptions) { + // Import a synthetic `default` if enabled. + if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { + return 1 /* Default */; + } + // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. + var moduleKind = ts.getEmitModuleKind(compilerOptions); + switch (moduleKind) { + case ts.ModuleKind.AMD: + case ts.ModuleKind.CommonJS: + case ts.ModuleKind.UMD: + return 3 /* Equals */; + case ts.ModuleKind.System: + case ts.ModuleKind.ES2015: + case ts.ModuleKind.ESNext: + case ts.ModuleKind.None: + // Fall back to the `import * as ns` style import. + return 2 /* Namespace */; + default: + return ts.Debug.assertNever(moduleKind); + } + } + function getFixesInfoForNonUMDImport(_a, symbolToken) { + var sourceFile = _a.sourceFile, program = _a.program, cancellationToken = _a.cancellationToken, host = _a.host, preferences = _a.preferences; + // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. + var checker = program.getTypeChecker(); + // If we're at ``, we must check if `Foo` is already in scope, and if so, get an import for `React` instead. + var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) + && symbolToken.parent.tagName === symbolToken + && (!ts.isIdentifier(symbolToken) || ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) + ? checker.getJsxNamespace() + : ts.isIdentifier(symbolToken) ? symbolToken.text : undefined; + if (!symbolName) + return undefined; + // "default" is a keyword and not a legal identifier for the import, so we don't expect it here + ts.Debug.assert(symbolName !== "default" /* Default */); + var fixes = ts.arrayFrom(ts.flatMapIterator(getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, checker, program).entries(), function (_a) { + var _ = _a[0], exportInfos = _a[1]; + return getFixForImport(exportInfos, symbolName, symbolToken, program, sourceFile, host, preferences); + })); + return { fixes: fixes, symbolName: symbolName }; + } + // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. + function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, sourceFile, checker, program) { + // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. + // Maps symbol id to info for modules providing that symbol (original export + re-exports). + var originalSymbolToExportInfos = ts.createMultiMap(); + function addSymbol(moduleSymbol, exportedSymbol, importKind) { + originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); + } + forEachExternalModuleToImportFrom(checker, sourceFile, program.getSourceFiles(), function (moduleSymbol) { + cancellationToken.throwIfCancellationRequested(); + // check the default export + var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) { + var info = getDefaultExportInfo(defaultExport, moduleSymbol, program); + if (info && info.name === symbolName && symbolHasMeaning(info.symbolForMeaning, currentTokenMeaning)) { + addSymbol(moduleSymbol, defaultExport, 1 /* Default */); + } + } + // check exports with the same name + var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); + if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); + } + }); + return originalSymbolToExportInfos; + } + function getDefaultExportInfo(defaultExport, moduleSymbol, program) { + var checker = program.getTypeChecker(); + var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); + if (localSymbol) + return { symbolForMeaning: localSymbol, name: localSymbol.name }; + var name = getNameForExportDefault(defaultExport); + if (name !== undefined) + return { symbolForMeaning: defaultExport, name: name }; + if (defaultExport.flags & 2097152 /* Alias */) { + var aliased = checker.getAliasedSymbol(defaultExport); + return getDefaultExportInfo(aliased, ts.Debug.assertDefined(aliased.parent), program); + } + else { + var moduleName = moduleSymbolToValidIdentifier(moduleSymbol, program.getCompilerOptions().target); + return moduleName === undefined ? undefined : { symbolForMeaning: defaultExport, name: moduleName }; + } + } + function getNameForExportDefault(symbol) { + return symbol.declarations && ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.text; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.text === "default" /* Default */); + return declaration.propertyName && declaration.propertyName.text; + } + }); + } + function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference) { + var diag; + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); + }); + return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + } + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { + switch (fix.kind) { + case 0 /* UseNamespace */: + addNamespaceQualifier(changes, sourceFile, fix); + return [ts.Diagnostics.Change_0_to_1, symbolName, fix.namespacePrefix + "." + symbolName]; + case 1 /* AddToExisting */: { + var importClause = fix.importClause, importKind = fix.importKind; + doAddExistingFix(changes, sourceFile, importClause, importKind === 1 /* Default */ ? symbolName : undefined, importKind === 0 /* Named */ ? [symbolName] : ts.emptyArray); + var moduleSpecifierWithoutQuotes = ts.stripQuotes(importClause.parent.moduleSpecifier.getText()); + return [ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, symbolName, moduleSpecifierWithoutQuotes]; + } + case 2 /* AddNew */: { + var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier; + addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, importKind === 1 /* Default */ ? { defaultImport: symbolName, namedImports: ts.emptyArray, namespaceLikeImport: undefined } + : importKind === 0 /* Named */ ? { defaultImport: undefined, namedImports: [symbolName], namespaceLikeImport: undefined } + : { defaultImport: undefined, namedImports: ts.emptyArray, namespaceLikeImport: { importKind: importKind, name: symbolName } }); + return [ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + } + default: + return ts.Debug.assertNever(fix); + } + } + function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports) { + if (defaultImport) { + ts.Debug.assert(!clause.name); + changes.insertNodeAt(sourceFile, clause.getStart(sourceFile), ts.createIdentifier(defaultImport), { suffix: ", " }); + } + if (namedImports.length) { + var specifiers = namedImports.map(function (name) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name)); }); + if (clause.namedBindings && ts.cast(clause.namedBindings, ts.isNamedImports).elements.length) { + for (var _i = 0, specifiers_1 = specifiers; _i < specifiers_1.length; _i++) { + var spec = specifiers_1[_i]; + changes.insertNodeInListAfter(sourceFile, ts.last(ts.cast(clause.namedBindings, ts.isNamedImports).elements), spec); + } + } + else { + if (specifiers.length) { + var namedImports_1 = ts.createNamedImports(specifiers); + if (clause.namedBindings) { + changes.replaceNode(sourceFile, clause.namedBindings, namedImports_1); + } + else { + changes.insertNodeAfter(sourceFile, ts.Debug.assertDefined(clause.name), namedImports_1); + } + } + } + } + } + function addNamespaceQualifier(changes, sourceFile, _a) { + var namespacePrefix = _a.namespacePrefix, symbolToken = _a.symbolToken; + changes.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); + } + function addNewImports(changes, sourceFile, moduleSpecifier, quotePreference, _a) { + var defaultImport = _a.defaultImport, namedImports = _a.namedImports, namespaceLikeImport = _a.namespaceLikeImport; + var quotedModuleSpecifier = ts.makeStringLiteral(moduleSpecifier, quotePreference); + if (defaultImport !== undefined || namedImports.length) { + ts.insertImport(changes, sourceFile, ts.makeImport(defaultImport === undefined ? undefined : ts.createIdentifier(defaultImport), namedImports.map(function (n) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(n)); }), moduleSpecifier, quotePreference)); + } + if (namespaceLikeImport) { + ts.insertImport(changes, sourceFile, namespaceLikeImport.importKind === 3 /* Equals */ + ? ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(namespaceLikeImport.name), ts.createExternalModuleReference(quotedModuleSpecifier)) + : ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(ts.createIdentifier(namespaceLikeImport.name))), quotedModuleSpecifier)); + } + } + function symbolHasMeaning(_a, meaning) { + var declarations = _a.declarations; + return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); + } + function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { + forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { + if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + cb(module); + } + }); + } + codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; + function forEachExternalModule(checker, allSourceFiles, cb) { + for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { + var ambient = _a[_i]; + cb(ambient, /*sourceFile*/ undefined); + } + for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { + var sourceFile = allSourceFiles_1[_b]; + if (ts.isExternalOrCommonJsModule(sourceFile)) { + cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); + } + } + } + /** + * Don't include something from a `node_modules` that isn't actually reachable by a global import. + * A relative import to node_modules is usually a bad idea. + */ + function isImportablePath(fromPath, toPath) { + // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. + var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); + return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + } + function moduleSymbolToValidIdentifier(moduleSymbol, target) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + } + codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; + function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); + var res = ""; + var lastCharWasValid = true; + var firstCharCode = baseName.charCodeAt(0); + if (ts.isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + } + else { + lastCharWasValid = false; + } + for (var i = 1; i < baseName.length; i++) { + var ch = baseName.charCodeAt(i); + var isValid = ts.isIdentifierPart(ch, target); + if (isValid) { + var char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + // Need `|| "_"` to ensure result isn't empty. + return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; + } + codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixSpelling"; + var errorCodes = [ + ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code, + ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2.code, + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var info = getInfo(sourceFile, context.span.start, context); + if (!info) + return undefined; + var node = info.node, suggestion = info.suggestion; + var target = context.host.getCompilationSettings().target; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start, context); + var target = context.host.getCompilationSettings().target; + if (info) + doChange(changes, context.sourceFile, info.node, info.suggestion, target); + }); }, + }); + function getInfo(sourceFile, pos, context) { + // This is the identifier of the misspelled word. eg: + // this.speling = 1; + // ^^^^^^^ + var node = ts.getTokenAtPosition(sourceFile, pos); + var checker = context.program.getTypeChecker(); + var suggestion; + if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); + var containingType = checker.getTypeAtLocation(node.parent.expression); + suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + } + else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { + ts.Debug.assert(node.kind === 71 /* Identifier */); + var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); + var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); + if (resolvedSourceFile && resolvedSourceFile.symbol) { + suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + } + } + else { + var meaning = ts.getMeaningFromLocation(node); + var name = ts.getTextOfNode(node); + ts.Debug.assert(name !== undefined, "name should be defined"); + suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + } + return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + } + function doChange(changes, sourceFile, node, suggestion, target) { + if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } + else { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + } + function convertSemanticMeaningToSymbolFlags(meaning) { + var flags = 0; + if (meaning & 4 /* Namespace */) { + flags |= 1920 /* Namespace */; + } + if (meaning & 2 /* Type */) { + flags |= 67901928 /* Type */; + } + if (meaning & 1 /* Value */) { + flags |= 67216319 /* Value */; + } + return flags; + } + function getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration) { + if (!importDeclaration || !ts.isStringLiteralLike(importDeclaration.moduleSpecifier)) + return undefined; + var resolvedModule = ts.getResolvedModule(sourceFile, importDeclaration.moduleSpecifier.text); + if (!resolvedModule) + return undefined; + return context.program.getSourceFile(resolvedModule.resolvedFileName); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixName = "addMissingMember"; var errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1.code, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, @@ -97320,94 +105225,131 @@ var ts; var info = getInfo(context.sourceFile, context.span.start, context.program.getTypeChecker()); if (!info) return undefined; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); + if (info.kind === InfoKind.enum) { + var token_1 = info.token, parentDeclaration_1 = info.parentDeclaration; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addEnumMemberDeclaration(t, context.program.getTypeChecker(), token_1, parentDeclaration_1); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_missing_enum_member_0, token_1.text], fixId, ts.Diagnostics.Add_all_missing_members)]; + } + var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + var methodCodeAction = call && getActionForMethodDeclaration(context, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); var addMember = inJs ? - ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, token.text, makeStatic)) : - getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, classDeclaration, token, makeStatic); + ts.singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic)) : + getActionsForAddMissingMemberInTypeScriptFile(context, classDeclarationSourceFile, parentDeclaration, token, makeStatic); return ts.concatenate(ts.singleElementArray(methodCodeAction), addMember); }, fixIds: [fixId], getAllCodeActions: function (context) { - var seenNames = ts.createMap(); - return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var program = context.program; - var info = getInfo(diag.file, diag.start, program.getTypeChecker()); - if (!info) - return; - var classDeclaration = info.classDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; - if (!ts.addToSeen(seenNames, token.text)) { - return; - } - // Always prefer to add a method declaration if possible. - if (call) { - addMethodDeclaration(changes, classDeclarationSourceFile, classDeclaration, token, call, makeStatic, inJs); - } - else { - if (inJs) { - addMissingMemberInJs(changes, classDeclarationSourceFile, classDeclaration, token.text, makeStatic); + var program = context.program, preferences = context.preferences; + var checker = program.getTypeChecker(); + var seen = ts.createMap(); + var classToMembers = new ts.NodeMap(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (diag) { + var info = getInfo(diag.file, diag.start, checker); + if (!info || !ts.addToSeen(seen, ts.getNodeId(info.parentDeclaration) + "#" + info.token.text)) { + return; + } + if (info.kind === InfoKind.enum) { + var token = info.token, parentDeclaration = info.parentDeclaration; + addEnumMemberDeclaration(changes, checker, token, parentDeclaration); } else { - var typeNode = getTypeNode(program.getTypeChecker(), classDeclaration, token); - addPropertyDeclaration(changes, classDeclarationSourceFile, classDeclaration, token.text, typeNode, makeStatic); + var parentDeclaration = info.parentDeclaration, token_2 = info.token; + var infos = classToMembers.getOrUpdate(parentDeclaration, function () { return []; }); + if (!infos.some(function (i) { return i.token.text === token_2.text; })) + infos.push(info); } - } - }); + }); + classToMembers.forEach(function (infos, classDeclaration) { + var superClasses = getAllSuperClasses(classDeclaration, checker); + var _loop_24 = function (info) { + // If some superclass added this property, don't add it again. + if (superClasses.some(function (superClass) { + var superInfos = classToMembers.get(superClass); + return !!superInfos && superInfos.some(function (_a) { + var token = _a.token; + return token.text === info.token.text; + }); + })) + return "continue"; + var parentDeclaration = info.parentDeclaration, classDeclarationSourceFile = info.classDeclarationSourceFile, inJs = info.inJs, makeStatic = info.makeStatic, token = info.token, call = info.call; + // Always prefer to add a method declaration if possible. + if (call) { + addMethodDeclaration(context, changes, classDeclarationSourceFile, parentDeclaration, token, call, makeStatic, inJs, preferences); + } + else { + if (inJs) { + addMissingMemberInJs(changes, classDeclarationSourceFile, parentDeclaration, token.text, makeStatic); + } + else { + var typeNode = getTypeNode(program.getTypeChecker(), parentDeclaration, token); + addPropertyDeclaration(changes, classDeclarationSourceFile, parentDeclaration, token.text, typeNode, makeStatic); + } + } + }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + _loop_24(info); + } + }); + })); }, }); + function getAllSuperClasses(cls, checker) { + var res = []; + while (cls) { + var superElement = ts.getClassExtendsHeritageElement(cls); + var superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); + var superDecl = superSymbol && ts.find(superSymbol.declarations, ts.isClassLike); + if (superDecl) { + res.push(superDecl); + } + cls = superDecl; + } + return res; + } + var InfoKind; + (function (InfoKind) { + InfoKind[InfoKind["enum"] = 0] = "enum"; + InfoKind[InfoKind["class"] = 1] = "class"; + })(InfoKind || (InfoKind = {})); function getInfo(tokenSourceFile, tokenPos, checker) { // The identifier of the missing property. eg: // this.missing = 1; // ^^^^^^^ - var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(tokenSourceFile, tokenPos); if (!ts.isIdentifier(token)) { return undefined; } - var classAndMakeStatic = getClassAndMakeStatic(token, checker); - if (!classAndMakeStatic) { - return undefined; - } - var classDeclaration = classAndMakeStatic.classDeclaration, makeStatic = classAndMakeStatic.makeStatic; - var classDeclarationSourceFile = classDeclaration.getSourceFile(); - var inJs = ts.isInJavaScriptFile(classDeclarationSourceFile); - var call = ts.tryCast(token.parent.parent, ts.isCallExpression); - return { token: token, classDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; - } - function getClassAndMakeStatic(token, checker) { var parent = token.parent; - if (!ts.isPropertyAccessExpression(parent)) { + if (!ts.isPropertyAccessExpression(parent)) return undefined; + var leftExpressionType = ts.skipConstraint(checker.getTypeAtLocation(parent.expression)); + var symbol = leftExpressionType.symbol; + if (!symbol || !symbol.declarations) + return undefined; + var classDeclaration = ts.find(symbol.declarations, ts.isClassLike); + if (classDeclaration) { + var makeStatic = leftExpressionType.target !== checker.getDeclaredTypeOfSymbol(symbol); + var classDeclarationSourceFile = classDeclaration.getSourceFile(); + var inJs = ts.isSourceFileJavaScript(classDeclarationSourceFile); + var call = ts.tryCast(parent.parent, ts.isCallExpression); + return { kind: InfoKind.class, token: token, parentDeclaration: classDeclaration, makeStatic: makeStatic, classDeclarationSourceFile: classDeclarationSourceFile, inJs: inJs, call: call }; } - if (parent.expression.kind === 99 /* ThisKeyword */) { - var containingClassMemberDeclaration = ts.getThisContainer(token, /*includeArrowFunctions*/ false); - if (!ts.isClassElement(containingClassMemberDeclaration)) { - return undefined; - } - var classDeclaration = containingClassMemberDeclaration.parent; - // Property accesses on `this` in a static method are accesses of a static member. - return ts.isClassLike(classDeclaration) ? { classDeclaration: classDeclaration, makeStatic: ts.hasModifier(containingClassMemberDeclaration, 32 /* Static */) } : undefined; - } - else { - var leftExpressionType = checker.getTypeAtLocation(parent.expression); - var symbol = leftExpressionType.symbol; - if (!(symbol && leftExpressionType.flags & 65536 /* Object */ && symbol.flags & 32 /* Class */)) { - return undefined; - } - var classDeclaration = ts.cast(ts.first(symbol.declarations), ts.isClassLike); - // The expression is a class symbol but the type is not the instance-side. - return { classDeclaration: classDeclaration, makeStatic: leftExpressionType !== checker.getDeclaredTypeOfSymbol(symbol) }; + var enumDeclaration = ts.find(symbol.declarations, ts.isEnumDeclaration); + if (enumDeclaration) { + return { kind: InfoKind.enum, token: token, parentDeclaration: enumDeclaration }; } + return undefined; } function getActionsForAddMissingMemberInJavaScriptFile(context, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMemberInJs(t, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic); }); - if (changes.length === 0) - return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor), [tokenName]); - return { description: description, changes: changes, fixId: fixId }; + return changes.length === 0 ? undefined + : codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Initialize_static_property_0 : ts.Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addMissingMemberInJs(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, makeStatic) { if (makeStatic) { - if (classDeclaration.kind === 203 /* ClassExpression */) { + if (classDeclaration.kind === 207 /* ClassExpression */) { return; } var className = classDeclaration.name.getText(); @@ -97433,7 +105375,7 @@ var ts; } function getTypeNode(checker, classDeclaration, token) { var typeNode; - if (token.parent.parent.kind === 198 /* BinaryExpression */) { + if (token.parent.parent.kind === 202 /* BinaryExpression */) { var binaryExpression = token.parent.parent; var otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; var widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); @@ -97442,9 +105384,8 @@ var ts; return typeNode || ts.createKeywordTypeNode(119 /* AnyKeyword */); } function createAddPropertyDeclarationAction(context, classDeclarationSourceFile, classDeclaration, makeStatic, tokenName, typeNode) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0), [tokenName]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addPropertyDeclaration(t, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_property_0 : ts.Diagnostics.Declare_property_0, tokenName], fixId, ts.Diagnostics.Add_all_missing_members); } function addPropertyDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, tokenName, typeNode, makeStatic) { var property = ts.createProperty( @@ -97452,7 +105393,24 @@ var ts; /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, tokenName, /*questionToken*/ undefined, typeNode, /*initializer*/ undefined); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + var lastProp = getNodeToInsertPropertyAfter(classDeclaration); + if (lastProp) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, lastProp, property); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, property); + } + } + // Gets the last of the first run of PropertyDeclarations, or undefined if the class does not start with a PropertyDeclaration. + function getNodeToInsertPropertyAfter(cls) { + var res; + for (var _i = 0, _a = cls.members; _i < _a.length; _i++) { + var member = _a[_i]; + if (!ts.isPropertyDeclaration(member)) + break; + res = member; + } + return res; } function createAddIndexSignatureAction(context, classDeclarationSourceFile, classDeclaration, tokenName, typeNode) { // Index signatures cannot have the static modifier. @@ -97468,82 +105426,34 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return { description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_index_signature_for_property_0), [tokenName]), changes: changes, fixId: undefined }; + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } - function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0), [token.text]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs); }); - return { description: description, changes: changes, fixId: fixId }; + function getActionForMethodDeclaration(context, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMethodDeclaration(context, t, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences); }); + return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } - function addMethodDeclaration(changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs) { - var methodDeclaration = codefix.createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); - } - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var codefix; - (function (codefix) { - var fixId = "fixSpelling"; - var errorCodes = [ - ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - ]; - codefix.registerCodeFix({ - errorCodes: errorCodes, - getCodeActions: function (context) { - var sourceFile = context.sourceFile; - var info = getInfo(sourceFile, context.span.start, context.program.getTypeChecker()); - if (!info) - return undefined; - var node = info.node, suggestion = info.suggestion; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion); }); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_spelling_to_0), [suggestion]); - return [{ description: description, changes: changes, fixId: fixId }]; - }, - fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var info = getInfo(diag.file, diag.start, context.program.getTypeChecker()); - if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion); - }); }, - }); - function getInfo(sourceFile, pos, checker) { - // This is the identifier of the misspelled word. eg: - // this.speling = 1; - // ^^^^^^^ - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); // TODO: GH#15852 - var suggestion; - if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 71 /* Identifier */); - var containingType = checker.getTypeAtLocation(node.parent.expression); - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + function addMethodDeclaration(context, changeTracker, classDeclarationSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences); + var containingMethodDeclaration = ts.getAncestor(callExpression, 154 /* MethodDeclaration */); + if (containingMethodDeclaration && containingMethodDeclaration.parent === classDeclaration) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, containingMethodDeclaration, methodDeclaration); } else { - var meaning = ts.getMeaningFromLocation(node); - var name = ts.getTextOfNode(node); - ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; } - function doChange(changes, sourceFile, node, suggestion) { - changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); - } - function convertSemanticMeaningToSymbolFlags(meaning) { - var flags = 0; - if (meaning & 4 /* Namespace */) { - flags |= 1920 /* Namespace */; - } - if (meaning & 2 /* Type */) { - flags |= 67901928 /* Type */; - } - if (meaning & 1 /* Value */) { - flags |= 67216319 /* Value */; - } - return flags; + function addEnumMemberDeclaration(changes, checker, token, enumDeclaration) { + /** + * create initializer only literal enum that has string initializer. + * value of initializer is a string literal that equal to name of enum member. + * numeric enum or empty enum will not create initializer. + */ + var hasStringInitializer = ts.some(enumDeclaration.members, function (member) { + var type = checker.getTypeAtLocation(member); + return !!(type && type.flags & 68 /* StringLike */); + }); + var enumMember = ts.createEnumMember(token, hasStringInitializer ? ts.createStringLiteral(token.text) : undefined); + changes.replaceNode(enumDeclaration.getSourceFile(), enumDeclaration, ts.updateEnumDeclaration(enumDeclaration, enumDeclaration.decorators, enumDeclaration.modifiers, enumDeclaration.name, ts.concatenate(enumDeclaration.members, ts.singleElementArray(enumMember)))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97553,39 +105463,36 @@ var ts; var codefix; (function (codefix) { var fixId = "fixCannotFindModule"; - var errorCodes = [ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code]; + var errorCodeCannotFindModule = ts.Diagnostics.Cannot_find_module_0.code; + var errorCodes = [ + errorCodeCannotFindModule, + ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var codeAction = tryGetCodeActionForInstallPackageTypes(context.host, context.sourceFile.fileName, getModuleName(context.sourceFile, context.span.start)); - return codeAction && [__assign({ fixId: fixId }, codeAction)]; + var host = context.host, sourceFile = context.sourceFile, start = context.span.start; + var packageName = getTypesPackageNameToInstall(host, sourceFile, start, context.errorCode); + return packageName === undefined ? [] + : [codefix.createCodeFixAction(fixId, /*changes*/ [], [ts.Diagnostics.Install_0, packageName], fixId, ts.Diagnostics.Install_all_missing_types_packages, getCommand(sourceFile.fileName, packageName))]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (_, diag, commands) { - var pkg = getTypesPackageNameToInstall(context.host, getModuleName(diag.file, diag.start)); + var pkg = getTypesPackageNameToInstall(context.host, diag.file, diag.start, diag.code); if (pkg) { commands.push(getCommand(diag.file.fileName, pkg)); } }); }, }); - function getModuleName(sourceFile, pos) { - return ts.cast(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), ts.isStringLiteral).text; - } function getCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } - function getTypesPackageNameToInstall(host, moduleName) { + function getTypesPackageNameToInstall(host, sourceFile, pos, diagCode) { + var moduleName = ts.cast(ts.getTokenAtPosition(sourceFile, pos), ts.isStringLiteral).text; var packageName = ts.getPackageName(moduleName).packageName; - // If !registry, registry not available yet, can't do anything. - return host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined; - } - function tryGetCodeActionForInstallPackageTypes(host, fileName, moduleName) { - var packageName = getTypesPackageNameToInstall(host, moduleName); - return packageName === undefined ? undefined : { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Install_0), [packageName]), - changes: [], - commands: [getCommand(fileName, packageName)], - }; + return diagCode === errorCodeCannotFindModule + ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) + : (host.isKnownTypesPackageName(packageName) ? ts.getTypesPackageName(packageName) : undefined); // TODO: GH#18217 } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97604,9 +105511,9 @@ var ts; getCodeActions: function (context) { var program = context.program, sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); }); - return changes.length === 0 ? undefined : [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Implement_inherited_abstract_class), changes: changes, fixId: fixId }]; + return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -97614,7 +105521,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes); + addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); } }); }, @@ -97622,16 +105529,16 @@ var ts; function getClass(sourceFile, pos) { // Token is the identifier in the case of a class declaration // or the class keyword token in the case of a class expression. - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker) { - var extendsNode = ts.getClassExtendsHeritageClauseElement(classDeclaration); + function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -97657,7 +105564,7 @@ var ts; return undefined; var constructor = nodes.constructor, superCall = nodes.superCall; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, constructor, superCall); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId, ts.Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -97676,10 +105583,10 @@ var ts; }); function doChange(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); - changes.deleteNode(sourceFile, superCall); + changes.delete(sourceFile, superCall); } function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); if (token.kind !== 99 /* ThisKeyword */) return undefined; var constructor = ts.getContainingFunction(token); @@ -97710,7 +105617,7 @@ var ts; var sourceFile = context.sourceFile, span = context.span; var ctr = getNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, ctr); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_super_call, fixId, ts.Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97718,7 +105625,7 @@ var ts; }); }, }); function getNode(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); ts.Debug.assert(token.kind === 123 /* ConstructorKeyword */); return token.parent; } @@ -97744,7 +105651,7 @@ var ts; return undefined; var extendsToken = nodes.extendsToken, heritageClauses = nodes.heritageClauses; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChanges(t, sourceFile, extendsToken, heritageClauses); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Change_extends_to_implements), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Change_extends_to_implements, fixId, ts.Diagnostics.Change_all_extended_interfaces_to_implements)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -97754,13 +105661,13 @@ var ts; }); }, }); function getNodes(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); var heritageClauses = ts.getContainingClass(token).heritageClauses; var extendsToken = heritageClauses[0].getFirstToken(); return extendsToken.kind === 85 /* ExtendsKeyword */ ? { extendsToken: extendsToken, heritageClauses: heritageClauses } : undefined; } function doChanges(changes, sourceFile, extendsToken, heritageClauses) { - changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */), ts.textChanges.useNonAdjustedPositions); + changes.replaceNode(sourceFile, extendsToken, ts.createToken(108 /* ImplementsKeyword */)); // If there is already an implements clause, replace the implements keyword with a comma. if (heritageClauses.length === 2 && heritageClauses[0].token === 85 /* ExtendsKeyword */ && @@ -97786,34 +105693,40 @@ var ts; var codefix; (function (codefix) { var fixId = "forgottenThisPropertyAccess"; - var errorCodes = [ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code]; + var didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; + var errorCodes = [ + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, + didYouMeanStaticMemberCode, + ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { var sourceFile = context.sourceFile; - var token = getNode(sourceFile, context.span.start); - if (!token) { + var info = getInfo(sourceFile, context.span.start, context.errorCode); + if (!info) { return undefined; } - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, token); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_this_to_unresolved_variable), changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId, ts.Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - doChange(changes, context.sourceFile, getNode(diag.file, diag.start)); + var info = getInfo(diag.file, diag.start, diag.code); + if (info) + doChange(changes, context.sourceFile, info); }); }, }); - function getNode(sourceFile, pos) { - var node = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); - return ts.isIdentifier(node) ? node : undefined; + function getInfo(sourceFile, pos, diagCode) { + var node = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(node)) + return undefined; + return { node: node, className: diagCode === didYouMeanStaticMemberCode ? ts.getContainingClass(node).name.text : undefined }; } - function doChange(changes, sourceFile, token) { - if (!token) { - return; - } + function doChange(changes, sourceFile, _a) { + var node = _a.node, className = _a.className; // TODO (https://github.com/Microsoft/TypeScript/issues/21246): use shared helper - ts.suppressLeadingAndTrailingTrivia(token); - changes.replaceNode(sourceFile, token, ts.createPropertyAccess(ts.createThis(), token), ts.textChanges.useNonAdjustedPositions); + ts.suppressLeadingAndTrailingTrivia(node); + changes.replaceNode(sourceFile, node, ts.createPropertyAccess(className ? ts.createIdentifier(className) : ts.createThis(), node)); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -97822,70 +105735,106 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; var errorCodes = [ ts.Diagnostics._0_is_declared_but_its_value_is_never_read.code, + ts.Diagnostics._0_is_declared_but_never_used.code, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, ts.Diagnostics.All_imports_in_import_declaration_are_unused.code, + ts.Diagnostics.All_destructured_elements_are_unused.code, + ts.Diagnostics.All_variables_are_unused.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var errorCode = context.errorCode, sourceFile = context.sourceFile; - var importDecl = tryGetFullImport(sourceFile, context.span.start); + var errorCode = context.errorCode, sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + var importDecl = tryGetFullImport(token); if (importDecl) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_import_from_0), [ts.showModuleSpecifier(importDecl)]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.deleteNode(sourceFile, importDecl); }); - return [{ description: description, changes: changes, fixId: fixIdDelete }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.delete(sourceFile, importDecl); }); + return [codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Remove_import_from_0, ts.showModuleSpecifier(importDecl)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var delDestructure = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteFullDestructure(token, t, sourceFile, checker, sourceFiles, /*isFixAll*/ false); + }); + if (delDestructure.length) { + return [codefix.createCodeFixAction(fixName, delDestructure, ts.Diagnostics.Remove_destructuring, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; + } + var delVar = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteFullVariableStatement(sourceFile, token, t); }); + if (delVar.length) { + return [codefix.createCodeFixAction(fixName, delVar, ts.Diagnostics.Remove_variable_statement, fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)]; } - var token = getToken(sourceFile, ts.textSpanEnd(context.span)); var result = []; - var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { return tryDeleteDeclaration(t, sourceFile, token); }); + var deletion = ts.textChanges.ChangeTracker.with(context, function (t) { + return tryDeleteDeclaration(sourceFile, token, t, checker, sourceFiles, /*isFixAll*/ false); + }); if (deletion.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), [token.getText()]); - result.push({ description: description, changes: deletion, fixId: fixIdDelete }); + var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; + result.push(codefix.createCodeFixAction(fixName, deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)], fixIdDelete, ts.Diagnostics.Delete_all_unused_declarations)); } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); if (prefix.length) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), [token.getText()]); - result.push({ description: description, changes: prefix, fixId: fixIdPrefix }); + result.push(codefix.createCodeFixAction(fixName, prefix, [ts.Diagnostics.Prefix_0_with_an_underscore, token.getText(sourceFile)], fixIdPrefix, ts.Diagnostics.Prefix_all_unused_declarations_with_where_possible)); } return result; }, fixIds: [fixIdPrefix, fixIdDelete], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var sourceFile = context.sourceFile; - var token = ts.findPrecedingToken(ts.textSpanEnd(diag), diag.file); - switch (context.fixId) { - case fixIdPrefix: - if (ts.isIdentifier(token) && canPrefix(token)) { - tryPrefixDeclaration(changes, diag.code, sourceFile, token); + getAllCodeActions: function (context) { + var sourceFile = context.sourceFile, program = context.program; + var checker = program.getTypeChecker(); + var sourceFiles = program.getSourceFiles(); + return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var token = ts.getTokenAtPosition(sourceFile, diag.start); + switch (context.fixId) { + case fixIdPrefix: + if (ts.isIdentifier(token) && canPrefix(token)) { + tryPrefixDeclaration(changes, diag.code, sourceFile, token); + } + break; + case fixIdDelete: { + var importDecl = tryGetFullImport(token); + if (importDecl) { + changes.delete(sourceFile, importDecl); + } + else if (!tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, /*isFixAll*/ true) && + !tryDeleteFullVariableStatement(sourceFile, token, changes)) { + tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, /*isFixAll*/ true); + } + break; } - break; - case fixIdDelete: - var importDecl = tryGetFullImport(diag.file, diag.start); - if (importDecl) { - changes.deleteNode(sourceFile, importDecl); - } - else { - tryDeleteDeclaration(changes, sourceFile, token); - } - break; - default: - ts.Debug.fail(JSON.stringify(context.fixId)); - } - }); }, + default: + ts.Debug.fail(JSON.stringify(context.fixId)); + } + }); + }, }); // Sometimes the diagnostic span is an entire ImportDeclaration, so we should remove the whole thing. - function tryGetFullImport(sourceFile, pos) { - var startToken = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); - return startToken.kind === 91 /* ImportKeyword */ ? ts.tryCast(startToken.parent, ts.isImportDeclaration) : undefined; + function tryGetFullImport(token) { + return token.kind === 91 /* ImportKeyword */ ? ts.tryCast(token.parent, ts.isImportDeclaration) : undefined; } - function getToken(sourceFile, pos) { - var token = ts.findPrecedingToken(pos, sourceFile); - // this handles var ["computed"] = 12; - return token.kind === 22 /* CloseBracketToken */ ? ts.findPrecedingToken(pos - 1, sourceFile) : token; + function tryDeleteFullDestructure(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + if (token.kind !== 17 /* OpenBraceToken */ || !ts.isObjectBindingPattern(token.parent)) + return false; + var decl = token.parent.parent; + if (decl.kind === 149 /* Parameter */) { + tryDeleteParameter(changes, sourceFile, decl, checker, sourceFiles, isFixAll); + } + else { + changes.delete(sourceFile, decl); + } + return true; + } + function tryDeleteFullVariableStatement(sourceFile, token, changes) { + var declarationList = ts.tryCast(token.parent, ts.isVariableDeclarationList); + if (declarationList && declarationList.getChildren(sourceFile)[0] === token) { + changes.delete(sourceFile, declarationList.parent.kind === 217 /* VariableStatement */ ? declarationList.parent : declarationList); + return true; + } + return false; } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { // Don't offer to prefix a property. @@ -97895,170 +105844,174 @@ var ts; } function canPrefix(token) { switch (token.parent.kind) { - case 148 /* Parameter */: + case 149 /* Parameter */: return true; - case 230 /* VariableDeclaration */: { + case 235 /* VariableDeclaration */: { var varDecl = token.parent; switch (varDecl.parent.parent.kind) { - case 220 /* ForOfStatement */: - case 219 /* ForInStatement */: + case 225 /* ForOfStatement */: + case 224 /* ForInStatement */: return true; } } } return false; } - function tryDeleteDeclaration(changes, sourceFile, token) { - switch (token.kind) { - case 71 /* Identifier */: - tryDeleteIdentifier(changes, sourceFile, token); - break; - case 151 /* PropertyDeclaration */: - case 244 /* NamespaceImport */: - changes.deleteNode(sourceFile, token.parent); - break; - default: - tryDeleteDefault(changes, sourceFile, token); - } + function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, isFixAll) { + tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll); + if (ts.isIdentifier(token)) + deleteAssignments(changes, sourceFile, token, checker); } - function tryDeleteDefault(changes, sourceFile, token) { - if (ts.isDeclarationName(token)) { - changes.deleteNode(sourceFile, token.parent); - } - else if (ts.isLiteralComputedPropertyDeclarationName(token)) { - changes.deleteNode(sourceFile, token.parent.parent); - } - } - function tryDeleteIdentifier(changes, sourceFile, identifier) { - var parent = identifier.parent; - switch (parent.kind) { - case 230 /* VariableDeclaration */: - tryDeleteVariableDeclaration(changes, sourceFile, parent); - break; - case 147 /* TypeParameter */: - var typeParameters = parent.parent.typeParameters; - if (typeParameters.length === 1) { - var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); - ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); - changes.deleteNodeRange(sourceFile, previousToken, nextToken); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 148 /* Parameter */: - var oldFunction = parent.parent; - if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { - // Lambdas with exactly one parameter are special because, after removal, there - // must be an empty parameter list (i.e. `()`) and this won't necessarily be the - // case if the parameter is simply removed (e.g. in `x => 1`). - var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, - /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); - // Drop leading and trailing trivia of the new function because we're only going - // to replace the span (vs the full span) of the old function - the old leading - // and trailing trivia will remain. - ts.suppressLeadingAndTrailingTrivia(newFunction); - changes.replaceNode(sourceFile, oldFunction, newFunction, ts.textChanges.useNonAdjustedPositions); - } - else { - changes.deleteNodeInList(sourceFile, parent); - } - break; - // handle case where 'import a = A;' - case 241 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(identifier, 241 /* ImportEqualsDeclaration */); - changes.deleteNode(sourceFile, importEquals); - break; - case 246 /* ImportSpecifier */: - var namedImports = parent.parent; - if (namedImports.elements.length === 1) { - tryDeleteNamedImportBinding(changes, sourceFile, namedImports); - } - else { - // delete import specifier - changes.deleteNodeInList(sourceFile, parent); - } - break; - case 243 /* ImportClause */: // this covers both 'import |d|' and 'import |d,| *' - var importClause = parent; - if (!importClause.namedBindings) { // |import d from './file'| - changes.deleteNode(sourceFile, ts.getAncestor(importClause, 242 /* ImportDeclaration */)); - } - else { - // import |d,| * as ns from './file' - var start = importClause.name.getStart(sourceFile); - var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); - if (nextToken && nextToken.kind === 26 /* CommaToken */) { - // shift first non-whitespace position after comma to the start position of the node - var end = ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true); - changes.deleteRange(sourceFile, { pos: start, end: end }); - } - else { - changes.deleteNode(sourceFile, importClause.name); - } - } - break; - case 244 /* NamespaceImport */: - tryDeleteNamedImportBinding(changes, sourceFile, parent); - break; - default: - tryDeleteDefault(changes, sourceFile, identifier); - break; - } - } - function tryDeleteNamedImportBinding(changes, sourceFile, namedBindings) { - if (namedBindings.parent.name) { - // Delete named imports while preserving the default import - // import d|, * as ns| from './file' - // import d|, { a }| from './file' - var previousToken = ts.getTokenAtPosition(sourceFile, namedBindings.pos - 1, /*includeJsDocComment*/ false); - if (previousToken && previousToken.kind === 26 /* CommaToken */) { - changes.deleteRange(sourceFile, { pos: previousToken.getStart(), end: namedBindings.end }); + function deleteAssignments(changes, sourceFile, token, checker) { + ts.FindAllReferences.Core.eachSymbolReferenceInFile(token, checker, sourceFile, function (ref) { + if (ref.parent.kind === 187 /* PropertyAccessExpression */) + ref = ref.parent; + if (ref.parent.kind === 202 /* BinaryExpression */ && ref.parent.parent.kind === 219 /* ExpressionStatement */) { + changes.delete(sourceFile, ref.parent.parent); } + }); + } + function tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, isFixAll) { + var parent = token.parent; + if (ts.isParameter(parent)) { + tryDeleteParameter(changes, sourceFile, parent, checker, sourceFiles, isFixAll); } else { - // Delete the entire import declaration - // |import * as ns from './file'| - // |import { a } from './file'| - var importDecl = ts.getAncestor(namedBindings, 242 /* ImportDeclaration */); - changes.deleteNode(sourceFile, importDecl); + changes.delete(sourceFile, ts.isImportClause(parent) ? token : ts.isComputedPropertyName(parent) ? parent.parent : parent); } } - // token.parent is a variableDeclaration - function tryDeleteVariableDeclaration(changes, sourceFile, varDecl) { - switch (varDecl.parent.parent.kind) { - case 218 /* ForStatement */: { - var forStatement = varDecl.parent.parent; - var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - changes.deleteNode(sourceFile, forInitializer); - } - else { - changes.deleteNodeInList(sourceFile, varDecl); - } - break; - } - case 220 /* ForOfStatement */: - var forOfStatement = varDecl.parent.parent; - ts.Debug.assert(forOfStatement.initializer.kind === 231 /* VariableDeclarationList */); - var forOfInitializer = forOfStatement.initializer; - changes.replaceNode(sourceFile, forOfInitializer.declarations[0], ts.createObjectLiteral()); - break; - case 219 /* ForInStatement */: - case 228 /* TryStatement */: - break; - default: - var variableStatement = varDecl.parent.parent; - if (variableStatement.declarationList.declarations.length === 1) { - changes.deleteNode(sourceFile, variableStatement); - } - else { - changes.deleteNodeInList(sourceFile, varDecl); - } + function tryDeleteParameter(changes, sourceFile, p, checker, sourceFiles, isFixAll) { + if (mayDeleteParameter(p, checker, isFixAll)) { + changes.delete(sourceFile, p); + deleteUnusedArguments(changes, sourceFile, p, sourceFiles, checker); } } + function mayDeleteParameter(p, checker, isFixAll) { + var parent = p.parent; + switch (parent.kind) { + case 154 /* MethodDeclaration */: + // Don't remove a parameter if this overrides something. + var symbol = checker.getSymbolAtLocation(parent.name); + if (ts.isMemberSymbolInBaseType(symbol, checker)) + return false; + // falls through + case 155 /* Constructor */: + case 237 /* FunctionDeclaration */: + return true; + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: { + // Can't remove a non-last parameter in a callback. Can remove a parameter in code-fix-all if future parameters are also unused. + var parameters = parent.parameters; + var index = parameters.indexOf(p); + ts.Debug.assert(index !== -1); + return isFixAll + ? parameters.slice(index + 1).every(function (p) { return p.name.kind === 71 /* Identifier */ && !p.symbol.isReferenced; }) + : index === parameters.length - 1; + } + case 157 /* SetAccessor */: + // Setter must have a parameter + return false; + default: + return ts.Debug.failBadSyntaxKind(parent); + } + } + function deleteUnusedArguments(changes, sourceFile, deletedParameter, sourceFiles, checker) { + ts.FindAllReferences.Core.eachSignatureCall(deletedParameter.parent, sourceFiles, checker, function (call) { + var index = deletedParameter.parent.parameters.indexOf(deletedParameter); + if (call.arguments.length > index) { // Just in case the call didn't provide enough arguments. + changes.delete(sourceFile, call.arguments[index]); + } + }); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnreachableCode"; + var errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, diag.length); }); }, + }); + function doChange(changes, sourceFile, start, length) { + var token = ts.getTokenAtPosition(sourceFile, start); + var statement = ts.findAncestor(token, ts.isStatement); + ts.Debug.assert(statement.getStart(sourceFile) === token.getStart(sourceFile)); + var container = (ts.isBlock(statement.parent) ? statement.parent : statement).parent; + if (!ts.isBlock(statement.parent) || statement === ts.first(statement.parent.statements)) { + switch (container.kind) { + case 220 /* IfStatement */: + if (container.elseStatement) { + if (ts.isBlock(statement.parent)) { + break; + } + else { + changes.replaceNode(sourceFile, statement, ts.createBlock(ts.emptyArray)); + } + return; + } + // falls through + case 222 /* WhileStatement */: + case 223 /* ForStatement */: + changes.delete(sourceFile, container); + return; + } + } + if (ts.isBlock(statement.parent)) { + var end_2 = start + length; + var lastStatement = ts.Debug.assertDefined(lastWhere(ts.sliceAfter(statement.parent.statements, statement), function (s) { return s.pos < end_2; })); + changes.deleteNodeRange(sourceFile, statement, lastStatement); + } + else { + changes.delete(sourceFile, statement); + } + } + function lastWhere(a, pred) { + var last; + for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { + var value = a_1[_i]; + if (!pred(value)) + break; + last = value; + } + return last; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "fixUnusedLabel"; + var errorCodes = [ts.Diagnostics.Unused_label.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); }, + }); + function doChange(changes, sourceFile, start) { + var token = ts.getTokenAtPosition(sourceFile, start); + var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement); + var pos = token.getStart(sourceFile); + var statementPos = labeledStatement.statement.getStart(sourceFile); + // If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement. + var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos + : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true); + changes.deleteRange(sourceFile, { pos: pos, end: end }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -98079,18 +106032,16 @@ var ts; return undefined; var typeNode = info.typeNode, type = info.type; var original = typeNode.getText(sourceFile); - var actions = [fix(type, fixIdPlain)]; - if (typeNode.kind === 277 /* JSDocNullableType */) { + var actions = [fix(type, fixIdPlain, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; + if (typeNode.kind === 284 /* JSDocNullableType */) { // for nullable types, suggest the flow-compatible `T | null | undefined` // in addition to the jsdoc/closure-compatible `T | null` - actions.push(fix(checker.getNullableType(type, 4096 /* Undefined */), fixIdNullable)); + actions.push(fix(checker.getNullableType(type, 8192 /* Undefined */), fixIdNullable, ts.Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions; - function fix(type, fixId) { - var newText = checker.typeToString(type); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Change_0_to_1), [original, newText]); + function fix(type, fixId, fixAllDescription) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, typeNode, type, checker); }); - return { description: description, changes: changes, fixId: fixId }; + return codefix.createCodeFixAction("jdocTypes", changes, [ts.Diagnostics.Change_0_to_1, original, checker.typeToString(type)], fixId, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], @@ -98102,16 +106053,16 @@ var ts; if (!info) return; var typeNode = info.typeNode, type = info.type; - var fixedType = typeNode.kind === 277 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 4096 /* Undefined */) : type; + var fixedType = typeNode.kind === 284 /* JSDocNullableType */ && fixId === fixIdNullable ? checker.getNullableType(type, 8192 /* Undefined */) : type; doChange(changes, sourceFile, typeNode, fixedType, checker); }); } }); function doChange(changes, sourceFile, oldTypeNode, newType, checker) { - changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); + changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode(newType, /*enclosingDeclaration*/ oldTypeNode)); // TODO: GH#18217 } function getInfo(sourceFile, pos, checker) { - var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false), isTypeContainer); + var decl = ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), isTypeContainer); var typeNode = decl && decl.type; return typeNode && { typeNode: typeNode, type: checker.getTypeFromTypeNode(typeNode) }; } @@ -98119,22 +106070,22 @@ var ts; // NOTE: Some locations are not handled yet: // MappedTypeNode.typeParameters and SignatureDeclaration.typeParameters, as well as CallExpression.typeArguments switch (node.kind) { - case 206 /* AsExpression */: - case 157 /* CallSignature */: - case 158 /* ConstructSignature */: - case 232 /* FunctionDeclaration */: - case 155 /* GetAccessor */: - case 159 /* IndexSignature */: - case 176 /* MappedType */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 148 /* Parameter */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: - case 156 /* SetAccessor */: - case 235 /* TypeAliasDeclaration */: - case 188 /* TypeAssertionExpression */: - case 230 /* VariableDeclaration */: + case 210 /* AsExpression */: + case 158 /* CallSignature */: + case 159 /* ConstructSignature */: + case 237 /* FunctionDeclaration */: + case 156 /* GetAccessor */: + case 160 /* IndexSignature */: + case 179 /* MappedType */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 149 /* Parameter */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: + case 157 /* SetAccessor */: + case 240 /* TypeAliasDeclaration */: + case 192 /* TypeAssertionExpression */: + case 235 /* VariableDeclaration */: return true; default: return false; @@ -98160,7 +106111,7 @@ var ts; if (!nodes) return undefined; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, nodes); }); - return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_async_modifier_to_containing_function), changes: changes, fixId: fixId }]; + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { @@ -98181,24 +106132,27 @@ var ts; } } function getNodes(sourceFile, start) { - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var containingFunction = ts.getContainingFunction(token); + if (!containingFunction) { + return; + } var insertBefore; switch (containingFunction.kind) { - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: insertBefore = containingFunction.name; break; - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: insertBefore = ts.findChildOfKind(containingFunction, 89 /* FunctionKeyword */, sourceFile); break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: insertBefore = ts.findChildOfKind(containingFunction, 19 /* OpenParenToken */, sourceFile) || ts.first(containingFunction.parameters); break; default: return; } - return { + return insertBefore && { insertBefore: insertBefore, returnType: getReturnType(containingFunction) }; @@ -98220,708 +106174,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var ChangeTracker = ts.textChanges.ChangeTracker; - codefix.registerCodeFix({ - errorCodes: [ - ts.Diagnostics.Cannot_find_name_0.code, - ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, - ts.Diagnostics.Cannot_find_namespace_0.code, - ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ], - getCodeActions: getImportCodeActions, - // TODO: GH#20315 - fixIds: [], - getAllCodeActions: ts.notImplemented, - }); - function createCodeAction(descriptionDiagnostic, diagnosticArgs, changes) { - var description = ts.formatMessage.apply(undefined, [undefined, descriptionDiagnostic].concat(diagnosticArgs)); - // TODO: GH#20315 - return { description: description, changes: changes, fixId: undefined }; - } - function convertToImportCodeFixContext(context, symbolToken, symbolName) { - var useCaseSensitiveFileNames = context.host.useCaseSensitiveFileNames ? context.host.useCaseSensitiveFileNames() : false; - var program = context.program; - var checker = program.getTypeChecker(); - return { - host: context.host, - formatContext: context.formatContext, - sourceFile: context.sourceFile, - program: program, - checker: checker, - compilerOptions: program.getCompilerOptions(), - cachedImportDeclarations: [], - getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), - symbolName: symbolName, - symbolToken: symbolToken - }; - } - var ImportKind; - (function (ImportKind) { - ImportKind[ImportKind["Named"] = 0] = "Named"; - ImportKind[ImportKind["Default"] = 1] = "Default"; - ImportKind[ImportKind["Namespace"] = 2] = "Namespace"; - ImportKind[ImportKind["Equals"] = 3] = "Equals"; - })(ImportKind || (ImportKind = {})); - function getImportCompletionAction(exportedSymbol, moduleSymbol, sourceFile, symbolName, host, program, checker, compilerOptions, allSourceFiles, formatContext, getCanonicalFileName, symbolToken) { - var exportInfos = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); - ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol; })); - // We sort the best codefixes first, so taking `first` is best for completions. - var moduleSpecifier = ts.first(getNewImportInfos(program, sourceFile, exportInfos, compilerOptions, getCanonicalFileName, host)).moduleSpecifier; - var ctx = { host: host, program: program, checker: checker, compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, symbolName: symbolName, getCanonicalFileName: getCanonicalFileName, symbolToken: symbolToken }; - return { moduleSpecifier: moduleSpecifier, codeAction: ts.first(getCodeActionsForImport(exportInfos, ctx)) }; - } - codefix.getImportCompletionAction = getImportCompletionAction; - function getAllReExportingModules(exportedSymbol, checker, allSourceFiles) { - var result = []; - forEachExternalModule(checker, allSourceFiles, function (moduleSymbol) { - for (var _i = 0, _a = checker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { - var exported = _a[_i]; - if (ts.skipAlias(exported, checker) === exportedSymbol) { - var isDefaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol) === exported; - result.push({ moduleSymbol: moduleSymbol, importKind: isDefaultExport ? 1 /* Default */ : 0 /* Named */ }); - } - } - }); - return result; - } - function getCodeActionsForImport(exportInfos, context) { - var existingImports = ts.flatMap(exportInfos, function (info) { - return getImportDeclarations(info, context.checker, context.sourceFile, context.cachedImportDeclarations); - }); - // It is possible that multiple import statements with the same specifier exist in the file. - // e.g. - // - // import * as ns from "foo"; - // import { member1, member2 } from "foo"; - // - // member3/**/ <-- cusor here - // - // in this case we should provie 2 actions: - // 1. change "member3" to "ns.member3" - // 2. add "member3" to the second import statement's import list - // and it is up to the user to decide which one fits best. - var useExistingImportActions = !context.symbolToken || !ts.isIdentifier(context.symbolToken) ? ts.emptyArray : ts.mapDefined(existingImports, function (_a) { - var declaration = _a.declaration; - var namespace = getNamespaceImportName(declaration); - if (namespace) { - var moduleSymbol = context.checker.getAliasedSymbol(context.checker.getSymbolAtLocation(namespace)); - if (moduleSymbol && moduleSymbol.exports.has(ts.escapeLeadingUnderscores(context.symbolName))) { - return getCodeActionForUseExistingNamespaceImport(namespace.text, context, context.symbolToken); - } - } - }); - return useExistingImportActions.concat(getCodeActionsForAddImport(exportInfos, context, existingImports)); - } - function getNamespaceImportName(declaration) { - if (declaration.kind === 242 /* ImportDeclaration */) { - var namedBindings = declaration.importClause && ts.isImportClause(declaration.importClause) && declaration.importClause.namedBindings; - return namedBindings && namedBindings.kind === 244 /* NamespaceImport */ ? namedBindings.name : undefined; - } - else { - return declaration.name; - } - } - // TODO(anhans): This doesn't seem important to cache... just use an iterator instead of creating a new array? - function getImportDeclarations(_a, checker, _b, cachedImportDeclarations) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var imports = _b.imports; - if (cachedImportDeclarations === void 0) { cachedImportDeclarations = []; } - var moduleSymbolId = ts.getUniqueSymbolId(moduleSymbol, checker); - var cached = cachedImportDeclarations[moduleSymbolId]; - if (!cached) { - cached = cachedImportDeclarations[moduleSymbolId] = ts.mapDefined(imports, function (importModuleSpecifier) { - var declaration = checker.getSymbolAtLocation(importModuleSpecifier) === moduleSymbol ? getImportDeclaration(importModuleSpecifier) : undefined; - return declaration && { declaration: declaration, importKind: importKind }; - }); - } - return cached; - } - function getImportDeclaration(_a) { - var parent = _a.parent; - switch (parent.kind) { - case 242 /* ImportDeclaration */: - return parent; - case 252 /* ExternalModuleReference */: - return parent.parent; - case 248 /* ExportDeclaration */: - case 185 /* CallExpression */: // For "require()" calls - // Ignore these, can't add imports to them. - return undefined; - default: - ts.Debug.fail(); - } - } - function getCodeActionForNewImport(context, _a) { - var moduleSpecifier = _a.moduleSpecifier, importKind = _a.importKind; - var sourceFile = context.sourceFile, symbolName = context.symbolName; - var lastImportDeclaration = ts.findLast(sourceFile.statements, ts.isAnyImportSyntax); - var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - var quotedModuleSpecifier = createStringLiteralWithQuoteStyle(sourceFile, moduleSpecifierWithoutQuotes); - var importDecl = importKind !== 3 /* Equals */ - ? ts.createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, createImportClauseOfKind(importKind, symbolName), quotedModuleSpecifier) - : ts.createImportEqualsDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createIdentifier(symbolName), ts.createExternalModuleReference(quotedModuleSpecifier)); - var changes = ChangeTracker.with(context, function (changeTracker) { - if (lastImportDeclaration) { - changeTracker.insertNodeAfter(sourceFile, lastImportDeclaration, importDecl); - } - else { - changeTracker.insertNodeAtTopOfFile(sourceFile, importDecl, /*blankLineBetween*/ true); - } - }); - // if this file doesn't have any import statements, insert an import statement and then insert a new line - // between the only import statement and user code. Otherwise just insert the statement because chances - // are there are already a new line seperating code and import statements. - return createCodeAction(ts.Diagnostics.Import_0_from_module_1, [symbolName, moduleSpecifierWithoutQuotes], changes); - } - function createStringLiteralWithQuoteStyle(sourceFile, text) { - var literal = ts.createLiteral(text); - var firstModuleSpecifier = ts.firstOrUndefined(sourceFile.imports); - literal.singleQuote = !!firstModuleSpecifier && !ts.isStringDoubleQuoted(firstModuleSpecifier, sourceFile); - return literal; - } - function usesJsExtensionOnImports(sourceFile) { - return ts.firstDefined(sourceFile.imports, function (_a) { - var text = _a.text; - return ts.pathIsRelative(text) ? ts.fileExtensionIs(text, ".js" /* Js */) : undefined; - }) || false; - } - function createImportClauseOfKind(kind, symbolName) { - var id = ts.createIdentifier(symbolName); - switch (kind) { - case 1 /* Default */: - return ts.createImportClause(id, /*namedBindings*/ undefined); - case 2 /* Namespace */: - return ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(id)); - case 0 /* Named */: - return ts.createImportClause(/*name*/ undefined, ts.createNamedImports([ts.createImportSpecifier(/*propertyName*/ undefined, id)])); - default: - ts.Debug.assertNever(kind); - } - } - function getNewImportInfos(program, sourceFile, moduleSymbols, options, getCanonicalFileName, host) { - var baseUrl = options.baseUrl, paths = options.paths, rootDirs = options.rootDirs; - var addJsExtension = usesJsExtensionOnImports(sourceFile); - var choicesForEachExportingModule = ts.flatMap(moduleSymbols, function (_a) { - var moduleSymbol = _a.moduleSymbol, importKind = _a.importKind; - var modulePathsGroups = getAllModulePaths(program, moduleSymbol.valueDeclaration.getSourceFile()).map(function (moduleFileName) { - var sourceDirectory = ts.getDirectoryPath(sourceFile.fileName); - var global = tryGetModuleNameFromAmbientModule(moduleSymbol) - || tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) - || tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) - || rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName); - if (global) { - return [global]; - } - var relativePath = removeExtensionAndIndexPostFix(getRelativePath(moduleFileName, sourceDirectory, getCanonicalFileName), options, addJsExtension); - if (!baseUrl) { - return [relativePath]; - } - var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName); - if (!relativeToBaseUrl) { - return [relativePath]; - } - var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, options, addJsExtension); - if (paths) { - var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths); - if (fromPaths) { - return [fromPaths]; - } - } - if (isPathRelativeToParent(relativeToBaseUrl)) { - return [relativePath]; - } - /* - Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/a/b - moduleFileName = /base/foo/bar - Then: - relativePath = ../../foo/bar - getRelativePathNParents(relativePath) = 2 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 2 < 2 = false - In this case we should prefer using the baseUrl path "/a/b" instead of the relative path "../../foo/bar". - - Suppose we have: - baseUrl = /base - sourceDirectory = /base/foo/a - moduleFileName = /base/foo/bar - Then: - relativePath = ../a - getRelativePathNParents(relativePath) = 1 - pathFromSourceToBaseUrl = ../../ - getRelativePathNParents(pathFromSourceToBaseUrl) = 2 - 1 < 2 = true - In this case we should prefer using the relative path "../a" instead of the baseUrl path "foo/a". - */ - var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); - var relativeFirst = getRelativePathNParents(relativePath) < getRelativePathNParents(pathFromSourceToBaseUrl); - return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; - }); - return modulePathsGroups.map(function (group) { return group.map(function (moduleSpecifier) { return ({ moduleSpecifier: moduleSpecifier, importKind: importKind }); }); }); - }); - // Sort to keep the shortest paths first, but keep [relativePath, importRelativeToBaseUrl] groups together - return ts.flatten(choicesForEachExportingModule.sort(function (a, b) { return ts.first(a).moduleSpecifier.length - ts.first(b).moduleSpecifier.length; })); - } - /** - * Looks for a existing imports that use symlinks to this module. - * Only if no symlink is available, the real path will be used. - */ - function getAllModulePaths(program, _a) { - var fileName = _a.fileName; - var symlinks = ts.mapDefined(program.getSourceFiles(), function (sf) { - return sf.resolvedModules && ts.firstDefinedIterator(sf.resolvedModules.values(), function (res) { - return res && res.resolvedFileName === fileName ? res.originalPath : undefined; - }); - }); - return symlinks.length === 0 ? [fileName] : symlinks; - } - function getRelativePathNParents(relativePath) { - var count = 0; - for (var i = 0; i + 3 <= relativePath.length && relativePath.slice(i, i + 3) === "../"; i += 3) { - count++; - } - return count; - } - function tryGetModuleNameFromAmbientModule(moduleSymbol) { - var decl = moduleSymbol.valueDeclaration; - if (ts.isModuleDeclaration(decl) && ts.isStringLiteral(decl.name)) { - return decl.name.text; - } - } - function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { - for (var key in paths) { - for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var patternText_1 = _a[_i]; - var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); - var indexOfStar = pattern.indexOf("*"); - if (indexOfStar === 0 && pattern.length === 1) { - continue; - } - else if (indexOfStar !== -1) { - var prefix = pattern.substr(0, indexOfStar); - var suffix = pattern.substr(indexOfStar + 1); - if (relativeToBaseUrl.length >= prefix.length + suffix.length && - ts.startsWith(relativeToBaseUrl, prefix) && - ts.endsWith(relativeToBaseUrl, suffix)) { - var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); - return key.replace("*", matchedStar); - } - } - else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { - return key; - } - } - } - } - function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName) { - var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName); - if (normalizedTargetPath === undefined) { - return undefined; - } - var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName); - var relativePath = normalizedSourcePath !== undefined ? getRelativePath(normalizedTargetPath, normalizedSourcePath, getCanonicalFileName) : normalizedTargetPath; - return ts.removeFileExtension(relativePath); - } - function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { - var roots = ts.getEffectiveTypeRoots(options, host); - return ts.firstDefined(roots, function (unNormalizedTypeRoot) { - var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); - if (ts.startsWith(moduleFileName, typeRoot)) { - return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); - } - }); - } - function tryGetModuleNameAsNodeModule(options, moduleFileName, host, getCanonicalFileName, sourceDirectory) { - if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) { - // nothing to do here - return undefined; - } - var parts = getNodeModulePathParts(moduleFileName); - if (!parts) { - return undefined; - } - // Simplify the full file path to something that can be resolved by Node. - // If the module could be imported by a directory name, use that directory's name - var moduleSpecifier = getDirectoryOrExtensionlessFileName(moduleFileName); - // Get a path that's relative to node_modules or the importing file's path - moduleSpecifier = getNodeResolvablePath(moduleSpecifier); - // If the module was found in @types, get the actual Node package name - return ts.getPackageNameFromAtTypesDirectory(moduleSpecifier); - function getDirectoryOrExtensionlessFileName(path) { - // If the file is the main module, it can be imported by the package name - var packageRootPath = path.substring(0, parts.packageRootIndex); - var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - if (packageJsonContent) { - var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (mainExportFile === getCanonicalFileName(path)) { - return packageRootPath; - } - } - } - } - // We still have a file name - remove the extension - var fullModulePathWithoutExtension = ts.removeFileExtension(path); - // If the file is /index, it can be imported by its directory name - if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index") { - return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex); - } - return fullModulePathWithoutExtension; - } - function getNodeResolvablePath(path) { - var basePath = path.substring(0, parts.topLevelNodeModulesIndex); - if (sourceDirectory.indexOf(basePath) === 0) { - // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - return path.substring(parts.topLevelPackageNameIndex + 1); - } - else { - return getRelativePath(path, sourceDirectory, getCanonicalFileName); - } - } - } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // 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; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf("/node_modules/", partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } - function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); - return isPathRelativeToParent(relativePath) ? undefined : relativePath; - }); - } - function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { - var noExtension = ts.removeFileExtension(fileName); - return addJsExtension - ? noExtension + ".js" - : ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeJs - ? ts.removeSuffix(noExtension, "/index") - : noExtension; - } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; - } - function isPathRelativeToParent(path) { - return ts.startsWith(path, ".."); - } - function getRelativePath(path, directoryPath, getCanonicalFileName) { - var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return !ts.pathIsRelative(relativePath) ? "./" + relativePath : relativePath; - } - function getCodeActionsForAddImport(exportInfos, ctx, existingImports) { - var fromExistingImport = ts.firstDefined(existingImports, function (_a) { - var declaration = _a.declaration, importKind = _a.importKind; - if (declaration.kind === 242 /* ImportDeclaration */ && declaration.importClause) { - var changes = tryUpdateExistingImport(ctx, ts.isImportClause(declaration.importClause) && declaration.importClause || undefined, importKind); - if (changes) { - var moduleSpecifierWithoutQuotes = ts.stripQuotes(declaration.moduleSpecifier.getText()); - return createCodeAction(ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, [ctx.symbolName, moduleSpecifierWithoutQuotes], changes); - } - } - }); - if (fromExistingImport) { - return [fromExistingImport]; - } - var existingDeclaration = ts.firstDefined(existingImports, newImportInfoFromExistingSpecifier); - var newImportInfos = existingDeclaration - ? [existingDeclaration] - : getNewImportInfos(ctx.program, ctx.sourceFile, exportInfos, ctx.compilerOptions, ctx.getCanonicalFileName, ctx.host); - return newImportInfos.map(function (info) { return getCodeActionForNewImport(ctx, info); }); - } - function newImportInfoFromExistingSpecifier(_a) { - var declaration = _a.declaration, importKind = _a.importKind; - var expression = declaration.kind === 242 /* ImportDeclaration */ - ? declaration.moduleSpecifier - : declaration.moduleReference.kind === 252 /* ExternalModuleReference */ - ? declaration.moduleReference.expression - : undefined; - return expression && ts.isStringLiteral(expression) ? { moduleSpecifier: expression.text, importKind: importKind } : undefined; - } - function tryUpdateExistingImport(context, importClause, importKind) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - var name = importClause.name; - var namedBindings = (importClause.kind !== 241 /* ImportEqualsDeclaration */ && importClause).namedBindings; - switch (importKind) { - case 1 /* Default */: - return name ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(ts.createIdentifier(symbolName), namedBindings)); - }); - case 0 /* Named */: { - var newImportSpecifier_1 = ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(symbolName)); - if (namedBindings && namedBindings.kind === 245 /* NamedImports */ && namedBindings.elements.length !== 0) { - // There are already named imports; add another. - return ChangeTracker.with(context, function (t) { return t.insertNodeInListAfter(sourceFile, namedBindings.elements[namedBindings.elements.length - 1], newImportSpecifier_1); }); - } - if (!namedBindings || namedBindings.kind === 245 /* NamedImports */ && namedBindings.elements.length === 0) { - return ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamedImports([newImportSpecifier_1]))); - }); - } - return undefined; - } - case 2 /* Namespace */: - return namedBindings ? undefined : ChangeTracker.with(context, function (t) { - return t.replaceNode(sourceFile, importClause, ts.createImportClause(name, ts.createNamespaceImport(ts.createIdentifier(symbolName)))); - }); - case 3 /* Equals */: - return undefined; - default: - ts.Debug.assertNever(importKind); - } - } - function getCodeActionForUseExistingNamespaceImport(namespacePrefix, context, symbolToken) { - var symbolName = context.symbolName, sourceFile = context.sourceFile; - /** - * Cases: - * import * as ns from "mod" - * import default, * as ns from "mod" - * import ns = require("mod") - * - * Because there is no import list, we alter the reference to include the - * namespace instead of altering the import declaration. For example, "foo" would - * become "ns.foo" - */ - var changes = ChangeTracker.with(context, function (tracker) { - return tracker.replaceNode(sourceFile, symbolToken, ts.createPropertyAccess(ts.createIdentifier(namespacePrefix), symbolToken)); - }); - return createCodeAction(ts.Diagnostics.Change_0_to_1, [symbolName, namespacePrefix + "." + symbolName], changes); - } - function getImportCodeActions(context) { - return context.errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getActionsForUMDImport(context) - : getActionsForNonUMDImport(context); - } - function getActionsForUMDImport(context) { - var token = ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false); - var checker = context.program.getTypeChecker(); - var umdSymbol; - if (ts.isIdentifier(token)) { - // try the identifier to see if it is the umd symbol - umdSymbol = checker.getSymbolAtLocation(token); - } - if (!ts.isUMDExportSymbol(umdSymbol)) { - // The error wasn't for the symbolAtLocation, it was for the JSX tag itself, which needs access to e.g. `React`. - var parent = token.parent; - var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(parent); - if ((ts.isJsxOpeningLikeElement && parent.tagName === token) || parent.kind === 258 /* JsxOpeningFragment */) { - umdSymbol = checker.resolveName(checker.getJsxNamespace(parent), isNodeOpeningLikeElement ? parent.tagName : parent, 67216319 /* Value */, /*excludeGlobals*/ false); - } - } - if (ts.isUMDExportSymbol(umdSymbol)) { - var symbol = checker.getAliasedSymbol(umdSymbol); - if (symbol) { - return getCodeActionsForImport([{ moduleSymbol: symbol, importKind: getUmdImportKind(context.program.getCompilerOptions()) }], convertToImportCodeFixContext(context, token, umdSymbol.name)); - } - } - return undefined; - } - function getUmdImportKind(compilerOptions) { - // Import a synthetic `default` if enabled. - if (ts.getAllowSyntheticDefaultImports(compilerOptions)) { - return 1 /* Default */; - } - // When a synthetic `default` is unavailable, use `import..require` if the module kind supports it. - var moduleKind = ts.getEmitModuleKind(compilerOptions); - switch (moduleKind) { - case ts.ModuleKind.AMD: - case ts.ModuleKind.CommonJS: - case ts.ModuleKind.UMD: - return 3 /* Equals */; - case ts.ModuleKind.System: - case ts.ModuleKind.ES2015: - case ts.ModuleKind.ESNext: - case ts.ModuleKind.None: - // Fall back to the `import * as ns` style import. - return 2 /* Namespace */; - default: - return ts.Debug.assertNever(moduleKind); - } - } - function getActionsForNonUMDImport(context) { - // This will always be an Identifier, since the diagnostics we fix only fail on identifiers. - var sourceFile = context.sourceFile, span = context.span, program = context.program, cancellationToken = context.cancellationToken; - var checker = program.getTypeChecker(); - var symbolToken = ts.getTokenAtPosition(sourceFile, span.start, /*includeJsDocComment*/ false); - var isJsxNamespace = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken; - if (!isJsxNamespace && !ts.isIdentifier(symbolToken)) { - return undefined; - } - var symbolName = isJsxNamespace ? checker.getJsxNamespace() : symbolToken.text; - var allSourceFiles = program.getSourceFiles(); - var compilerOptions = program.getCompilerOptions(); - // "default" is a keyword and not a legal identifier for the import, so we don't expect it here - ts.Debug.assert(symbolName !== "default"); - var currentTokenMeaning = ts.getMeaningFromLocation(symbolToken); - // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. - // Maps symbol id to info for modules providing that symbol (original export + re-exports). - var originalSymbolToExportInfos = ts.createMultiMap(); - function addSymbol(moduleSymbol, exportedSymbol, importKind) { - originalSymbolToExportInfos.add(ts.getUniqueSymbolId(exportedSymbol, checker).toString(), { moduleSymbol: moduleSymbol, importKind: importKind }); - } - forEachExternalModuleToImportFrom(checker, sourceFile, allSourceFiles, function (moduleSymbol) { - cancellationToken.throwIfCancellationRequested(); - // check the default export - var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) { - var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || - getEscapedNameForExportDefault(defaultExport) === symbolName || - moduleSymbolToValidIdentifier(moduleSymbol, compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { - addSymbol(moduleSymbol, localSymbol || defaultExport, 1 /* Default */); - } - } - // check exports with the same name - var exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName, moduleSymbol); - if (exportSymbolWithIdenticalName && checkSymbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { - addSymbol(moduleSymbol, exportSymbolWithIdenticalName, 0 /* Named */); - } - function getEscapedNameForExportDefault(symbol) { - return ts.firstDefined(symbol.declarations, function (declaration) { - if (ts.isExportAssignment(declaration)) { - if (ts.isIdentifier(declaration.expression)) { - return declaration.expression.escapedText; - } - } - else if (ts.isExportSpecifier(declaration)) { - ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); - if (declaration.propertyName) { - return declaration.propertyName.escapedText; - } - } - }); - } - }); - return ts.arrayFrom(ts.flatMapIterator(originalSymbolToExportInfos.values(), function (exportInfos) { return getCodeActionsForImport(exportInfos, convertToImportCodeFixContext(context, symbolToken, symbolName)); })); - } - function checkSymbolHasMeaning(_a, meaning) { - var declarations = _a.declarations; - return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); - } - function forEachExternalModuleToImportFrom(checker, from, allSourceFiles, cb) { - forEachExternalModule(checker, allSourceFiles, function (module, sourceFile) { - if (sourceFile === undefined || sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { - cb(module); - } - }); - } - codefix.forEachExternalModuleToImportFrom = forEachExternalModuleToImportFrom; - function forEachExternalModule(checker, allSourceFiles, cb) { - for (var _i = 0, _a = checker.getAmbientModules(); _i < _a.length; _i++) { - var ambient = _a[_i]; - cb(ambient, /*sourceFile*/ undefined); - } - for (var _b = 0, allSourceFiles_1 = allSourceFiles; _b < allSourceFiles_1.length; _b++) { - var sourceFile = allSourceFiles_1[_b]; - if (ts.isExternalOrCommonJsModule(sourceFile)) { - cb(sourceFile.symbol, sourceFile); - } - } - } - /** - * Don't include something from a `node_modules` that isn't actually reachable by a global import. - * A relative import to node_modules is usually a bad idea. - */ - function isImportablePath(fromPath, toPath) { - // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. - var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); - } - function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.getBaseFileName(moduleSymbol.name)), target); - } - codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; - function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { - var res = ""; - var lastCharWasValid = true; - var firstCharCode = moduleSpecifier.charCodeAt(0); - if (ts.isIdentifierStart(firstCharCode, target)) { - res += String.fromCharCode(firstCharCode); - } - else { - lastCharWasValid = false; - } - for (var i = 1; i < moduleSpecifier.length; i++) { - var ch = moduleSpecifier.charCodeAt(i); - var isValid = ts.isIdentifierPart(ch, target); - if (isValid) { - var char = String.fromCharCode(ch); - if (!lastCharWasValid) { - char = char.toUpperCase(); - } - res += char; - } - lastCharWasValid = isValid; - } - // Need `|| "_"` to ensure result isn't empty. - return !ts.isStringANonContextualKeyword(res) ? res || "_" : "_" + res; - } - codefix.moduleSpecifierToValidIdentifier = moduleSpecifierToValidIdentifier; - })(codefix = ts.codefix || (ts.codefix = {})); -})(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - var codefix; - (function (codefix) { + var fixName = "disableJsDiagnostics"; var fixId = "disableJsDiagnostics"; var errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics), function (key) { var diag = ts.Diagnostics[key]; @@ -98935,23 +106188,15 @@ var ts; return undefined; } var fixes = [ - { - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Disable_checking_for_this_file), - changes: [codefix.createFileTextChanges(sourceFile.fileName, [ - ts.createTextChange(sourceFile.checkJsDirective - ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) - : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), - ])], - // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - fixId: undefined, - } + // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. + codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + ts.createTextChange(sourceFile.checkJsDirective + ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) + : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), + ])], ts.Diagnostics.Disable_checking_for_this_file), ]; - if (isValidSuppressLocation(sourceFile, span.start)) { - fixes.unshift({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), - fixId: fixId, - }); + if (ts.textChanges.isValidLocationToAddComment(sourceFile, span.start)) { + fixes.unshift(codefix.createCodeFixAction(fixName, ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, sourceFile, span.start); }), ts.Diagnostics.Ignore_this_error_message, fixId, ts.Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; }, @@ -98959,32 +106204,18 @@ var ts; getAllCodeActions: function (context) { var seenLines = ts.createMap(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - if (isValidSuppressLocation(diag.file, diag.start)) { + if (ts.textChanges.isValidLocationToAddComment(diag.file, diag.start)) { makeChange(changes, diag.file, diag.start, seenLines); } }); }, }); - function isValidSuppressLocation(sourceFile, position) { - return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position); - } function makeChange(changes, sourceFile, position, seenLines) { var lineNumber = ts.getLineAndCharacterOfPosition(sourceFile, position).line; // Only need to add `// @ts-ignore` for a line once. - if (seenLines && !ts.addToSeen(seenLines, lineNumber)) { - return; + if (!seenLines || ts.addToSeen(seenLines, lineNumber)) { + changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } - var lineStartPosition = ts.getStartPositionOfLine(lineNumber, sourceFile); - var startPosition = ts.getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); - // First try to see if we can put the '// @ts-ignore' on the previous line. - // We need to make sure that we are not in the middle of a string literal or a comment. - // If so, we do not want to separate the node from its comment if we can. - // Otherwise, add an extra new line immediately before the error span. - var insertAtLineStart = isValidSuppressLocation(sourceFile, startPosition); - var token = ts.getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position, /*includeJsDocComment*/ false); - var clone = ts.setStartsOnNewLine(ts.getSynthesizedDeepClone(token), true); - ts.addSyntheticLeadingComment(clone, 2 /* SingleLineCommentTrivia */, " @ts-ignore"); - changes.replaceNode(sourceFile, token, clone, { preserveLeadingWhitespace: true, prefix: insertAtLineStart ? undefined : changes.newLineCharacter }); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -98999,12 +106230,12 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); } } } @@ -99012,30 +106243,29 @@ var ts; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } var declaration = declarations[0]; - // Clone name to remove leading trivia. - var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration)); + var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); var optional = !!(symbol.flags & 16777216 /* Optional */); switch (declaration.kind) { - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 150 /* PropertySignature */: - case 151 /* PropertyDeclaration */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 151 /* PropertySignature */: + case 152 /* PropertyDeclaration */: var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); break; - case 152 /* MethodSignature */: - case 153 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 154 /* MethodDeclaration */: // The signature for the implementation appears as an entry in `signatures` iff // there is only one signature. // If there are overloads and an implementation signature, it appears as an @@ -99050,21 +106280,21 @@ var ts; if (declarations.length === 1) { ts.Debug.assert(signatures.length === 1); var signature = signatures[0]; - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); break; } for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. - outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); + outputMethod(signature, ts.getSynthesizedDeepClones(modifiers, /*includeTrivia*/ false), ts.getSynthesizedDeepClone(name, /*includeTrivia*/ false)); } if (declarations.length > signatures.length) { var signature = checker.getSignatureFromDeclaration(declarations[declarations.length - 1]); - outputMethod(signature, modifiers, name, createStubbedMethodBody()); + outputMethod(signature, modifiers, name, createStubbedMethodBody(preferences)); } else { ts.Debug.assert(declarations.length === signatures.length); - out(createMethodImplementingSignatures(signatures, name, optional, modifiers)); + out(createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences)); } break; } @@ -99075,7 +106305,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 153 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 154 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } @@ -99086,24 +106316,35 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function getSynthesizedDeepClones(nodes) { - return nodes && ts.createNodeArray(nodes.map(ts.getSynthesizedDeepClone)); - } - function createMethodFromCallExpression(_a, methodName, inJs, makeStatic) { - var typeArguments = _a.typeArguments, args = _a.arguments; + function createMethodFromCallExpression(context, _a, methodName, inJs, makeStatic, preferences) { + var typeArguments = _a.typeArguments, args = _a.arguments, parent = _a.parent; + var checker = context.program.getTypeChecker(); + var types = ts.map(args, function (arg) { + var type = checker.getTypeAtLocation(arg); + if (type === undefined) { + return undefined; + } + // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" + type = checker.getBaseTypeOfLiteralType(type); + return checker.typeToTypeNode(type); + }); + var names = ts.map(args, function (arg) { + return ts.isIdentifier(arg) ? arg.text : + ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; + }); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(115 /* StaticKeyword */)] : undefined, - /*asteriskToken*/ undefined, methodName, + /*asteriskToken*/ ts.isYieldExpression(parent) ? ts.createToken(39 /* AsteriskToken */) : undefined, methodName, /*questionToken*/ undefined, /*typeParameters*/ inJs ? undefined : ts.map(typeArguments, function (_, i) { return ts.createTypeParameterDeclaration(84 /* T */ + typeArguments.length - 1 <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + i) : "T" + i); }), - /*parameters*/ createDummyParameters(args.length, /*names*/ undefined, /*minArgumentCount*/ undefined, inJs), - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody()); + /*parameters*/ createDummyParameters(args.length, names, types, /*minArgumentCount*/ undefined, inJs), + /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), createStubbedMethodBody(preferences)); } codefix.createMethodFromCallExpression = createMethodFromCallExpression; - function createDummyParameters(argCount, names, minArgumentCount, inJs) { + function createDummyParameters(argCount, names, types, minArgumentCount, inJs) { var parameters = []; for (var i = 0; i < argCount; i++) { var newParameter = ts.createParameter( @@ -99112,13 +106353,13 @@ var ts; /*dotDotDotToken*/ undefined, /*name*/ names && names[i] || "arg" + i, /*questionToken*/ minArgumentCount !== undefined && i >= minArgumentCount ? ts.createToken(55 /* QuestionToken */) : undefined, - /*type*/ inJs ? undefined : ts.createKeywordTypeNode(119 /* AnyKeyword */), + /*type*/ inJs ? undefined : types && types[i] || ts.createKeywordTypeNode(119 /* AnyKeyword */), /*initializer*/ undefined); parameters.push(newParameter); } return parameters; } - function createMethodImplementingSignatures(signatures, name, optional, modifiers) { + function createMethodImplementingSignatures(signatures, name, optional, modifiers, preferences) { /** This is *a* signature with the maximal number of arguments, * such that if there is a "maximal" signature without rest arguments, * this is one of them. @@ -99138,7 +106379,7 @@ var ts; } var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); - var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, minArgumentCount, /*inJs*/ false); + var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { var anyArrayType = ts.createArrayTypeNode(ts.createKeywordTypeNode(119 /* AnyKeyword */)); var restParameter = ts.createParameter( @@ -99150,16 +106391,16 @@ var ts; } return createStubbedMethod(modifiers, name, optional, /*typeParameters*/ undefined, parameters, - /*returnType*/ undefined); + /*returnType*/ undefined, preferences); } - function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType) { + function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, preferences) { return ts.createMethod( /*decorators*/ undefined, modifiers, - /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody()); + /*asteriskToken*/ undefined, name, optional ? ts.createToken(55 /* QuestionToken */) : undefined, typeParameters, parameters, returnType, createStubbedMethodBody(preferences)); } - function createStubbedMethodBody() { + function createStubbedMethodBody(preferences) { return ts.createBlock([ts.createThrow(ts.createNew(ts.createIdentifier("Error"), - /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.")]))], + /*typeArguments*/ undefined, [ts.createLiteral("Method not implemented.", /*isSingleQuote*/ preferences.quotePreference === "single")]))], /*multiline*/ true); } function createVisibilityModifier(flags) { @@ -99202,50 +106443,53 @@ var ts; if (ts.isSourceFileJavaScript(sourceFile)) { return undefined; // TODO: GH#20113 } - var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken); }); - if (changes.length === 0) - return undefined; - var name = ts.getNameOfDeclaration(declaration).getText(); - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(getDiagnostic(errorCode, token)), [name]); - return [{ description: description, changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeenseen*/ ts.returnTrue); }); + var name = declaration && ts.getNameOfDeclaration(declaration); + return !name || changes.length === 0 ? undefined + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken; - var seenFunctions = ts.createMap(); + var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start, /*includeJsDocComment*/ false), err.code, program, cancellationToken, seenFunctions); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen); }); }, }); function getDiagnostic(errorCode, token) { switch (errorCode) { case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: - return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; + return ts.isSetAccessor(ts.getContainingFunction(token)) ? ts.Diagnostics.Infer_type_of_0_from_usage : ts.Diagnostics.Infer_parameter_types_from_usage; // TODO: GH#18217 case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: return ts.Diagnostics.Infer_parameter_types_from_usage; default: return ts.Diagnostics.Infer_type_of_0_from_usage; } } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, seenFunctions) { - if (!isAllowedTokenKind(token.kind)) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen) { + if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 71 /* Identifier */ && token.kind !== 24 /* DotDotDotToken */) { return undefined; } + var parent = token.parent; switch (errorCode) { // Variable and Property declarations case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: - annotateVariableDeclaration(changes, sourceFile, token.parent, program, cancellationToken); - return token.parent; + if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location + annotateVariableDeclaration(changes, sourceFile, parent, program, cancellationToken); + return parent; + } + return undefined; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); - if (symbol && symbol.valueDeclaration) { + if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, cancellationToken); return symbol.valueDeclaration; } + return undefined; } } var containingFunction = ts.getContainingFunction(token); @@ -99261,8 +106505,8 @@ var ts; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: - if (!seenFunctions || ts.addToSeen(seenFunctions, ts.getNodeId(containingFunction))) { - var param = ts.cast(token.parent, ts.isParameter); + if (markSeen(containingFunction)) { + var param = ts.cast(parent, ts.isParameter); annotateParameters(changes, param, containingFunction, sourceFile, program, cancellationToken); return param; } @@ -99286,19 +106530,6 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function isAllowedTokenKind(kind) { - switch (kind) { - case 71 /* Identifier */: - case 24 /* DotDotDotToken */: - case 114 /* PublicKeyword */: - case 112 /* PrivateKeyword */: - case 113 /* ProtectedKeyword */: - case 132 /* ReadonlyKeyword */: - return true; - default: - return false; - } - } function annotateVariableDeclaration(changes, sourceFile, declaration, program, cancellationToken) { if (ts.isIdentifier(declaration.name)) { annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program); @@ -99306,11 +106537,11 @@ var ts; } function isApplicableFunctionForInference(declaration) { switch (declaration.kind) { - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 154 /* Constructor */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 155 /* Constructor */: return true; - case 190 /* FunctionExpression */: + case 194 /* FunctionExpression */: return !!declaration.name; } return false; @@ -99342,13 +106573,14 @@ var ts; function annotate(changes, sourceFile, declaration, type, program) { var typeNode = type && getTypeNodeIfAccessible(type, declaration, program.getTypeChecker()); if (typeNode) - changes.insertTypeAnnotation(sourceFile, declaration, typeNode); + changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } function getTypeNodeIfAccessible(type, enclosingScope, checker) { var typeIsAccessible = true; var notAccessible = function () { typeIsAccessible = false; }; var res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { trackSymbol: function (symbol, declaration, meaning) { + // TODO: GH#18217 typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning, /*shouldComputeAliasToMarkVisible*/ false).accessibility === 0 /* Accessible */; }, reportInaccessibleThisError: notAccessible, @@ -99368,11 +106600,11 @@ var ts; } function inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) { switch (containingFunction.kind) { - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - var isConstructor = containingFunction.kind === 154 /* Constructor */; + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + var isConstructor = containingFunction.kind === 155 /* Constructor */; var searchToken = isConstructor ? ts.findChildOfKind(containingFunction, 123 /* ConstructorKeyword */, sourceFile) : containingFunction.name; @@ -99406,7 +106638,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); inferTypeFromContext(reference, checker, usageContext); } - var isConstructor = declaration.kind === 154 /* Constructor */; + var isConstructor = declaration.kind === 155 /* Constructor */; var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map(function (parameter, parameterIndex) { var types = []; @@ -99438,21 +106670,21 @@ var ts; node = node.parent; } switch (node.parent.kind) { - case 197 /* PostfixUnaryExpression */: + case 201 /* PostfixUnaryExpression */: usageContext.isNumber = true; break; - case 196 /* PrefixUnaryExpression */: + case 200 /* PrefixUnaryExpression */: inferTypeFromPrefixUnaryExpressionContext(node.parent, usageContext); break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: inferTypeFromBinaryExpressionContext(node, node.parent, checker, usageContext); break; - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: inferTypeFromSwitchStatementLabelContext(node.parent, checker, usageContext); break; - case 185 /* CallExpression */: - case 186 /* NewExpression */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: if (node.parent.expression === node) { inferTypeFromCallExpressionContext(node.parent, checker, usageContext); } @@ -99460,12 +106692,22 @@ var ts; inferTypeFromContextualType(node, checker, usageContext); } break; - case 183 /* PropertyAccessExpression */: + case 187 /* PropertyAccessExpression */: inferTypeFromPropertyAccessExpressionContext(node.parent, checker, usageContext); break; - case 184 /* ElementAccessExpression */: + case 188 /* ElementAccessExpression */: inferTypeFromPropertyElementExpressionContext(node.parent, node, checker, usageContext); break; + case 235 /* VariableDeclaration */: { + var _a = node.parent, name = _a.name, initializer = _a.initializer; + if (node === name) { + if (initializer) { // This can happen for `let x = null;` which still has an implicit-any error. + addCandidateType(usageContext, checker.getTypeAtLocation(initializer)); + } + break; + } + } + // falls through default: return inferTypeFromContextualType(node, checker, usageContext); } @@ -99526,7 +106768,7 @@ var ts; case 29 /* GreaterThanToken */: case 31 /* GreaterThanEqualsToken */: var operandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (operandType.flags & 272 /* EnumLike */) { + if (operandType.flags & 544 /* EnumLike */) { addCandidateType(usageContext, operandType); } else { @@ -99536,13 +106778,13 @@ var ts; case 59 /* PlusEqualsToken */: case 37 /* PlusToken */: var otherOperandType = checker.getTypeAtLocation(parent.left === node ? parent.right : parent.left); - if (otherOperandType.flags & 272 /* EnumLike */) { + if (otherOperandType.flags & 544 /* EnumLike */) { addCandidateType(usageContext, otherOperandType); } - else if (otherOperandType.flags & 84 /* NumberLike */) { + else if (otherOperandType.flags & 168 /* NumberLike */) { usageContext.isNumber = true; } - else if (otherOperandType.flags & 524322 /* StringLike */) { + else if (otherOperandType.flags & 68 /* StringLike */) { usageContext.isString = true; } else { @@ -99565,7 +106807,7 @@ var ts; // LogicalOperator case 54 /* BarBarToken */: if (node === parent.left && - (node.parent.parent.kind === 230 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { + (node.parent.parent.kind === 235 /* VariableDeclaration */ || ts.isAssignmentExpression(node.parent.parent, /*excludeCompoundAssignment*/ true))) { // var x = x || {}; // TODO: use getFalsyflagsOfType addCandidateType(usageContext, checker.getTypeAtLocation(parent.right)); @@ -99593,7 +106835,7 @@ var ts; } } inferTypeFromContext(parent, checker, callContext.returnType); - if (parent.kind === 185 /* CallExpression */) { + if (parent.kind === 189 /* CallExpression */) { (usageContext.callContexts || (usageContext.callContexts = [])).push(callContext); } else { @@ -99618,7 +106860,7 @@ var ts; var indexType = checker.getTypeAtLocation(parent); var indexUsageContext = {}; inferTypeFromContext(parent, checker, indexUsageContext); - if (indexType.flags & 84 /* NumberLike */) { + if (indexType.flags & 168 /* NumberLike */) { usageContext.numberIndexContext = indexUsageContext; } else { @@ -99637,10 +106879,10 @@ var ts; return checker.getStringType(); } else if (usageContext.candidateTypes) { - return checker.getWidenedType(checker.getUnionType(ts.map(usageContext.candidateTypes, function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); + return checker.getWidenedType(checker.getUnionType(usageContext.candidateTypes.map(function (t) { return checker.getBaseTypeOfLiteralType(t); }), 2 /* Subtype */)); } else if (usageContext.properties && hasCallContext(usageContext.properties.get("then"))) { - var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); + var paramType = getParameterTypeFromCallContexts(0, usageContext.properties.get("then").callContexts, /*isRestParameter*/ false, checker); // TODO: GH#18217 var types = paramType.getCallSignatures().map(function (c) { return c.getReturnType(); }); return checker.createPromiseType(types.length ? checker.getUnionType(types, 2 /* Subtype */) : checker.getAnyType()); } @@ -99648,7 +106890,7 @@ var ts; return checker.createArrayType(getParameterTypeFromCallContexts(0, usageContext.properties.get("push").callContexts, /*isRestParameter*/ false, checker)); } else if (usageContext.properties || usageContext.callContexts || usageContext.constructContexts || usageContext.numberIndexContext || usageContext.stringIndexContext) { - var members_5 = ts.createUnderscoreEscapedMap(); + var members_6 = ts.createUnderscoreEscapedMap(); var callSignatures = []; var constructSignatures = []; var stringIndexInfo = void 0; @@ -99657,7 +106899,7 @@ var ts; usageContext.properties.forEach(function (context, name) { var symbol = checker.createSymbol(4 /* Property */, name); symbol.type = getTypeFromUsageContext(context, checker) || checker.getAnyType(); - members_5.set(name, symbol); + members_6.set(name, symbol); }); } if (usageContext.callContexts) { @@ -99673,12 +106915,12 @@ var ts; } } if (usageContext.numberIndexContext) { - numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); + numberIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.numberIndexContext, checker), /*isReadonly*/ false); // TODO: GH#18217 } if (usageContext.stringIndexContext) { stringIndexInfo = checker.createIndexInfo(getTypeFromUsageContext(usageContext.stringIndexContext, checker), /*isReadonly*/ false); } - return checker.createAnonymousType(/*symbol*/ undefined, members_5, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); + return checker.createAnonymousType(/*symbol*/ undefined, members_6, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); // TODO: GH#18217 } else { return undefined; @@ -99713,15 +106955,16 @@ var ts; parameters.push(symbol); } var returnType = getTypeFromUsageContext(callContext.returnType, checker) || checker.getVoidType(); + // TODO: GH#18217 return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, callContext.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); } function addCandidateType(context, type) { - if (type && !(type.flags & 1 /* Any */) && !(type.flags & 16384 /* Never */)) { + if (type && !(type.flags & 1 /* Any */) && !(type.flags & 32768 /* Never */)) { (context.candidateTypes || (context.candidateTypes = [])).push(type); } } function hasCallContext(usageContext) { - return usageContext && usageContext.callContexts; + return !!usageContext && !!usageContext.callContexts; } })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); @@ -99731,29 +106974,14 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.registerCodeFix({ - errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], - getCodeActions: getActionsForInvalidImport - }); - function getActionsForInvalidImport(context) { - var sourceFile = context.sourceFile; - // This is the whole import statement, eg: - // import * as Bluebird from 'bluebird'; - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; - if (!ts.isImportDeclaration(node)) { - // No import quick fix for import calls - return []; - } - return getCodeFixesForImportDeclaration(context, node); - } + var fixName = "invalidImportSyntax"; function getCodeFixesForImportDeclaration(context, node) { var sourceFile = ts.getSourceFileOfNode(node); var namespace = ts.getNamespaceDeclarationNode(node); var opts = context.program.getCompilerOptions(); var variations = []; // import Bluebird from "bluebird"; - variations.push(createAction(context, sourceFile, node, codefix.makeImportDeclaration(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier))); + variations.push(createAction(context, sourceFile, node, ts.makeImport(namespace.name, /*namedImports*/ undefined, node.moduleSpecifier, ts.getQuotePreference(sourceFile, context.preferences)))); if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { // import Bluebird = require("bluebird"); variations.push(createAction(context, sourceFile, node, ts.createImportEqualsDeclaration( @@ -99763,12 +106991,8 @@ var ts; return variations; } function createAction(context, sourceFile, node, replacement) { - // TODO: GH#21246 Should be able to use `replaceNode`, but be sure to preserve comments (see `codeFixCalledES2015Import11.ts`) - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceRange(sourceFile, { pos: node.getStart(), end: node.end }, replacement); }); - return { - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), - changes: changes, - }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); + return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -99779,25 +107003,55 @@ var ts; }); function getActionsForUsageOfInvalidImport(context) { var sourceFile = context.sourceFile; - var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 185 /* CallExpression */ : 186 /* NewExpression */; - var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 189 /* CallExpression */ : 190 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); if (!node) { return []; } var expr = node.expression; + return getImportCodeFixesForExpression(context, expr); + } + codefix.registerCodeFix({ + errorCodes: [ + // The following error codes cover pretty much all assignability errors that could involve an expression + ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code, + ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1.code, + ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated.code, + ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2.code, + ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2.code, + ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2.code, + ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_type_2.code, + ts.Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property.code, + ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1.code, + ], + getCodeActions: getActionsForInvalidImportLocation + }); + function getActionsForInvalidImportLocation(context) { + var sourceFile = context.sourceFile; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start), function (a) { return a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + return getImportCodeFixesForExpression(context, node); + } + function getImportCodeFixesForExpression(context, expr) { var type = context.program.getTypeChecker().getTypeAtLocation(expr); if (!(type.symbol && type.symbol.originatingImport)) { return []; } var fixes = []; - var relatedImport = type.symbol.originatingImport; + var relatedImport = type.symbol.originatingImport; // TODO: GH#18217 if (!ts.isImportCall(relatedImport)) { ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); } - fixes.push({ - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), - changes: ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, expr, ts.createPropertyAccess(expr, "default"), {}); }), - }); + if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { + var sourceFile_3 = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_3, expr, ts.createPropertyAccess(expr, "default"), {}); }); + fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + } return fixes; } })(codefix = ts.codefix || (ts.codefix = {})); @@ -99807,6 +107061,7 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var fixName = "strictClassInitialization"; var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; var fixIdAddInitializer = "addMissingPropertyInitializer"; @@ -99817,24 +107072,22 @@ var ts; var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); if (!propertyDeclaration) return; - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); var result = [ getActionForAddMissingUndefinedType(context, propertyDeclaration), - getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) + getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) ]; - ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter)); + ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: function (context) { - var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); if (!propertyDeclaration) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration, newLineCharacter); + addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); break; case fixIdAddUndefinedType: addUndefinedType(changes, diag.file, propertyDeclaration); @@ -99844,7 +107097,7 @@ var ts; var initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return; - addInitializer(changes, diag.file, propertyDeclaration, initializer, newLineCharacter); + addInitializer(changes, diag.file, propertyDeclaration, initializer); break; default: ts.Debug.fail(JSON.stringify(context.fixId)); @@ -99853,75 +107106,101 @@ var ts; }, }); function getPropertyDeclaration(sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var token = ts.getTokenAtPosition(sourceFile, pos); return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; } - function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration, newLineCharacter) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_definite_assignment_assertion_to_property_0), [propertyDeclaration.getText()]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration, newLineCharacter); }); - return { description: description, changes: changes, fixId: fixIdAddDefiniteAssignmentAssertions }; + function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } - function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, newLineCharacter) { + function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.createToken(51 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getActionForAddMissingUndefinedType(context, propertyDeclaration) { - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_undefined_type_to_property_0), [propertyDeclaration.name.getText()]); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); - return { description: description, changes: changes, fixId: fixIdAddUndefinedType }; + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var undefinedTypeNode = ts.createKeywordTypeNode(140 /* UndefinedKeyword */); - var types = ts.isUnionTypeNode(propertyDeclaration.type) ? propertyDeclaration.type.types.concat(undefinedTypeNode) : [propertyDeclaration.type, undefinedTypeNode]; - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration.type, ts.createUnionTypeNode(types)); + var type = propertyDeclaration.type; // TODO: GH#18217 + var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; + changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.createUnionTypeNode(types)); } - function getActionForAddMissingInitializer(context, propertyDeclaration, newLineCharacter) { + function getActionForAddMissingInitializer(context, propertyDeclaration) { var checker = context.program.getTypeChecker(); var initializer = getInitializer(checker, propertyDeclaration); if (!initializer) return undefined; - var description = ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Add_initializer_to_property_0), [propertyDeclaration.name.getText()]); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer, newLineCharacter); }); - return { description: description, changes: changes, fixId: fixIdAddInitializer }; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); } - function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer, newLineCharacter) { + function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { var property = ts.updateProperty(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); - changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property, { suffix: newLineCharacter }); + changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } function getInitializer(checker, propertyDeclaration) { - return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); + return getDefaultValueFromType(checker, checker.getTypeFromTypeNode(propertyDeclaration.type)); // TODO: GH#18217 } function getDefaultValueFromType(checker, type) { - if (type.flags & 2 /* String */) { - return ts.createLiteral(""); + if (type.flags & 256 /* BooleanLiteral */) { + return type === checker.getFalseType() ? ts.createFalse() : ts.createTrue(); } - else if (type.flags & 4 /* Number */) { - return ts.createNumericLiteral("0"); - } - else if (type.flags & 8 /* Boolean */) { - return ts.createFalse(); - } - else if (type.flags & 224 /* Literal */) { + else if (type.isLiteral()) { return ts.createLiteral(type.value); } - else if (type.flags & 131072 /* Union */) { + else if (type.isUnion()) { return ts.firstDefined(type.types, function (t) { return getDefaultValueFromType(checker, t); }); } - else if (ts.getObjectFlags(type) & 1 /* Class */) { + else if (type.isClass()) { var classDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol); if (!classDeclaration || ts.hasModifier(classDeclaration, 128 /* Abstract */)) return undefined; - var constructorDeclaration = ts.find(classDeclaration.members, function (m) { return ts.isConstructorDeclaration(m) && !!m.body; }); + var constructorDeclaration = ts.getFirstConstructorWithBody(classDeclaration); if (constructorDeclaration && constructorDeclaration.parameters.length) return undefined; return ts.createNew(ts.createIdentifier(type.symbol.name), /*typeArguments*/ undefined, /*argumentsArray*/ undefined); } + else if (checker.isArrayLikeType(type)) { + return ts.createArrayLiteral(); + } return undefined; } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "requireInTs"; + var errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.program); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_require_to_import, fixId, ts.Diagnostics.Convert_all_require_to_import)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start, context.program); }); }, + }); + function doChange(changes, sourceFile, pos, program) { + var _a = getInfo(sourceFile, pos), statement = _a.statement, name = _a.name, required = _a.required; + changes.replaceNode(sourceFile, statement, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions()) + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(name, /*namedBindings*/ undefined), required) + : ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, name, ts.createExternalModuleReference(required))); + } + function getInfo(sourceFile, pos) { + var parent = ts.getTokenAtPosition(sourceFile, pos).parent; + if (!ts.isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ true)) + throw ts.Debug.failBadSyntaxKind(parent); + var decl = ts.cast(parent.parent, ts.isVariableDeclaration); + return { statement: ts.cast(decl.parent.parent, ts.isVariableStatement), name: ts.cast(decl.name, ts.isIdentifier), required: parent.arguments[0] }; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -99934,19 +107213,18 @@ var ts; var info = getInfo(sourceFile, start); if (!info) return undefined; - var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); - return [{ description: description, changes: changes, fixId: fixId }]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info, context.preferences); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_default_import, fixId, ts.Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start); if (info) - doChange(changes, diag.file, info); + doChange(changes, diag.file, info, context.preferences); }); }, }); function getInfo(sourceFile, pos) { - var name = ts.getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); + var name = ts.getTokenAtPosition(sourceFile, pos); if (!ts.isIdentifier(name)) return undefined; // bad input var parent = name.parent; @@ -99958,37 +107236,421 @@ var ts; return { importNode: importNode, name: name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange(changes, sourceFile, info) { - changes.replaceNode(sourceFile, info.importNode, codefix.makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); + function doChange(changes, sourceFile, info, preferences) { + changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var importType = getImportTypeNode(sourceFile, span.start); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_typeof, fixId, ts.Diagnostics.Add_missing_typeof)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return doChange(changes, context.sourceFile, getImportTypeNode(diag.file, diag.start)); + }); }, + }); + function getImportTypeNode(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + ts.Debug.assert(token.kind === 91 /* ImportKeyword */); + ts.Debug.assert(token.parent.kind === 181 /* ImportType */); + return token.parent; + } + function doChange(changes, sourceFile, importType) { + var newTypeNode = ts.updateImportTypeNode(importType, importType.argument, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); + changes.replaceNode(sourceFile, importType, newTypeNode); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; + var fixId = fixIdAddMissingTypeof; + var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var info = getInfo(sourceFile, span.start); + if (!info) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, info); }); + var name = ts.idText(info.container.name); + return [codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Convert_0_to_mapped_object_type, name], fixId, [ts.Diagnostics.Convert_0_to_mapped_object_type, name])]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var info = getInfo(diag.file, diag.start); + if (info) + doChange(changes, diag.file, info); + }); } + }); + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (ts.isClassDeclaration(indexSignature.parent)) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + return { indexSignature: indexSignature, container: container }; + } + function createTypeAliasFromInterface(declaration, type) { + return ts.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type); + } + function doChange(changes, sourceFile, _a) { + var indexSignature = _a.indexSignature, container = _a.container; + var members = ts.isInterfaceDeclaration(container) ? container.members : container.type.members; + var otherMembers = members.filter(function (member) { return !ts.isIndexSignatureDeclaration(member); }); + var parameter = ts.first(indexSignature.parameters); + var mappedTypeParameter = ts.createTypeParameterDeclaration(ts.cast(parameter.name, ts.isIdentifier), parameter.type); + var mappedIntersectionType = ts.createMappedTypeNode(ts.hasReadonlyModifier(indexSignature) ? ts.createModifier(132 /* ReadonlyKeyword */) : undefined, mappedTypeParameter, indexSignature.questionToken, indexSignature.type); + var intersectionType = ts.createIntersectionTypeNode(ts.getAllSuperTypeNodes(container).concat([ + mappedIntersectionType + ], (otherMembers.length ? [ts.createTypeLiteralNode(otherMembers)] : ts.emptyArray))); + changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert export"; + var actionNameDefaultToNamed = "Convert default export to named export"; + var actionNameNamedToDefault = "Convert named export to default export"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var info = getInfo(context); + if (!info) + return undefined; + var description = info.wasDefault ? ts.Diagnostics.Convert_default_export_to_named_export.message : ts.Diagnostics.Convert_named_export_to_default_export.message; + var actionName = info.wasDefault ? actionNameDefaultToNamed : actionNameNamedToDefault; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameDefaultToNamed || actionName === actionNameNamedToDefault); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, ts.Debug.assertDefined(getInfo(context)), t, context.cancellationToken); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + }, + }); + function getInfo(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var exportNode = ts.getParentNodeInSpan(token, file, span); + if (!exportNode || (!ts.isSourceFile(exportNode.parent) && !(ts.isModuleBlock(exportNode.parent) && ts.isAmbientModule(exportNode.parent.parent)))) { + return undefined; + } + var exportingModuleSymbol = ts.isSourceFile(exportNode.parent) ? exportNode.parent.symbol : exportNode.parent.parent.symbol; + var flags = ts.getModifierFlags(exportNode); + var wasDefault = !!(flags & 512 /* Default */); + // If source file already has a default export, don't offer refactor. + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return undefined; + } + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: { + var node = exportNode; + return node.name && ts.isIdentifier(node.name) ? { exportNode: node, exportName: node.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + case 217 /* VariableStatement */: { + var vs = exportNode; + // Must be `export const x = something;`. + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return undefined; + } + var decl = ts.first(vs.declarationList.declarations); + if (!decl.initializer) + return undefined; + ts.Debug.assert(!wasDefault); + return ts.isIdentifier(decl.name) ? { exportNode: vs, exportName: decl.name, wasDefault: wasDefault, exportingModuleSymbol: exportingModuleSymbol } : undefined; + } + default: + return undefined; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, _a, changes, checker) { + var wasDefault = _a.wasDefault, exportNode = _a.exportNode, exportName = _a.exportName; + if (wasDefault) { + changes.delete(exportingSourceFile, ts.Debug.assertDefined(ts.findModifier(exportNode, 79 /* DefaultKeyword */))); + } + else { + var exportKeyword = ts.Debug.assertDefined(ts.findModifier(exportNode, 84 /* ExportKeyword */)); + switch (exportNode.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 239 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, ts.createToken(79 /* DefaultKeyword */)); + break; + case 217 /* VariableStatement */: + // If 'x' isn't used in this file, `export const x = 0;` --> `export default 0;` + if (!ts.FindAllReferences.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile)) { + // We checked in `getInfo` that an initializer exists. + changes.replaceNode(exportingSourceFile, exportNode, ts.createExportDefault(ts.Debug.assertDefined(ts.first(exportNode.declarationList.declarations).initializer))); + break; + } + // falls through + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 242 /* ModuleDeclaration */: + // `export type T = number;` -> `type T = number; export default T;` + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, ts.createExportDefault(ts.createIdentifier(exportName.text))); + break; + default: + ts.Debug.assertNever(exportNode); + } + } + } + function changeImports(program, _a, changes, cancellationToken) { + var wasDefault = _a.wasDefault, exportName = _a.exportName, exportingModuleSymbol = _a.exportingModuleSymbol; + var checker = program.getTypeChecker(); + var exportSymbol = ts.Debug.assertDefined(checker.getSymbolAtLocation(exportName)); + ts.FindAllReferences.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, function (ref) { + var importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } + else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.default` --> `a.foo` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier(exportName)); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + // `default as foo` --> `foo`, `default as bar` --> `foo as bar` + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 248 /* ImportClause */: { + var clause = parent; + ts.Debug.assert(clause.name === ref); + var spec = makeImportSpecifier(exportName, ref.text); + var namedBindings = clause.namedBindings; + if (!namedBindings) { + // `import foo from "./a";` --> `import { foo } from "./a";` + changes.replaceNode(importingSourceFile, ref, ts.createNamedImports([spec])); + } + else if (namedBindings.kind === 249 /* NamespaceImport */) { + // `import foo, * as a from "./a";` --> `import * as a from ".a/"; import { foo } from "./a";` + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + var quotePreference = ts.isStringLiteral(clause.parent.moduleSpecifier) ? ts.quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + var newImport = ts.makeImport(/*default*/ undefined, [makeImportSpecifier(exportName, ref.text)], clause.parent.moduleSpecifier, quotePreference); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } + else { + // `import foo, { bar } from "./a"` --> `import { bar, foo } from "./a";` + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + var parent = ref.parent; + switch (parent.kind) { + case 187 /* PropertyAccessExpression */: + // `a.foo` --> `a.default` + changes.replaceNode(importingSourceFile, ref, ts.createIdentifier("default")); + break; + case 251 /* ImportSpecifier */: + case 255 /* ExportSpecifier */: { + var spec = parent; + if (spec.kind === 251 /* ImportSpecifier */) { + // `import { foo } from "./a";` --> `import foo from "./a";` + // `import { foo as bar } from "./a";` --> `import bar from "./a";` + var defaultImport = ts.createIdentifier(spec.name.text); + if (spec.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, spec.parent, defaultImport); + } + else { + changes.delete(importingSourceFile, spec); + changes.insertNodeBefore(importingSourceFile, spec.parent, defaultImport); + } + } + else { + // `export { foo } from "./a";` --> `export { default as foo } from "./a";` + // `export { foo as bar } from "./a";` --> `export { default as bar } from "./a";` + // `export { foo as default } from "./a";` --> `export { default } from "./a";` + // (Because `export foo from "./a";` isn't valid syntax.) + changes.replaceNode(importingSourceFile, spec, makeExportSpecifier("default", spec.name.text)); + } + break; + } + default: + ts.Debug.failBadSyntaxKind(parent); + } + } + function makeImportSpecifier(propertyName, name) { + return ts.createImportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + function makeExportSpecifier(propertyName, name) { + return ts.createExportSpecifier(propertyName === name ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name)); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Convert import"; + var actionNameNamespaceToNamed = "Convert namespace import to named imports"; + var actionNameNamedToNamespace = "Convert named imports to namespace import"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + var i = getImportToConvert(context); + if (!i) + return undefined; + var description = i.kind === 249 /* NamespaceImport */ ? ts.Diagnostics.Convert_namespace_import_to_named_imports.message : ts.Diagnostics.Convert_named_imports_to_namespace_import.message; + var actionName = i.kind === 249 /* NamespaceImport */ ? actionNameNamespaceToNamed : actionNameNamedToNamespace; + return [{ name: refactorName, description: description, actions: [{ name: actionName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === actionNameNamespaceToNamed || actionName === actionNameNamedToNamespace); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, ts.Debug.assertDefined(getImportToConvert(context))); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. + function getImportToConvert(context) { + var file = context.file; + var span = ts.getRefactorContextSpan(context); + var token = ts.getTokenAtPosition(file, span.start); + var importDecl = ts.getParentNodeInSpan(token, file, span); + if (!importDecl || !ts.isImportDeclaration(importDecl)) + return undefined; + var importClause = importDecl.importClause; + return importClause && importClause.namedBindings; + } + function doChange(sourceFile, program, changes, toConvert) { + var checker = program.getTypeChecker(); + if (toConvert.kind === 249 /* NamespaceImport */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } + else { + doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + var usedAsNamespaceOrDefault = false; + var nodesToReplace = []; + var conflictingNames = ts.createMap(); + ts.FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, function (id) { + if (!ts.isPropertyAccessExpression(id.parent)) { + usedAsNamespaceOrDefault = true; + } + else { + var parent = ts.cast(id.parent, ts.isPropertyAccessExpression); + var exportName = parent.name.text; + if (checker.resolveName(exportName, id, 67108863 /* All */, /*excludeGlobals*/ true)) { + conflictingNames.set(exportName, true); + } + ts.Debug.assert(parent.expression === id); + nodesToReplace.push(parent); + } + }); + // We may need to change `mod.x` to `_x` to avoid a name conflict. + var exportNameToImportName = ts.createMap(); + for (var _i = 0, nodesToReplace_1 = nodesToReplace; _i < nodesToReplace_1.length; _i++) { + var propertyAccess = nodesToReplace_1[_i]; + var exportName = propertyAccess.name.text; + var importName = exportNameToImportName.get(exportName); + if (importName === undefined) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? ts.getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccess, ts.createIdentifier(importName)); + } + var importSpecifiers = []; + exportNameToImportName.forEach(function (name, propertyName) { + importSpecifiers.push(ts.createImportSpecifier(name === propertyName ? undefined : ts.createIdentifier(propertyName), ts.createIdentifier(name))); + }); + var importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + // Need to leave the namespace import alone + changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); + } + else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? ts.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); + } + } + function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + var importDecl = toConvert.parent.parent; + var moduleSpecifier = importDecl.moduleSpecifier; + var preferredName = moduleSpecifier && ts.isStringLiteral(moduleSpecifier) ? ts.codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 6 /* ESNext */) : "module"; + var namespaceNameConflicts = toConvert.elements.some(function (element) { + return ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + return !!checker.resolveName(preferredName, id, 67108863 /* All */, /*excludeGlobals*/ true); + }) || false; + }); + var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; + var neededNamedImports = []; + var _loop_25 = function (element) { + var propertyName = (element.propertyName || element.name).text; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { + var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); + if (ts.isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, ts.createPropertyAssignment(id.text, access)); + } + else if (ts.isExportSpecifier(id.parent) && !id.parent.propertyName) { + if (!neededNamedImports.some(function (n) { return n.name === element.name; })) { + neededNamedImports.push(ts.createImportSpecifier(element.propertyName && ts.createIdentifier(element.propertyName.text), ts.createIdentifier(element.name.text))); + } + } + else { + changes.replaceNode(sourceFile, id, access); + } + }); + }; + for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { + var element = _a[_i]; + _loop_25(element); + } + changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); + if (neededNamedImports.length) { + changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, neededNamedImports)); + } + } + function updateImport(old, defaultImportName, elements) { + return ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImportName, elements && elements.length ? ts.createNamedImports(elements) : undefined), old.moduleSpecifier); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); /* @internal */ var ts; (function (ts) { @@ -100003,7 +107665,7 @@ var ts; * Exported for tests. */ function getAvailableActions(context) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; if (targetRange === undefined) { return undefined; @@ -100072,8 +107734,8 @@ var ts; extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { - var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); - var targetRange = rangeToExtract.targetRange; + var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); + var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); if (parsedFunctionIndexMatch) { var index = +parsedFunctionIndexMatch[1]; @@ -100144,9 +107806,9 @@ var ts; } // 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); + var start = ts.getParentNodeInSpan(ts.getTokenAtPosition(sourceFile, span.start), sourceFile, span); // Do the same for the ending position - var end = getParentNodeInSpan(ts.findTokenOnLeftOfPosition(sourceFile, ts.textSpanEnd(span)), sourceFile, span); + var end = ts.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. @@ -100165,7 +107827,8 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { + var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 + for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -100198,7 +107861,7 @@ var ts; if (errors) { return { errors: errors }; } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, declarations: declarations } }; // TODO: GH#18217 /** * Attempt to refine the extraction node (generally, by shrinking it) to produce better results. * @param node The unrefined extraction node. @@ -100240,20 +107903,20 @@ var ts; function checkForStaticContext(nodeToCheck, containingClass) { var current = nodeToCheck; while (current !== containingClass) { - if (current.kind === 151 /* PropertyDeclaration */) { + if (current.kind === 152 /* PropertyDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 148 /* Parameter */) { + else if (current.kind === 149 /* Parameter */) { var ctorOrMethod = ts.getContainingFunction(current); - if (ctorOrMethod.kind === 154 /* Constructor */) { + if (ctorOrMethod.kind === 155 /* Constructor */) { rangeFacts |= RangeFacts.InStaticRegion; } break; } - else if (current.kind === 153 /* MethodDeclaration */) { + else if (current.kind === 154 /* MethodDeclaration */) { if (ts.hasModifier(current, 32 /* Static */)) { rangeFacts |= RangeFacts.InStaticRegion; } @@ -100277,7 +107940,7 @@ var ts; if (!ts.isStatement(nodeToCheck) && !(ts.isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck))) { return [ts.createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; } - if (nodeToCheck.flags & 2097152 /* Ambient */) { + if (nodeToCheck.flags & 4194304 /* Ambient */) { 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) @@ -100296,8 +107959,11 @@ var ts; return true; } if (ts.isDeclaration(node)) { - var declaringNode = (node.kind === 230 /* VariableDeclaration */) ? node.parent.parent : node; + var declaringNode = (node.kind === 235 /* VariableDeclaration */) ? node.parent.parent : node; if (ts.hasModifier(declaringNode, 1 /* Export */)) { + // TODO: GH#18217 Silly to use `errors ||` since it's definitely not defined (see top of `visit`) + // Also, if we're only pushing one error, just use `let error: Diagnostic | undefined`! + // Also TODO: GH#19956 (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractExportedEntity)); return true; } @@ -100305,15 +107971,15 @@ var ts; } // Some things can't be extracted in certain situations switch (node.kind) { - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractImport)); 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 === 185 /* CallExpression */) { + if (node.parent.kind === 189 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); + var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; @@ -100324,10 +107990,10 @@ var ts; } break; } - if (!node || ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { + if (ts.isFunctionLikeDeclaration(node) || ts.isClassLike(node)) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 233 /* ClassDeclaration */: + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: if (ts.isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); @@ -100339,20 +108005,20 @@ var ts; } var savedPermittedJumps = permittedJumps; switch (node.kind) { - case 215 /* IfStatement */: + case 220 /* IfStatement */: permittedJumps = 0 /* None */; break; - case 228 /* TryStatement */: + case 233 /* TryStatement */: // forbid all jumps inside try blocks permittedJumps = 0 /* None */; break; - case 211 /* Block */: - if (node.parent && node.parent.kind === 228 /* TryStatement */ && node.parent.finallyBlock === node) { + case 216 /* Block */: + if (node.parent && node.parent.kind === 233 /* TryStatement */ && node.parent.finallyBlock === node) { // allow unconditional returns from finally blocks permittedJumps = 4 /* Return */; } break; - case 264 /* CaseClause */: + case 269 /* CaseClause */: // allow unlabeled break inside case clauses permittedJumps |= 1 /* Break */; break; @@ -100364,11 +108030,11 @@ var ts; break; } switch (node.kind) { - case 173 /* ThisType */: + case 176 /* ThisType */: case 99 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: { var label = node.label; (seenLabels || (seenLabels = [])).push(label.escapedText); @@ -100376,8 +108042,8 @@ var ts; seenLabels.pop(); break; } - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: { var label = node.label; if (label) { @@ -100387,20 +108053,20 @@ var ts; } } else { - if (!(permittedJumps & (node.kind === 222 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + if (!(permittedJumps & (node.kind === 227 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { // attempt to break or continue in a forbidden context (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); } } break; } - case 195 /* AwaitExpression */: + case 199 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; - case 201 /* YieldExpression */: + case 205 /* YieldExpression */: rangeFacts |= RangeFacts.IsGenerator; break; - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: if (permittedJumps & 4 /* Return */) { rangeFacts |= RangeFacts.HasReturn; } @@ -100454,7 +108120,7 @@ var ts; while (true) { current = current.parent; // A function parameter's initializer is actually in the outer scope, not the function declaration - if (current.kind === 148 /* Parameter */) { + if (current.kind === 149 /* Parameter */) { // Skip all the way to the outer scope of the function that declared this parameter current = ts.findAncestor(current, function (parent) { return ts.isFunctionLikeDeclaration(parent); }).parent; } @@ -100465,7 +108131,7 @@ var ts; // * Module/namespace or source file if (isScope(current)) { scopes.push(current); - if (current.kind === 272 /* SourceFile */) { + if (current.kind === 277 /* SourceFile */) { return scopes; } } @@ -100474,7 +108140,7 @@ var ts; function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { var _a = getPossibleExtractionsWorker(targetRange, context), scopes = _a.scopes, _b = _a.readsAndWrites, target = _b.target, usagesPerScope = _b.usagesPerScope, functionErrorsPerScope = _b.functionErrorsPerScope, exposedVariableDeclarations = _b.exposedVariableDeclarations; ts.Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); + context.cancellationToken.throwIfCancellationRequested(); // TODO: GH#18217 return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); } function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { @@ -100555,32 +108221,32 @@ var ts; } function getDescriptionForFunctionLikeDeclaration(scope) { switch (scope.kind) { - case 154 /* Constructor */: + case 155 /* Constructor */: return "constructor"; - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: return scope.name ? "function '" + scope.name.text + "'" : "anonymous function"; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: return "arrow function"; - case 153 /* MethodDeclaration */: + case 154 /* MethodDeclaration */: return "method '" + scope.name.getText(); - case 155 /* GetAccessor */: + case 156 /* GetAccessor */: return "'get " + scope.name.getText() + "'"; - case 156 /* SetAccessor */: + case 157 /* SetAccessor */: return "'set " + scope.name.getText() + "'"; default: - ts.Debug.assertNever(scope); + throw ts.Debug.assertNever(scope); } } function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 233 /* ClassDeclaration */ + return scope.kind === 238 /* ClassDeclaration */ ? scope.name ? "class '" + scope.name.text + "'" : "anonymous class declaration" : scope.name ? "class expression '" + scope.name.text + "'" : "anonymous class expression"; } function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 238 /* ModuleBlock */ + return scope.kind === 243 /* ModuleBlock */ ? "namespace '" + scope.parent.name.getText() + "'" : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; } @@ -100589,13 +108255,6 @@ var ts; SpecialScope[SpecialScope["Module"] = 0] = "Module"; SpecialScope[SpecialScope["Global"] = 1] = "Global"; })(SpecialScope || (SpecialScope = {})); - function getUniqueName(baseName, fileText) { - var nameText = baseName; - for (var i = 1; ts.stringContains(fileText, nameText); i++) { - nameText = baseName + "_" + i; - } - return nameText; - } /** * Result of 'extractRange' operation for a specific scope. * Stores either a list of changes that should be applied to extract a range or a list of errors @@ -100605,7 +108264,7 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted function var file = scope.getSourceFile(); - var functionNameText = getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file.text); + var functionNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newMethod" : "newFunction", file); var isJS = ts.isInJavaScriptFile(scope); var functionName = ts.createIdentifier(functionNameText); var returnType; @@ -100646,7 +108305,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); // TODO: GH#18217 } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -100796,7 +108455,7 @@ var ts; var edits = changeTracker.getChanges(); var renameRange = isReadonlyArray(range.range) ? ts.first(range.range) : range.range; var renameFilename = renameRange.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); + var renameLocation = ts.getRenameLocation(edits, renameFilename, functionNameText, /*isDeclaredBeforeUse*/ false); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; function getTypeDeepCloneUnionUndefined(typeNode) { if (typeNode === undefined) { @@ -100821,11 +108480,11 @@ var ts; var checker = context.program.getTypeChecker(); // Make a unique name for the extracted variable var file = scope.getSourceFile(); - var localNameText = getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file.text); + var localNameText = ts.getUniqueName(ts.isClassLike(scope) ? "newProperty" : "newLocal", file); var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); // TODO: GH#18217 var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -100841,14 +108500,14 @@ var ts; /*decorators*/ undefined, modifiers, localNameText, /*questionToken*/ undefined, variableType, initializer); var localReference = ts.createPropertyAccess(rangeFacts & RangeFacts.InStaticRegion - ? ts.createIdentifier(scope.name.getText()) + ? ts.createIdentifier(scope.name.getText()) // TODO: GH#18217 : ts.createThis(), ts.createIdentifier(localNameText)); // Declare var maxInsertionPos = node.pos; var nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariable, /*blankLineBetween*/ true); // Consume - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } else { var newVariableDeclaration = ts.createVariableDeclaration(localNameText, variableType, initializer); @@ -100863,14 +108522,14 @@ var ts; changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); // Consume var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } - else if (node.parent.kind === 214 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { + else if (node.parent.kind === 219 /* ExpressionStatement */ && scope === ts.findAncestor(node, isScope)) { // If the parent is an expression statement and the target scope is the immediately enclosing one, // replace the statement with the declaration. var newVariableStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */)); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); } else { var newVariableStatement = ts.createVariableStatement( @@ -100884,19 +108543,19 @@ var ts; changeTracker.insertNodeBefore(context.file, nodeToInsertBefore, newVariableStatement, /*blankLineBetween*/ false); } // Consume - if (node.parent.kind === 214 /* ExpressionStatement */) { + if (node.parent.kind === 219 /* ExpressionStatement */) { // If the parent is an expression statement, delete it. - changeTracker.deleteNode(context.file, node.parent, ts.textChanges.useNonAdjustedPositions); + changeTracker.delete(context.file, node.parent); } else { var localReference = ts.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference, ts.textChanges.useNonAdjustedPositions); + changeTracker.replaceNode(context.file, node, localReference); } } } var edits = changeTracker.getChanges(); var renameFilename = node.getSourceFile().fileName; - var renameLocation = getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); + var renameLocation = ts.getRenameLocation(edits, renameFilename, localNameText, /*isDeclaredBeforeUse*/ true); return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; } function getContainingVariableDeclarationIfInList(node, scope) { @@ -100912,36 +108571,6 @@ var ts; node = node.parent; } } - /** - * @return The index of the (only) reference to the extracted symbol. We want the cursor - * to be on the reference, rather than the declaration, because it's closer to where the - * user was before extracting it. - */ - function getRenameLocation(edits, renameFilename, functionNameText, isDeclaredBeforeUse) { - var delta = 0; - var lastPos = -1; - for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { - var _a = edits_1[_i], fileName = _a.fileName, textChanges_2 = _a.textChanges; - ts.Debug.assert(fileName === renameFilename); - for (var _b = 0, textChanges_3 = textChanges_2; _b < textChanges_3.length; _b++) { - var change = textChanges_3[_b]; - var span_14 = change.span, newText = change.newText; - var index = newText.indexOf(functionNameText); - if (index !== -1) { - lastPos = span_14.start + delta + index; - // If the reference comes first, return immediately. - if (!isDeclaredBeforeUse) { - return lastPos; - } - } - delta += newText.length - span_14.length; - } - } - // If the declaration comes first, return the position of the last occurrence. - ts.Debug.assert(isDeclaredBeforeUse); - ts.Debug.assert(lastPos >= 0); - return lastPos; - } function getFirstDeclaration(type) { var firstDeclaration; var symbol = type.symbol; @@ -100965,7 +108594,7 @@ var ts; function getCalledExpression(scope, range, functionNameText) { var functionReference = ts.createIdentifier(functionNameText); if (ts.isClassLike(scope)) { - var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); + var lhs = range.facts & RangeFacts.InStaticRegion ? ts.createIdentifier(scope.name.text) : ts.createThis(); // TODO: GH#18217 return ts.createPropertyAccess(lhs, functionReference); } else { @@ -101001,7 +108630,7 @@ var ts; return { body: ts.createBlock(statements, /*multiLine*/ true), returnValueProperty: undefined }; } function visitor(node) { - if (!ignoreReturns && node.kind === 223 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { + if (!ignoreReturns && node.kind === 228 /* ReturnStatement */ && hasWritesOrVariableDeclarations) { var assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); if (node.expression) { if (!returnValueProperty) { @@ -101037,7 +108666,7 @@ var ts; } function getStatementsOrClassElements(scope) { if (ts.isFunctionLikeDeclaration(scope)) { - var body = scope.body; + var body = scope.body; // TODO: GH#18217 if (ts.isBlock(body)) { return body.statements; } @@ -101067,8 +108696,8 @@ var ts; ts.Debug.assert(members.length > 0); // There must be at least one child, since we extracted from one. var prevMember; var allProperties = true; - for (var _i = 0, members_6 = members; _i < members_6.length; _i++) { - var member = members_6[_i]; + for (var _i = 0, members_7 = members; _i < members_7.length; _i++) { + var member = members_7[_i]; if (member.pos > maxPos) { return prevMember || members[0]; } @@ -101082,7 +108711,8 @@ var ts; } prevMember = member; } - ts.Debug.assert(prevMember !== undefined); // If the loop didn't return, then it did set prevMember. + if (prevMember === undefined) + return ts.Debug.fail(); // If the loop didn't return, then it did set prevMember. return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -101109,18 +108739,15 @@ var ts; return curr.parent.parent; } // There must be at least one statement since we started in one. - ts.Debug.assert(prevStatement !== undefined); - return prevStatement; - } - if (curr === scope) { - ts.Debug.fail("Didn't encounter a block-like before encountering scope"); - break; + return ts.Debug.assertDefined(prevStatement); } + ts.Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); } } function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { var variableAssignments = ts.map(exposedVariableDeclarations, function (v) { return ts.createShorthandPropertyAssignment(v.symbol.name); }); var writeAssignments = ts.map(writes, function (w) { return ts.createShorthandPropertyAssignment(w.symbol.name); }); + // TODO: GH#18217 `variableAssignments` not possibly undefined! return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined @@ -101173,7 +108800,7 @@ var ts; var end = ts.last(statements).end; expressionDiagnostic = ts.createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); } - else if (checker.getTypeAtLocation(expression).flags & (2048 /* Void */ | 16384 /* Never */)) { + else if (checker.getTypeAtLocation(expression).flags & (4096 /* Void */ | 32768 /* Never */)) { expressionDiagnostic = ts.createDiagnosticForNode(expression, Messages.uselessConstantType); } // initialize results @@ -101181,7 +108808,7 @@ var ts; var scope = scopes_1[_i]; usagesPerScope.push({ usages: ts.createMap(), typeParameterUsages: ts.createMap(), substitutions: ts.createMap() }); substitutionsPerScope.push(ts.createMap()); - functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 232 /* FunctionDeclaration */ + functionErrorsPerScope.push(ts.isFunctionLikeDeclaration(scope) && scope.kind !== 237 /* FunctionDeclaration */ ? [ts.createDiagnosticForNode(scope, Messages.cannotExtractToOtherFunctionLike)] : []); var constantErrors = []; @@ -101206,7 +108833,7 @@ var ts; // will use the contextual type of an expression as the return type of the extracted // method (and will therefore "use" all the types involved). if (inGenericContext && !isReadonlyArray(targetRange.range)) { - var contextualType = checker.getContextualType(targetRange.range); + var contextualType = checker.getContextualType(targetRange.range); // TODO: GH#18217 recordTypeParameterUsages(contextualType); } if (allTypeParameterUsages.size > 0) { @@ -101221,8 +108848,8 @@ var ts; i_1++; } // Note that we add the current node's type parameters *after* updating the corresponding scope. - if (ts.isDeclarationWithTypeParameters(curr) && curr.typeParameters) { - for (var _a = 0, _b = curr.typeParameters; _a < _b.length; _a++) { + if (ts.isDeclarationWithTypeParameters(curr)) { + for (var _a = 0, _b = ts.getEffectiveTypeParameterDeclarations(curr); _a < _b.length; _a++) { var typeParameterDecl = _b[_a]; var typeParameter = checker.getTypeAtLocation(typeParameterDecl); if (allTypeParameterUsages.has(typeParameter.id.toString())) { @@ -101244,7 +108871,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_11 = function (i) { + var _loop_26 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -101284,21 +108911,11 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_11(i); + _loop_26(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; - function hasTypeParameters(node) { - return ts.isDeclarationWithTypeParameters(node) && - node.typeParameters !== undefined && - node.typeParameters.length > 0; - } function isInGenericContext(node) { - for (; node; node = node.parent) { - if (hasTypeParameters(node)) { - return true; - } - } - return false; + return !!ts.findAncestor(node, function (n) { return ts.isDeclarationWithTypeParameters(n) && ts.getEffectiveTypeParameterDeclarations(n).length !== 0; }); } function recordTypeParameterUsages(type) { // PERF: This is potentially very expensive. `type` could be a library type with @@ -101308,7 +108925,7 @@ var ts; var visitedTypes = symbolWalker.walkType(type).visitedTypes; for (var _i = 0, visitedTypes_1 = visitedTypes; _i < visitedTypes_1.length; _i++) { var visitedType = visitedTypes_1[_i]; - if (visitedType.flags & 32768 /* TypeParameter */) { + if (visitedType.isTypeParameter()) { allTypeParameterUsages.set(visitedType.id.toString(), visitedType); } } @@ -101497,20 +109114,6 @@ var ts; : 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; - } - } - 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. @@ -101519,31 +109122,32 @@ var ts; * in the sense of something that you could extract on */ function isExtractableExpression(node) { - switch (node.parent.kind) { - case 271 /* EnumMember */: + var parent = node.parent; + switch (parent.kind) { + case 276 /* EnumMember */: return false; } switch (node.kind) { case 9 /* StringLiteral */: - return node.parent.kind !== 242 /* ImportDeclaration */ && - node.parent.kind !== 246 /* ImportSpecifier */; - case 202 /* SpreadElement */: - case 178 /* ObjectBindingPattern */: - case 180 /* BindingElement */: + return parent.kind !== 247 /* ImportDeclaration */ && + parent.kind !== 251 /* ImportSpecifier */; + case 206 /* SpreadElement */: + case 182 /* ObjectBindingPattern */: + case 184 /* BindingElement */: return false; case 71 /* Identifier */: - return node.parent.kind !== 180 /* BindingElement */ && - node.parent.kind !== 246 /* ImportSpecifier */ && - node.parent.kind !== 250 /* ExportSpecifier */; + return parent.kind !== 184 /* BindingElement */ && + parent.kind !== 251 /* ImportSpecifier */ && + parent.kind !== 255 /* ExportSpecifier */; } return true; } function isBlockLike(node) { switch (node.kind) { - case 211 /* Block */: - case 272 /* SourceFile */: - case 238 /* ModuleBlock */: - case 264 /* CaseClause */: + case 216 /* Block */: + case 277 /* SourceFile */: + case 243 /* ModuleBlock */: + case 269 /* CaseClause */: return true; default: return false; @@ -101552,48 +109156,948 @@ var ts; })(extractSymbol = refactor.extractSymbol || (refactor.extractSymbol = {})); })(refactor = ts.refactor || (ts.refactor = {})); })(ts || (ts = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var generateGetAccessorAndSetAccessor; + (function (generateGetAccessorAndSetAccessor) { + var actionName = "Generate 'get' and 'set' accessors"; + var actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + if (!getConvertibleFieldAtPosition(context)) + return undefined; + return [{ + name: actionName, + description: actionDescription, + actions: [ + { + name: actionName, + description: actionDescription + } + ] + }]; + } + function getEditsForAction(context, _actionName) { + var file = context.file; + var fieldInfo = getConvertibleFieldAtPosition(context); + if (!fieldInfo) + return undefined; + var isJS = ts.isSourceFileJavaScript(file); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + var isStatic = fieldInfo.isStatic, isReadonly = fieldInfo.isReadonly, fieldName = fieldInfo.fieldName, accessorName = fieldInfo.accessorName, originalName = fieldInfo.originalName, type = fieldInfo.type, container = fieldInfo.container, declaration = fieldInfo.declaration, renameAccessor = fieldInfo.renameAccessor; + ts.suppressLeadingAndTrailingTrivia(fieldName); + ts.suppressLeadingAndTrailingTrivia(declaration); + ts.suppressLeadingAndTrailingTrivia(container); + var isInClassLike = ts.isClassLike(container); + // avoid Readonly modifier because it will convert to get accessor + var modifierFlags = ts.getModifierFlags(declaration) & ~64 /* Readonly */; + var accessorModifiers = isInClassLike + ? !modifierFlags || modifierFlags & 8 /* Private */ + ? getModifiers(isJS, isStatic, 114 /* PublicKeyword */) + : ts.createNodeArray(ts.createModifiersFromModifierFlags(modifierFlags)) + : undefined; + var fieldModifiers = isInClassLike ? getModifiers(isJS, isStatic, 112 /* PrivateKeyword */) : undefined; + updateFieldDeclaration(changeTracker, file, declaration, fieldName, fieldModifiers); + var getAccessor = generateGetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(getAccessor); + insertAccessor(changeTracker, file, getAccessor, declaration, container); + if (isReadonly) { + // readonly modifier only existed in classLikeDeclaration + var constructor = ts.getFirstConstructorWithBody(container); + if (constructor) { + updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName); + } + } + else { + var setAccessor = generateSetAccessor(fieldName, accessorName, type, accessorModifiers, isStatic, container); + ts.suppressLeadingAndTrailingTrivia(setAccessor); + insertAccessor(changeTracker, file, setAccessor, declaration, container); + } + var edits = changeTracker.getChanges(); + var renameFilename = file.fileName; + var nameNeedRename = renameAccessor ? accessorName : fieldName; + var renameLocationOffset = ts.isIdentifier(nameNeedRename) ? 0 : -1; + var renameLocation = renameLocationOffset + ts.getRenameLocation(edits, renameFilename, nameNeedRename.text, /*preferLastLocation*/ ts.isParameter(declaration)); + return { renameFilename: renameFilename, renameLocation: renameLocation, edits: edits }; + } + function isConvertibleName(name) { + return ts.isIdentifier(name) || ts.isStringLiteral(name); + } + function isAcceptedDeclaration(node) { + return ts.isParameterPropertyDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node); + } + function createPropertyName(name, originalName) { + return ts.isIdentifier(originalName) ? ts.createIdentifier(name) : ts.createLiteral(name); + } + function createAccessorAccessExpression(fieldName, isStatic, container) { + var leftHead = isStatic ? container.name : ts.createThis(); // TODO: GH#18217 + return ts.isIdentifier(fieldName) ? ts.createPropertyAccess(leftHead, fieldName) : ts.createElementAccess(leftHead, ts.createLiteral(fieldName)); + } + function getModifiers(isJS, isStatic, accessModifier) { + var modifiers = ts.append(!isJS ? [ts.createToken(accessModifier)] : undefined, isStatic ? ts.createToken(115 /* StaticKeyword */) : undefined); + return modifiers && ts.createNodeArray(modifiers); + } + function startsWithUnderscore(name) { + return name.charCodeAt(0) === 95 /* _ */; + } + function getConvertibleFieldAtPosition(context) { + var file = context.file, startPosition = context.startPosition, endPosition = context.endPosition; + var node = ts.getTokenAtPosition(file, startPosition); + var declaration = ts.findAncestor(node.parent, isAcceptedDeclaration); + // make sure declaration have AccessibilityModifier or Static Modifier or Readonly Modifier + var meaning = 28 /* AccessibilityModifier */ | 32 /* Static */ | 64 /* Readonly */; + if (!declaration || !ts.nodeOverlapsWithStartEnd(declaration.name, file, startPosition, endPosition) // TODO: GH#18217 + || !isConvertibleName(declaration.name) || (ts.getModifierFlags(declaration) | meaning) !== meaning) + return undefined; + var name = declaration.name.text; + var startWithUnderscore = startsWithUnderscore(name); + var fieldName = createPropertyName(startWithUnderscore ? name : ts.getUniqueName("_" + name, file), declaration.name); + var accessorName = createPropertyName(startWithUnderscore ? ts.getUniqueName(name.substring(1), file) : name, declaration.name); + return { + isStatic: ts.hasStaticModifier(declaration), + isReadonly: ts.hasReadonlyModifier(declaration), + type: ts.getTypeAnnotationNode(declaration), + container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + originalName: declaration.name, + declaration: declaration, + fieldName: fieldName, + accessorName: accessorName, + renameAccessor: startWithUnderscore + }; + } + function generateGetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createGetAccessor( + /*decorators*/ undefined, modifiers, accessorName, + /*parameters*/ undefined, // TODO: GH#18217 + type, ts.createBlock([ + ts.createReturn(createAccessorAccessExpression(fieldName, isStatic, container)) + ], /*multiLine*/ true)); + } + function generateSetAccessor(fieldName, accessorName, type, modifiers, isStatic, container) { + return ts.createSetAccessor( + /*decorators*/ undefined, modifiers, accessorName, [ts.createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, ts.createIdentifier("value"), + /*questionToken*/ undefined, type)], ts.createBlock([ + ts.createStatement(ts.createAssignment(createAccessorAccessExpression(fieldName, isStatic, container), ts.createIdentifier("value"))) + ], /*multiLine*/ true)); + } + function updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + var property = ts.updateProperty(declaration, declaration.decorators, modifiers, fieldName, declaration.questionToken || declaration.exclamationToken, declaration.type, declaration.initializer); + changeTracker.replaceNode(file, declaration, property); + } + function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { + var assignment = ts.updatePropertyAssignment(declaration, fieldName, declaration.initializer); + changeTracker.replacePropertyAssignment(file, declaration, assignment); + } + function updateFieldDeclaration(changeTracker, file, declaration, fieldName, modifiers) { + if (ts.isPropertyDeclaration(declaration)) { + updatePropertyDeclaration(changeTracker, file, declaration, fieldName, modifiers); + } + else if (ts.isPropertyAssignment(declaration)) { + updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName); + } + else { + changeTracker.replaceNode(file, declaration, ts.updateParameter(declaration, declaration.decorators, modifiers, declaration.dotDotDotToken, ts.cast(fieldName, ts.isIdentifier), declaration.questionToken, declaration.type, declaration.initializer)); + } + } + function insertAccessor(changeTracker, file, accessor, declaration, container) { + ts.isParameterPropertyDeclaration(declaration) + ? changeTracker.insertNodeAtClassStart(file, container, accessor) + : ts.isPropertyAssignment(declaration) + ? changeTracker.insertNodeAfterComma(file, declaration, accessor) + : changeTracker.insertNodeAfter(file, declaration, accessor); + } + function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, context, constructor, fieldName, originalName) { + if (!constructor.body) + return; + var file = context.file, program = context.program, cancellationToken = context.cancellationToken; + var referenceEntries = ts.mapDefined(ts.FindAllReferences.getReferenceEntriesForNode(originalName.parent.pos, originalName, program, [file], cancellationToken), function (entry) { + return (entry.type === "node" && ts.rangeContainsRange(constructor, entry.node) && ts.isIdentifier(entry.node) && ts.isWriteAccess(entry.node)) ? entry.node : undefined; + }); + ts.forEach(referenceEntries, function (entry) { + var parent = entry.parent; + var accessorName = ts.createIdentifier(fieldName.text); + var node = ts.isBinaryExpression(parent) + ? ts.updateBinary(parent, accessorName, parent.right, parent.operatorToken) + : ts.isPropertyAccessExpression(parent) + ? ts.updatePropertyAccess(parent, parent.expression, accessorName) + : ts.Debug.fail("Unexpected write access token"); + changeTracker.replaceNode(file, parent, node); + }); + } + })(generateGetAccessorAndSetAccessor = refactor.generateGetAccessorAndSetAccessor || (refactor.generateGetAccessorAndSetAccessor = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var refactorName = "Move to a new file"; + refactor.registerRefactor(refactorName, { + getAvailableActions: function (context) { + if (!context.preferences.allowTextChangesInNewFiles || getStatementsToMove(context) === undefined) + return undefined; + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); + return [{ name: refactorName, description: description, actions: [{ name: refactorName, description: description }] }]; + }, + getEditsForAction: function (context, actionName) { + ts.Debug.assert(actionName === refactorName); + var statements = ts.Debug.assertDefined(getStatementsToMove(context)); + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); + return { edits: edits, renameFilename: undefined, renameLocation: undefined }; + } + }); + function getRangeToMove(context) { + var file = context.file; + var range = ts.createTextRangeFromSpan(ts.getRefactorContextSpan(context)); + var statements = file.statements; + var startNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.pos; }); + if (startNodeIndex === -1) + return undefined; + var startStatement = statements[startNodeIndex]; + if (ts.isNamedDeclaration(startStatement) && startStatement.name && ts.rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + // Can't only partially include the start node or be partially into the next node + if (range.pos > startStatement.getStart(file)) + return undefined; + var afterEndNodeIndex = ts.findIndex(statements, function (s) { return s.end > range.end; }, startNodeIndex); + // Can't be partially into the next node + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return undefined; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? undefined : statements[afterEndNodeIndex], + }; + } + function doChange(oldFile, program, toMove, changes, host, preferences) { + var checker = program.getTypeChecker(); + var usage = getUsageInfo(oldFile, toMove.all, checker); + var currentDirectory = ts.getDirectoryPath(oldFile.fileName); + var extension = ts.extensionFromPath(oldFile.fileName); + var newModuleName = makeUniqueModuleName(getNewModuleName(usage.movedSymbols), extension, currentDirectory, host); + var newFileNameWithExtension = newModuleName + extension; + // If previous file was global, this is easy. + changes.createNewFile(oldFile, ts.combinePaths(currentDirectory, newFileNameWithExtension), getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFileNameWithExtension, ts.hostGetCanonicalFileName(host)); + } + // Filters imports out of the range of statements to move. Imports will be copied to the new file anyway, and may still be needed in the old file. + function getStatementsToMove(context) { + var rangeToMove = getRangeToMove(context); + if (rangeToMove === undefined) + return undefined; + var all = []; + var ranges = []; + var toMove = rangeToMove.toMove, afterLast = rangeToMove.afterLast; + ts.getRangesWhere(toMove, function (s) { return !isPureImport(s); }, function (start, afterEndIndex) { + for (var i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast: afterLast }); + }); + return all.length === 0 ? undefined : { all: all, ranges: ranges }; + } + function isPureImport(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + return true; + case 246 /* ImportEqualsDeclaration */: + return !ts.hasModifier(node, 1 /* Export */); + case 217 /* VariableStatement */: + return node.declarationList.declarations.every(function (d) { return !!d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); }); + default: + return false; + } + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + var cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + var newFileAbsolutePath = ts.normalizePath(ts.combinePaths(oldFileName, "..", newFileNameWithExtension)); + var newFilePath = ts.getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); + var cfgObject = cfg.statements[0] && ts.tryCast(cfg.statements[0].expression, ts.isObjectLiteralExpression); + var filesProp = cfgObject && ts.find(cfgObject.properties, function (prop) { + return ts.isPropertyAssignment(prop) && ts.isStringLiteral(prop.name) && prop.name.text === "files"; + }); + if (filesProp && ts.isArrayLiteralExpression(filesProp.initializer)) { + changes.insertNodeInListAfter(cfg, ts.last(filesProp.initializer.elements), ts.createLiteral(newFilePath), filesProp.initializer.elements); + } + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, newModuleName, preferences) { + var checker = program.getTypeChecker(); + if (!oldFile.externalModuleIndicator && !oldFile.commonJsModuleIndicator) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return toMove.all; + } + var useEs6ModuleSyntax = !!oldFile.externalModuleIndicator; + var quotePreference = ts.getQuotePreference(oldFile, preferences); + var importsFromNewFile = createOldFileImportsFromNewFile(usage.oldFileImportsFromNewFile, newModuleName, useEs6ModuleSyntax, quotePreference); + if (importsFromNewFile) { + ts.insertImport(changes, oldFile, importsFromNewFile); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, oldFile, usage.movedSymbols, newModuleName); + return getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference).concat(addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEs6ModuleSyntax)); + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (var _i = 0, moved_1 = moved; _i < moved_1.length; _i++) { + var _a = moved_1[_i], first_1 = _a.first, afterLast = _a.afterLast; + changes.deleteNodeRangeExcludingEnd(sourceFile, first_1, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.contains(toMove, statement)) + continue; + forEachImportInStatement(statement, function (i) { return deleteUnusedImports(oldFile, i, changes, function (name) { return toDelete.has(checker.getSymbolAtLocation(name)); }); }); + } + } + function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { + var checker = program.getTypeChecker(); + var _loop_27 = function (sourceFile) { + if (sourceFile === oldFile) + return "continue"; + var _loop_28 = function (statement) { + forEachImportInStatement(statement, function (importNode) { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + var shouldMove = function (name) { + var symbol = ts.isBindingElement(name.parent) + ? ts.getPropertySymbolFromBindingElement(checker, name.parent) + : ts.skipAlias(checker.getSymbolAtLocation(name), checker); // TODO: GH#18217 + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); // These will be changed to imports from the new file + var newModuleSpecifier = ts.combinePaths(ts.getDirectoryPath(moduleSpecifierFromImport(importNode).text), newModuleName); + var newImportDeclaration = filterImport(importNode, ts.createLiteral(newModuleSpecifier), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + var ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, ns, importNode); + }); + }; + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + _loop_28(statement); + } + }; + for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + _loop_27(sourceFile); + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 247 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 249 /* NamespaceImport */ ? + node.importClause.namedBindings.name : undefined; + case 246 /* ImportEqualsDeclaration */: + return node.name; + case 235 /* VariableDeclaration */: + return ts.tryCast(node.name, ts.isIdentifier); + default: + return ts.Debug.assertNever(node); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleName, newModuleSpecifier, oldImportId, oldImportNode) { + var preferredNewNamespaceName = ts.codefix.moduleSpecifierToValidIdentifier(newModuleName, 6 /* ESNext */); + var needUniqueName = false; + var toChange = []; + ts.FindAllReferences.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, function (ref) { + if (!ts.isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName(preferredNewNamespaceName, ref, 67108863 /* All */, /*excludeGlobals*/ true); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + var newNamespaceName = needUniqueName ? ts.getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (var _i = 0, toChange_1 = toChange; _i < toChange_1.length; _i++) { + var ref = toChange_1[_i]; + changes.replaceNode(sourceFile, ref, ts.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, newModuleName, newModuleSpecifier)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier) { + var newNamespaceId = ts.createIdentifier(newNamespaceName); + var newModuleString = ts.createLiteral(newModuleSpecifier); + switch (node.kind) { + case 247 /* ImportDeclaration */: + return ts.createImportDeclaration( + /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(newNamespaceId)), newModuleString); + case 246 /* ImportEqualsDeclaration */: + return ts.createImportEqualsDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, newNamespaceId, ts.createExternalModuleReference(newModuleString)); + case 235 /* VariableDeclaration */: + return ts.createVariableDeclaration(newNamespaceId, /*type*/ undefined, createRequireCall(newModuleString)); + default: + return ts.Debug.assertNever(node); + } + } + function moduleSpecifierFromImport(i) { + return (i.kind === 247 /* ImportDeclaration */ ? i.moduleSpecifier + : i.kind === 246 /* ImportEqualsDeclaration */ ? i.moduleReference.expression + : i.initializer.arguments[0]); + } + function forEachImportInStatement(statement, cb) { + if (ts.isImportDeclaration(statement)) { + if (ts.isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } + else if (ts.isImportEqualsDeclaration(statement)) { + if (ts.isExternalModuleReference(statement.moduleReference) && ts.isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } + else if (ts.isVariableStatement(statement)) { + for (var _i = 0, _a = statement.declarationList.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true)) { + cb(decl); + } + } + } + } + function createOldFileImportsFromNewFile(newFileNeedExport, newFileNameWithExtension, useEs6Imports, quotePreference) { + var defaultImport; + var imports = []; + newFileNeedExport.forEach(function (symbol) { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = ts.createIdentifier(ts.symbolNameNoDefault(symbol)); // TODO: GH#18217 + } + else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(defaultImport, imports, newFileNameWithExtension, useEs6Imports, quotePreference); + } + function makeImportOrRequire(defaultImport, imports, path, useEs6Imports, quotePreference) { + path = ts.ensurePathIsNonModuleName(path); + if (useEs6Imports) { + var specifiers = imports.map(function (i) { return ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(i)); }); + return ts.makeImportIfNecessary(defaultImport, specifiers, path, quotePreference); + } + else { + ts.Debug.assert(!defaultImport); // If there's a default export, it should have been an es6 module. + var bindingElements = imports.map(function (i) { return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, i); }); + return bindingElements.length + ? makeVariableStatement(ts.createObjectBindingPattern(bindingElements), /*type*/ undefined, createRequireCall(ts.createLiteral(path))) + : undefined; + } + } + function makeVariableStatement(name, type, initializer, flags) { + if (flags === void 0) { flags = 2 /* Const */; } + return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(name, type, initializer)], flags)); + } + function createRequireCall(moduleSpecifier) { + return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, [moduleSpecifier]); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return ts.flatMap(toMove, function (statement) { + if (isTopLevelDeclarationStatement(statement) && + !isExported(sourceFile, statement, useEs6Exports) && + forEachTopLevelDeclaration(statement, function (d) { return needExport.has(ts.Debug.assertDefined(d.symbol)); })) { + var exports_3 = addExport(statement, useEs6Exports); + if (exports_3) + return exports_3; + } + return statement; + }); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 247 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 246 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 235 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + ts.Debug.assertNever(importDecl); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + var _a = importDecl.importClause, name = _a.name, namedBindings = _a.namedBindings; + var defaultUnused = !name || isUnused(name); + var namedBindingsUnused = !namedBindings || + (namedBindings.kind === 249 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.every(function (e) { return isUnused(e.name); })); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } + else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.delete(sourceFile, namedBindings); + } + else if (namedBindings.kind === 250 /* NamedImports */) { + for (var _i = 0, _b = namedBindings.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + var name = varDecl.name; + switch (name.kind) { + case 71 /* Identifier */: + if (isUnused(name)) { + changes.delete(sourceFile, name); + } + break; + case 183 /* ArrayBindingPattern */: + break; + case 182 /* ObjectBindingPattern */: + if (name.elements.every(function (e) { return ts.isIdentifier(e.name) && isUnused(e.name); })) { + changes.delete(sourceFile, ts.isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); + } + else { + for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (ts.isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, useEs6ModuleSyntax, quotePreference) { + var copiedOldImports = []; + for (var _i = 0, _a = oldFile.statements; _i < _a.length; _i++) { + var oldStatement = _a[_i]; + forEachImportInStatement(oldStatement, function (i) { + ts.append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), function (name) { return importsToCopy.has(checker.getSymbolAtLocation(name)); })); + }); + } + // Also, import things used from the old file, and insert 'export' modifiers as necessary in the old file. + var oldFileDefault; + var oldFileNamedImports = []; + var markSeenTop = ts.nodeSeenTracker(); // Needed because multiple declarations may appear in `const x = 0, y = 1;`. + newFileImportsFromOldFile.forEach(function (symbol) { + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (!isTopLevelDeclaration(decl)) + continue; + var name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + var top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, changes, useEs6ModuleSyntax); + } + if (ts.hasModifier(decl, 512 /* Default */)) { + oldFileDefault = name; + } + else { + oldFileNamedImports.push(name.text); + } + } + }); + ts.append(copiedOldImports, makeImportOrRequire(oldFileDefault, oldFileNamedImports, ts.removeFileExtension(ts.getBaseFileName(oldFile.fileName)), useEs6ModuleSyntax, quotePreference)); + return copiedOldImports; + } + function makeUniqueModuleName(moduleName, extension, inDirectory, host) { + var newModuleName = moduleName; + for (var i = 1;; i++) { + var name = ts.combinePaths(inDirectory, newModuleName + extension); + if (!host.fileExists(name)) + return newModuleName; // TODO: GH#18217 + newModuleName = moduleName + "." + i; + } + } + function getNewModuleName(movedSymbols) { + return movedSymbols.forEachEntry(ts.symbolNameNoDefault) || "newFile"; + } + function getUsageInfo(oldFile, toMove, checker) { + var movedSymbols = new SymbolSet(); + var oldImportsNeededByNewFile = new SymbolSet(); + var newFileImportsFromOldFile = new SymbolSet(); + for (var _i = 0, toMove_1 = toMove; _i < toMove_1.length; _i++) { + var statement = toMove_1[_i]; + forEachTopLevelDeclaration(statement, function (decl) { + movedSymbols.add(ts.Debug.assertDefined(ts.isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol)); + }); + } + for (var _a = 0, toMove_2 = toMove; _a < toMove_2.length; _a++) { + var statement = toMove_2[_a]; + forEachReference(statement, checker, function (symbol) { + if (!symbol.declarations) + return; + for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + if (isInImport(decl)) { + oldImportsNeededByNewFile.add(symbol); + } + else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + newFileImportsFromOldFile.add(symbol); + } + } + }); + } + var unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); + var oldFileImportsFromNewFile = new SymbolSet(); + for (var _b = 0, _c = oldFile.statements; _b < _c.length; _b++) { + var statement = _c[_b]; + if (ts.contains(toMove, statement)) + continue; + forEachReference(statement, checker, function (symbol) { + if (movedSymbols.has(symbol)) + oldFileImportsFromNewFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols: movedSymbols, newFileImportsFromOldFile: newFileImportsFromOldFile, oldFileImportsFromNewFile: oldFileImportsFromNewFile, oldImportsNeededByNewFile: oldImportsNeededByNewFile, unusedImportsFromOldFile: unusedImportsFromOldFile }; + } + // Below should all be utilities + function isInImport(decl) { + switch (decl.kind) { + case 246 /* ImportEqualsDeclaration */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: + return true; + case 235 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 184 /* BindingElement */: + return ts.isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return ts.isSourceFile(decl.parent.parent.parent) && + decl.initializer && ts.isRequireCall(decl.initializer, /*checkArgumentIsStringLiteralLike*/ true); + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 247 /* ImportDeclaration */: { + var clause = i.importClause; + if (!clause) + return undefined; + var defaultImport = clause.name && keep(clause.name) ? clause.name : undefined; + var namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings + ? ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(defaultImport, namedBindings), moduleSpecifier) + : undefined; + } + case 246 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : undefined; + case 235 /* VariableDeclaration */: { + var name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : undefined; + } + default: + return ts.Debug.assertNever(i); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 249 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : undefined; + } + else { + var newElements = namedBindings.elements.filter(function (e) { return keep(e.name); }); + return newElements.length ? ts.createNamedImports(newElements) : undefined; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 71 /* Identifier */: + return keep(name) ? name : undefined; + case 183 /* ArrayBindingPattern */: + return name; + case 182 /* ObjectBindingPattern */: { + // We can't handle nested destructurings or property names well here, so just copy them all. + var newElements = name.elements.filter(function (prop) { return prop.propertyName || !ts.isIdentifier(prop.name) || keep(prop.name); }); + return newElements.length ? ts.createObjectBindingPattern(newElements) : undefined; + } + } + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node) { + if (ts.isIdentifier(node) && !ts.isDeclarationName(node)) { + var sym = checker.getSymbolAtLocation(node); + if (sym) + onReference(sym); + } + else { + node.forEachChild(cb); + } + }); + } + var SymbolSet = /** @class */ (function () { + function SymbolSet() { + this.map = ts.createMap(); + } + SymbolSet.prototype.add = function (symbol) { + this.map.set(String(ts.getSymbolId(symbol)), symbol); + }; + SymbolSet.prototype.has = function (symbol) { + return this.map.has(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.delete = function (symbol) { + this.map.delete(String(ts.getSymbolId(symbol))); + }; + SymbolSet.prototype.forEach = function (cb) { + this.map.forEach(cb); + }; + SymbolSet.prototype.forEachEntry = function (cb) { + return ts.forEachEntry(this.map, cb); + }; + SymbolSet.prototype.clone = function () { + var clone = new SymbolSet(); + ts.copyEntries(this.map, clone.map); + return clone; + }; + return SymbolSet; + }()); + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && ts.isSourceFile(node.parent) || ts.isVariableDeclaration(node) && ts.isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return ts.isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function isTopLevelDeclarationStatement(node) { + ts.Debug.assert(ts.isSourceFile(node.parent)); + return isNonVariableTopLevelDeclaration(node) || ts.isVariableStatement(node); + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return cb(statement); + case 217 /* VariableStatement */: + return ts.forEach(statement.declarationList.declarations, cb); + case 219 /* ExpressionStatement */: { + var expression = statement.expression; + return ts.isBinaryExpression(expression) && ts.getSpecialPropertyAssignmentKind(expression) === 1 /* ExportsProperty */ + ? cb(statement) + : undefined; + } + } + } + function nameOfTopLevelDeclaration(d) { + return d.kind === 219 /* ExpressionStatement */ ? d.expression.left.name : ts.tryCast(d.name, ts.isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + return ts.isVariableDeclaration(d) ? d.parent.parent : d; + } + function addExportToChanges(sourceFile, decl, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports)) + return; + if (useEs6Exports) { + if (!ts.isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } + else { + var names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function isExported(sourceFile, decl, useEs6Exports) { + if (useEs6Exports) { + return !ts.isExpressionStatement(decl) && ts.hasModifier(decl, 1 /* Export */); + } + else { + return getNamesToExportInCommonJS(decl).some(function (name) { return sourceFile.symbol.exports.has(ts.escapeLeadingUnderscores(name)); }); + } + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + var modifiers = ts.concatenate([ts.createModifier(84 /* ExportKeyword */)], d.modifiers); + switch (d.kind) { + case 237 /* FunctionDeclaration */: + return ts.updateFunctionDeclaration(d, d.decorators, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 238 /* ClassDeclaration */: + return ts.updateClassDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 217 /* VariableStatement */: + return ts.updateVariableStatement(d, modifiers, d.declarationList); + case 242 /* ModuleDeclaration */: + return ts.updateModuleDeclaration(d, d.decorators, modifiers, d.name, d.body); + case 241 /* EnumDeclaration */: + return ts.updateEnumDeclaration(d, d.decorators, modifiers, d.name, d.members); + case 240 /* TypeAliasDeclaration */: + return ts.updateTypeAliasDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.type); + case 239 /* InterfaceDeclaration */: + return ts.updateInterfaceDeclaration(d, d.decorators, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 246 /* ImportEqualsDeclaration */: + return ts.updateImportEqualsDeclaration(d, d.decorators, modifiers, d.name, d.moduleReference); + case 219 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(d); + } + } + function addCommonjsExport(decl) { + return [decl].concat(getNamesToExportInCommonJS(decl).map(createExportAssignment)); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 237 /* FunctionDeclaration */: + case 238 /* ClassDeclaration */: + return [decl.name.text]; // TODO: GH#18217 + case 217 /* VariableStatement */: + return ts.mapDefined(decl.declarationList.declarations, function (d) { return ts.isIdentifier(d.name) ? d.name.text : undefined; }); + case 242 /* ModuleDeclaration */: + case 241 /* EnumDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 246 /* ImportEqualsDeclaration */: + return ts.emptyArray; + case 219 /* ExpressionStatement */: + return ts.Debug.fail(); // Shouldn't try to add 'export' keyword to `exports.x = ...` + default: + return ts.Debug.assertNever(decl); + } + } + /** Creates `exports.x = x;` */ + function createExportAssignment(name) { + return ts.createExpressionStatement(ts.createBinary(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(name)), 58 /* EqualsToken */, ts.createIdentifier(name))); + } + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var refactor; + (function (refactor) { + var addOrRemoveBracesToArrowFunction; + (function (addOrRemoveBracesToArrowFunction) { + var refactorName = "Add or remove braces in an arrow function"; + var refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + var addBracesActionName = "Add braces to arrow function"; + var removeBracesActionName = "Remove braces from arrow function"; + var addBracesActionDescription = ts.Diagnostics.Add_braces_to_arrow_function.message; + var removeBracesActionDescription = ts.Diagnostics.Remove_braces_from_arrow_function.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); + function getAvailableActions(context) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + return [{ + name: refactorName, + description: refactorDescription, + actions: [ + info.addBraces ? + { + name: addBracesActionName, + description: addBracesActionDescription + } : { + name: removeBracesActionName, + description: removeBracesActionDescription + } + ] + }]; + } + function getEditsForAction(context, actionName) { + var file = context.file, startPosition = context.startPosition; + var info = getConvertibleArrowFunctionAtPosition(file, startPosition); + if (!info) + return undefined; + var expression = info.expression, returnStatement = info.returnStatement, func = info.func; + var body; + if (actionName === addBracesActionName) { + var returnStatement_1 = ts.createReturn(expression); + body = ts.createBlock([returnStatement_1], /* multiLine */ true); + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(expression, returnStatement_1, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ true); + } + else if (actionName === removeBracesActionName && returnStatement) { + var actualExpression = expression || ts.createVoidZero(); + body = needsParentheses(actualExpression) ? ts.createParen(actualExpression) : actualExpression; + ts.suppressLeadingAndTrailingTrivia(body); + ts.copyComments(returnStatement, body, file, 3 /* MultiLineCommentTrivia */, /* hasTrailingNewLine */ false); + } + else { + ts.Debug.fail("invalid action"); + } + var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(file, func.body, body); }); + return { renameFilename: undefined, renameLocation: undefined, edits: edits }; + } + function needsParentheses(expression) { + return ts.isBinaryExpression(expression) && expression.operatorToken.kind === 26 /* CommaToken */ || ts.isObjectLiteralExpression(expression); + } + function getConvertibleArrowFunctionAtPosition(file, startPosition) { + var node = ts.getTokenAtPosition(file, startPosition); + var func = ts.getContainingFunction(node); + if (!func || !ts.isArrowFunction(func) || (!ts.rangeContainsRange(func, node) || ts.rangeContainsRange(func.body, node))) + return undefined; + if (ts.isExpression(func.body)) { + return { + func: func, + addBraces: true, + expression: func.body + }; + } + else if (func.body.statements.length === 1) { + var firstStatement = ts.first(func.body.statements); + if (ts.isReturnStatement(firstStatement)) { + return { + func: func, + addBraces: false, + expression: firstStatement.expression, + returnStatement: firstStatement + }; + } + } + return undefined; + } + })(addOrRemoveBracesToArrowFunction = refactor.addOrRemoveBracesToArrowFunction || (refactor.addOrRemoveBracesToArrowFunction = {})); + })(refactor = ts.refactor || (ts.refactor = {})); +})(ts || (ts = {})); var ts; (function (ts) { /** The version of the language service API */ - ts.servicesVersion = "0.7"; + ts.servicesVersion = "0.8"; function createNode(kind, pos, end, parent) { var node = ts.isNodeKind(kind) ? new NodeObject(kind, pos, end) : kind === 71 /* Identifier */ ? new IdentifierObject(71 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; - node.flags = parent.flags & 6387712 /* ContextFlags */; + node.flags = parent.flags & 12679168 /* ContextFlags */; return node; } var NodeObject = /** @class */ (function () { @@ -101601,7 +110105,7 @@ var ts; this.pos = pos; this.end = end; this.flags = 0 /* None */; - this.transformFlags = undefined; + this.transformFlags = undefined; // TODO: GH#18217 this.parent = undefined; this.kind = kind; } @@ -101647,104 +110151,15 @@ var ts; } return sourceFile.text.substring(this.getStart(sourceFile), this.getEnd()); }; - NodeObject.prototype.addSyntheticNodes = function (nodes, pos, end) { - ts.scanner.setTextPos(pos); - while (pos < end) { - var token = ts.scanner.scan(); - var textPos = ts.scanner.getTextPos(); - if (textPos <= end) { - if (token === 71 /* Identifier */) { - ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(this) + " to have an Identifier in its trivia"); - } - nodes.push(createNode(token, pos, textPos, this)); - } - pos = textPos; - if (token === 1 /* EndOfFileToken */) { - break; - } - } - return pos; - }; - NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(293 /* SyntaxList */, nodes.pos, nodes.end, this); - list._children = []; - var pos = nodes.pos; - for (var _i = 0, nodes_9 = nodes; _i < nodes_9.length; _i++) { - var node = nodes_9[_i]; - if (pos < node.pos) { - pos = this.addSyntheticNodes(list._children, pos, node.pos); - } - list._children.push(node); - pos = node.end; - } - if (pos < nodes.end) { - this.addSyntheticNodes(list._children, pos, nodes.end); - } - return list; - }; - NodeObject.prototype.createChildren = function (sourceFile) { - var _this = this; - if (!ts.isNodeKind(this.kind)) { - this._children = ts.emptyArray; - return; - } - if (ts.isJSDocCommentContainingNode(this)) { - /** Don't add trivia for "tokens" since this is in a comment. */ - var children_4 = []; - this.forEachChild(function (child) { children_4.push(child); }); - this._children = children_4; - return; - } - var children = []; - ts.scanner.setText((sourceFile || this.getSourceFile()).text); - var pos = this.pos; - var processNode = function (node) { - pos = _this.addSyntheticNodes(children, pos, node.pos); - children.push(node); - pos = node.end; - }; - var processNodes = function (nodes) { - if (pos < nodes.pos) { - pos = _this.addSyntheticNodes(children, pos, nodes.pos); - } - children.push(_this.createSyntaxList(nodes)); - pos = nodes.end; - }; - // jsDocComments need to be the first children - if (this.jsDoc) { - for (var _i = 0, _a = this.jsDoc; _i < _a.length; _i++) { - var jsDocComment = _a[_i]; - processNode(jsDocComment); - } - } - // For syntactic classifications, all trivia are classcified together, including jsdoc comments. - // For that to work, the jsdoc comments should still be the leading trivia of the first child. - // Restoring the scanner position ensures that. - pos = this.pos; - ts.forEachChild(this, processNode, processNodes); - if (pos < this.end) { - this.addSyntheticNodes(children, pos, this.end); - } - ts.scanner.setText(undefined); - this._children = children; - }; NodeObject.prototype.getChildCount = function (sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children.length; + return this.getChildren(sourceFile).length; }; NodeObject.prototype.getChildAt = function (index, sourceFile) { - this.assertHasRealPosition(); - if (!this._children) - this.createChildren(sourceFile); - return this._children[index]; + return this.getChildren(sourceFile)[index]; }; NodeObject.prototype.getChildren = function (sourceFile) { this.assertHasRealPosition("Node without a real position cannot be scanned and thus has no token nodes - use forEachChild and collect the result if that's fine"); - if (!this._children) - this.createChildren(sourceFile); - return this._children; + return this._children || (this._children = createChildren(this, sourceFile)); }; NodeObject.prototype.getFirstToken = function (sourceFile) { this.assertHasRealPosition(); @@ -101752,8 +110167,8 @@ var ts; if (!children.length) { return undefined; } - var child = ts.find(children, function (kid) { return kid.kind < 274 /* FirstJSDocNode */ || kid.kind > 292 /* LastJSDocNode */; }); - return child.kind < 145 /* FirstNode */ ? + var child = ts.find(children, function (kid) { return kid.kind < 281 /* FirstJSDocNode */ || kid.kind > 302 /* LastJSDocNode */; }); + return child.kind < 146 /* FirstNode */ ? child : child.getFirstToken(sourceFile); }; @@ -101764,13 +110179,76 @@ var ts; if (!child) { return undefined; } - return child.kind < 145 /* FirstNode */ ? child : child.getLastToken(sourceFile); + return child.kind < 146 /* FirstNode */ ? child : child.getLastToken(sourceFile); }; NodeObject.prototype.forEachChild = function (cbNode, cbNodeArray) { return ts.forEachChild(this, cbNode, cbNodeArray); }; return NodeObject; }()); + function createChildren(node, sourceFile) { + if (!ts.isNodeKind(node.kind)) { + return ts.emptyArray; + } + var children = []; + if (ts.isJSDocCommentContainingNode(node)) { + /** Don't add trivia for "tokens" since this is in a comment. */ + node.forEachChild(function (child) { children.push(child); }); + return children; + } + ts.scanner.setText((sourceFile || node.getSourceFile()).text); + var pos = node.pos; + var processNode = function (child) { + addSyntheticNodes(children, pos, child.pos, node); + children.push(child); + pos = child.end; + }; + var processNodes = function (nodes) { + addSyntheticNodes(children, pos, nodes.pos, node); + children.push(createSyntaxList(nodes, node)); + pos = nodes.end; + }; + // jsDocComments need to be the first children + ts.forEach(node.jsDoc, processNode); + // For syntactic classifications, all trivia are classified together, including jsdoc comments. + // For that to work, the jsdoc comments should still be the leading trivia of the first child. + // Restoring the scanner position ensures that. + pos = node.pos; + node.forEachChild(processNode, processNodes); + addSyntheticNodes(children, pos, node.end, node); + ts.scanner.setText(undefined); + return children; + } + function addSyntheticNodes(nodes, pos, end, parent) { + ts.scanner.setTextPos(pos); + while (pos < end) { + var token = ts.scanner.scan(); + var textPos = ts.scanner.getTextPos(); + if (textPos <= end) { + if (token === 71 /* Identifier */) { + ts.Debug.fail("Did not expect " + ts.Debug.showSyntaxKind(parent) + " to have an Identifier in its trivia"); + } + nodes.push(createNode(token, pos, textPos, parent)); + } + pos = textPos; + if (token === 1 /* EndOfFileToken */) { + break; + } + } + } + function createSyntaxList(nodes, parent) { + var list = createNode(303 /* SyntaxList */, nodes.pos, nodes.end, parent); + list._children = []; + var pos = nodes.pos; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; + addSyntheticNodes(list._children, pos, node.pos, parent); + list._children.push(node); + pos = node.end; + } + addSyntheticNodes(list._children, pos, nodes.end, parent); + return list; + } var TokenOrIdentifierObject = /** @class */ (function () { function TokenOrIdentifierObject(pos, end) { // Set properties in same order as NodeObject @@ -101813,10 +110291,10 @@ var ts; return 0; }; TokenOrIdentifierObject.prototype.getChildAt = function () { - return undefined; + return undefined; // TODO: GH#18217 }; TokenOrIdentifierObject.prototype.getChildren = function () { - return ts.emptyArray; + return this.kind === 1 /* EndOfFileToken */ ? this.jsDoc || ts.emptyArray : ts.emptyArray; }; TokenOrIdentifierObject.prototype.getFirstToken = function () { return undefined; @@ -101854,28 +110332,9 @@ var ts; return this.declarations; }; SymbolObject.prototype.getDocumentationComment = function (checker) { - if (this.documentationComment === undefined) { - if (this.declarations) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations(this.declarations); - if (this.documentationComment.length === 0 || this.declarations.some(hasJSDocInheritDocTag)) { - if (checker) { - for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; - var inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); - if (inheritedDocs.length > 0) { - if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); - } - this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); - break; - } - } - } - } - } - else { - this.documentationComment = []; - } + if (!this.documentationComment) { + this.documentationComment = ts.emptyArray; // Set temporarily to avoid an infinite loop finding inherited docs + this.documentationComment = getDocumentationComment(this.declarations, checker); } return this.documentationComment; }; @@ -101944,9 +110403,7 @@ var ts; return this.checker.getIndexTypeOfType(this, 1 /* Number */); }; TypeObject.prototype.getBaseTypes = function () { - return this.flags & 65536 /* Object */ && this.objectFlags & (1 /* Class */ | 2 /* Interface */) - ? this.checker.getBaseTypes(this) - : undefined; + return this.isClassOrInterface() ? this.checker.getBaseTypes(this) : undefined; }; TypeObject.prototype.getNonNullableType = function () { return this.checker.getNonNullableType(this); @@ -101957,6 +110414,33 @@ var ts; TypeObject.prototype.getDefault = function () { return this.checker.getDefaultFromTypeParameter(this); }; + TypeObject.prototype.isUnion = function () { + return !!(this.flags & 262144 /* Union */); + }; + TypeObject.prototype.isIntersection = function () { + return !!(this.flags & 524288 /* Intersection */); + }; + TypeObject.prototype.isUnionOrIntersection = function () { + return !!(this.flags & 786432 /* UnionOrIntersection */); + }; + TypeObject.prototype.isLiteral = function () { + return !!(this.flags & 192 /* StringOrNumberLiteral */); + }; + TypeObject.prototype.isStringLiteral = function () { + return !!(this.flags & 64 /* StringLiteral */); + }; + TypeObject.prototype.isNumberLiteral = function () { + return !!(this.flags & 128 /* NumberLiteral */); + }; + TypeObject.prototype.isTypeParameter = function () { + return !!(this.flags & 65536 /* TypeParameter */); + }; + TypeObject.prototype.isClassOrInterface = function () { + return !!(ts.getObjectFlags(this) & 3 /* ClassOrInterface */); + }; + TypeObject.prototype.isClass = function () { + return !!(ts.getObjectFlags(this) & 1 /* Class */); + }; return TypeObject; }()); var SignatureObject = /** @class */ (function () { @@ -101976,22 +110460,7 @@ var ts; return this.checker.getReturnTypeOfSignature(this); }; SignatureObject.prototype.getDocumentationComment = function () { - if (this.documentationComment === undefined) { - if (this.declaration) { - this.documentationComment = ts.JsDoc.getJsDocCommentsFromDeclarations([this.declaration]); - if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { - var inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); - if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); - } - this.documentationComment = ts.concatenate(inheritedDocs, this.documentationComment); - } - } - else { - this.documentationComment = []; - } - } - return this.documentationComment; + return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); }; SignatureObject.prototype.getJsDocTags = function () { if (this.jsDocTags === undefined) { @@ -102009,6 +110478,21 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } + function getDocumentationComment(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); + if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { + for (var _i = 0, declarations_14 = declarations; _i < declarations_14.length; _i++) { + var declaration = declarations_14[_i]; + var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 + // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs + if (inheritedDocs) + doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + } + } + return doc; + } /** * Attempts to find JSDoc comments for possibly-inherited properties. Checks superclasses then traverses * implemented interfaces until a symbol is found with the same name and with documentation. @@ -102018,38 +110502,13 @@ var ts; * @returns A filled array of documentation comments if any were found, otherwise an empty array. */ function findInheritedJSDocComments(declaration, propertyName, typeChecker) { - var foundDocs = false; - return ts.flatMap(getAllSuperTypeNodes(declaration), function (superTypeNode) { - if (foundDocs) { - return ts.emptyArray; - } + return ts.firstDefined(declaration.parent ? ts.getAllSuperTypeNodes(declaration.parent) : ts.emptyArray, function (superTypeNode) { var superType = typeChecker.getTypeAtLocation(superTypeNode); - if (!superType) { - return ts.emptyArray; - } - var baseProperty = typeChecker.getPropertyOfType(superType, propertyName); - if (!baseProperty) { - return ts.emptyArray; - } - var inheritedDocs = baseProperty.getDocumentationComment(typeChecker); - foundDocs = inheritedDocs.length > 0; - return inheritedDocs; + var baseProperty = superType && typeChecker.getPropertyOfType(superType, propertyName); + var inheritedDocs = baseProperty && baseProperty.getDocumentationComment(typeChecker); + return inheritedDocs && inheritedDocs.length ? inheritedDocs : undefined; }); } - /** - * Finds and returns the `TypeNode` for all super classes and implemented interfaces given a declaration. - * @param declaration The possibly-inherited declaration. - * @returns A filled array of `TypeNode`s containing all super classes and implemented interfaces if any exist, otherwise an empty array. - */ - function getAllSuperTypeNodes(declaration) { - var container = declaration.parent; - if (!container || (!ts.isClassDeclaration(container) && !ts.isInterfaceDeclaration(container))) { - return ts.emptyArray; - } - var extended = ts.getClassExtendsHeritageClauseElement(container); - var types = extended ? [extended] : ts.emptyArray; - return ts.isClassLike(container) ? ts.concatenate(types, ts.getClassImplementsHeritageClauseElements(container)) : types; - } var SourceFileObject = /** @class */ (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { @@ -102089,7 +110548,7 @@ var ts; }; SourceFileObject.prototype.computeNamedDeclarations = function () { var result = ts.createMultiMap(); - ts.forEachChild(this, visit); + this.forEachChild(visit); return result; function addDeclaration(declaration) { var name = getDeclarationName(declaration); @@ -102105,16 +110564,16 @@ var ts; return declarations; } function getDeclarationName(declaration) { - var name = ts.getNameOfDeclaration(declaration); - return name && (ts.isPropertyNameLiteral(name) ? ts.getTextOfIdentifierOrLiteral(name) : - name.kind === 146 /* ComputedPropertyName */ && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text : undefined); + var name = ts.getNonAssignedNameOfDeclaration(declaration); + return name && (ts.isComputedPropertyName(name) && ts.isPropertyAccessExpression(name.expression) ? name.expression.name.text + : ts.isPropertyName(name) ? ts.getNameFromPropertyName(name) : undefined); } function visit(node) { switch (node.kind) { - case 232 /* FunctionDeclaration */: - case 190 /* FunctionExpression */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: + case 237 /* FunctionDeclaration */: + case 194 /* FunctionExpression */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: var functionDeclaration = node; var declarationName = getDeclarationName(functionDeclaration); if (declarationName) { @@ -102134,31 +110593,31 @@ var ts; } ts.forEachChild(node, visit); break; - case 233 /* ClassDeclaration */: - case 203 /* ClassExpression */: - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: - case 236 /* EnumDeclaration */: - case 237 /* ModuleDeclaration */: - case 241 /* ImportEqualsDeclaration */: - case 250 /* ExportSpecifier */: - case 246 /* ImportSpecifier */: - case 243 /* ImportClause */: - case 244 /* NamespaceImport */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 165 /* TypeLiteral */: + case 238 /* ClassDeclaration */: + case 207 /* ClassExpression */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: + case 241 /* EnumDeclaration */: + case 242 /* ModuleDeclaration */: + case 246 /* ImportEqualsDeclaration */: + case 255 /* ExportSpecifier */: + case 251 /* ImportSpecifier */: + case 248 /* ImportClause */: + case 249 /* NamespaceImport */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 166 /* TypeLiteral */: addDeclaration(node); ts.forEachChild(node, visit); break; - case 148 /* Parameter */: + case 149 /* Parameter */: // Only consider parameter properties if (!ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { break; } // falls through - case 230 /* VariableDeclaration */: - case 180 /* BindingElement */: { + case 235 /* VariableDeclaration */: + case 184 /* BindingElement */: { var decl = node; if (ts.isBindingPattern(decl.name)) { ts.forEachChild(decl.name, visit); @@ -102169,31 +110628,31 @@ var ts; } } // falls through - case 271 /* EnumMember */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 276 /* EnumMember */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: addDeclaration(node); break; - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // Handle named exports case e.g.: // export {a, b as B} from "mod"; if (node.exportClause) { ts.forEach(node.exportClause.elements, visit); } break; - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: var importClause = node.importClause; if (importClause) { // Handle default import case e.g.: // import d from "mod"; if (importClause.name) { - addDeclaration(importClause); + addDeclaration(importClause.name); } // Handle named bindings in imports e.g.: // import * as NS from "mod"; // import {a, b as B} from "mod"; if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 244 /* NamespaceImport */) { + if (importClause.namedBindings.kind === 249 /* NamespaceImport */) { addDeclaration(importClause.namedBindings); } else { @@ -102202,7 +110661,7 @@ var ts; } } break; - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (ts.getSpecialPropertyAssignmentKind(node) !== 0 /* None */) { addDeclaration(node); } @@ -102301,6 +110760,9 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; + HostCache.prototype.getProjectReferences = function () { + return this.host.getProjectReferences && this.host.getProjectReferences(); + }; HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -102327,20 +110789,29 @@ var ts; }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { var info = this.getEntryByPath(path) || this.createEntry(fileName, path); - return ts.isString(info) ? undefined : info; + return ts.isString(info) ? undefined : info; // TODO: GH#18217 }; HostCache.prototype.getRootFileNames = function () { - return ts.arrayFrom(this.fileNameToEntry.values(), function (entry) { - return ts.isString(entry) ? entry : entry.hostFileName; + var names = []; + this.fileNameToEntry.forEach(function (entry) { + if (ts.isString(entry)) { + names.push(entry); + } + else { + if (entry.scriptKind !== 6 /* JSON */) { + names.push(entry.hostFileName); + } + } }); + return names; }; HostCache.prototype.getVersion = function (path) { var file = this.getHostFileInformation(path); - return file && file.version; + return (file && file.version); // TODO: GH#18217 }; HostCache.prototype.getScriptSnapshot = function (path) { var file = this.getHostFileInformation(path); - return file && file.scriptSnapshot; + return (file && file.scriptSnapshot); // TODO: GH#18217 }; return HostCache; }()); @@ -102443,7 +110914,7 @@ var ts; this.cancellationToken = cancellationToken; } CancellationTokenObject.prototype.isCancellationRequested = function () { - return this.cancellationToken && this.cancellationToken.isCancellationRequested(); + return !!this.cancellationToken && this.cancellationToken.isCancellationRequested(); }; CancellationTokenObject.prototype.throwIfCancellationRequested = function () { if (this.isCancellationRequested()) { @@ -102482,13 +110953,14 @@ var ts; return ThrottledCancellationToken; }()); ts.ThrottledCancellationToken = ThrottledCancellationToken; - function createLanguageService(host, documentRegistry) { + function createLanguageService(host, documentRegistry, syntaxOnly) { if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } + if (syntaxOnly === void 0) { syntaxOnly = false; } + var _a; var syntaxTreeCache = new SyntaxTreeCache(host); var program; var lastProjectVersion; var lastTypesRootVersion = 0; - var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -102500,7 +110972,9 @@ var ts; host.log(message); } } - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitivefileNames); + var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var sourceMapper = ts.getSourceMapper(getCanonicalFileName, currentDirectory, log, host, function () { return program; }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -102509,6 +110983,7 @@ var ts; return sourceFile; } function synchronizeHostData() { + ts.Debug.assert(!syntaxOnly); // perform fast check if host supports it if (host.getProjectVersion) { var hostProjectVersion = host.getProjectVersion(); @@ -102522,7 +110997,7 @@ var ts; var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; if (lastTypesRootVersion !== typeRootsVersion) { log("TypeRoots version has changed; provide new program"); - program = undefined; + program = undefined; // TODO: GH#18217 lastTypesRootVersion = typeRootsVersion; } // Get a fresh cache of the host information @@ -102530,7 +111005,7 @@ var ts; var rootFileNames = hostCache.getRootFileNames(); var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse; // If the program is already up-to-date, we can reuse it - if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, host.hasChangedAutomaticTypeDirectiveNames)) { + if (ts.isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), function (path) { return hostCache.getVersion(path); }, fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { return; } // IMPORTANT - It is critical from this moment onward that we do not check @@ -102545,7 +111020,7 @@ var ts; getSourceFileByPath: getOrCreateSourceFileByPath, getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, - useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, @@ -102554,7 +111029,7 @@ var ts; readFile: function (fileName) { // stub missing host functionality var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); if (entry) { return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } @@ -102583,20 +111058,31 @@ var ts; }; } var documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - program = ts.createProgram(rootFileNames, newSettings, compilerHost, program); + var options = { + rootNames: rootFileNames, + options: newSettings, + host: compilerHost, + oldProgram: program, + projectReferences: hostCache.getProjectReferences() + }; + program = ts.createProgram(options); // hostCache is captured in the closure for 'getOrCreateSourceFile' but it should not be used past this point. // It needs to be cleared to allow all collected snapshots to be released hostCache = undefined; + // We reset this cache on structure invalidation so we don't hold on to outdated files for long; however we can't use the `compilerHost` above, + // Because it only functions until `hostCache` is cleared, while we'll potentially need the functionality to lazily read sourcemap files during + // the course of whatever called `synchronizeHostData` + sourceMapper.clearCache(); // Make sure all the nodes in the program are both bound, and have their parent // pointers set property. program.getTypeChecker(); return; function fileExists(fileName) { var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache.getEntryByPath(path); + var entry = hostCache && hostCache.getEntryByPath(path); return entry ? !ts.isString(entry) : - (host.fileExists && host.fileExists(fileName)); + (!!host.fileExists && host.fileExists(fileName)); } // Release any files we have acquired in the old program but are // not part of the new program. @@ -102608,11 +111094,11 @@ var ts; return getOrCreateSourceFileByPath(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), languageVersion, onError, shouldCreateNewSourceFile); } function getOrCreateSourceFileByPath(fileName, path, _languageVersion, _onError, shouldCreateNewSourceFile) { - ts.Debug.assert(hostCache !== undefined); + ts.Debug.assert(hostCache !== undefined, "getOrCreateSourceFileByPath called after typical CompilerHost lifetime, check the callstack something with a reference to an old host."); // The program is asking for this file, check first if the host can locate it. // If the host can not locate the file, then it does not exist. return undefined // to the program to allow reporting of errors for missing files. - var hostFileInformation = hostCache.getOrCreateEntryByPath(fileName, path); + var hostFileInformation = hostCache && hostCache.getOrCreateEntryByPath(fileName, path); if (!hostFileInformation) { return undefined; } @@ -102656,19 +111142,24 @@ var ts; return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } } + // TODO: GH#18217 frequently asserted as defined function getProgram() { + if (syntaxOnly) { + ts.Debug.assert(program === undefined); + return undefined; + } synchronizeHostData(); return program; } function cleanupSemanticCache() { - program = undefined; + program = undefined; // TODO: GH#18217 } function dispose() { if (program) { ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); - program = undefined; + program = undefined; // TODO: GH#18217 } host = undefined; } @@ -102696,29 +111187,33 @@ var ts; } function getSuggestionDiagnostics(fileName) { synchronizeHostData(); - return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program); + return ts.computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); } function getCompilerOptionsDiagnostics() { synchronizeHostData(); return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } + if (options === void 0) { options = ts.emptyOptions; } + // Convert from deprecated options names to new names + var fullPreferences = __assign({}, ts.identity(options), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter); } - function getCompletionEntryDetails(fileName, position, name, formattingOptions, source) { + function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); - return ts.Completions.getCompletionEntryDetails(program, log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles(), host, formattingOptions && ts.formatting.getFormatContext(formattingOptions), getCanonicalFileName); + return ts.Completions.getCompletionEntryDetails(program, log, getValidSourceFile(fileName), position, { name: name, source: source }, host, (formattingOptions && ts.formatting.getFormatContext(formattingOptions)), // TODO: GH#18217 + preferences, cancellationToken); } function getCompletionEntrySymbol(fileName, position, name, source) { synchronizeHostData(); - return ts.Completions.getCompletionEntrySymbol(program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, { name: name, source: source }, program.getSourceFiles()); + return ts.Completions.getCompletionEntrySymbol(program, log, getValidSourceFile(fileName), position, { name: name, source: source }); } function getQuickInfoAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); + var node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { // Avoid giving quickInfo for the sourceFile as a whole. return undefined; @@ -102734,25 +111229,27 @@ var ts; return undefined; } // falls through - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: case 99 /* ThisKeyword */: - case 173 /* ThisType */: + case 176 /* ThisType */: case 97 /* SuperKeyword */: // For the identifiers/this/super etc get the type at position - var type = typeChecker.getTypeAtLocation(node); - return type && { + var type_4 = typeChecker.getTypeAtLocation(node); + return type_4 && { kind: "" /* unknown */, kindModifiers: "" /* none */, textSpan: ts.createTextSpanFromNode(node, sourceFile), - displayParts: ts.typeToDisplayParts(typeChecker, type, ts.getContainerNode(node)), - documentation: type.symbol ? type.symbol.getDocumentationComment(typeChecker) : undefined, - tags: type.symbol ? type.symbol.getJsDocTags() : undefined + displayParts: typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { return ts.typeToDisplayParts(typeChecker, type_4, ts.getContainerNode(node)); }), + documentation: type_4.symbol ? type_4.symbol.getDocumentationComment(typeChecker) : undefined, + tags: type_4.symbol ? type_4.symbol.getJsDocTags() : undefined }; } return undefined; } - var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; + var _a = typeChecker.runWithCancellationToken(cancellationToken, function (typeChecker) { + return ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, ts.getContainerNode(node), node); + }), symbolKind = _a.symbolKind, displayParts = _a.displayParts, documentation = _a.documentation, tags = _a.tags; return { kind: symbolKind, kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), @@ -102794,58 +111291,62 @@ var ts; } /// References and Occurrences function getOccurrencesAtPosition(fileName, position) { - var canonicalFileName = getCanonicalFileName(ts.normalizeSlashes(fileName)); - return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { - ts.Debug.assert(getCanonicalFileName(ts.normalizeSlashes(entry.fileName)) === canonicalFileName); // Get occurrences only supports reporting occurrences for the file queried. - return { - fileName: entry.fileName, - textSpan: highlightSpan.textSpan, - isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, - isDefinition: false, - isInString: highlightSpan.isInString, - }; - }); }); + return ts.flatMap(getDocumentHighlights(fileName, position, [fileName]), function (entry) { return entry.highlightSpans.map(function (highlightSpan) { return ({ + fileName: entry.fileName, + textSpan: highlightSpan.textSpan, + isWriteAccess: highlightSpan.kind === "writtenReference" /* writtenReference */, + isDefinition: false, + isInString: highlightSpan.isInString, + }); }); }); } function getDocumentHighlights(fileName, position, filesToSearch) { + var normalizedFileName = ts.normalizePath(fileName); + ts.Debug.assert(filesToSearch.some(function (f) { return ts.normalizePath(f) === normalizedFileName; })); synchronizeHostData(); var sourceFilesToSearch = ts.map(filesToSearch, function (f) { return ts.Debug.assertDefined(program.getSourceFile(f)); }); var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } function findRenameLocations(fileName, position, findInStrings, findInComments) { - return getReferences(fileName, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); - } - function getReferencesAtPosition(fileName, position) { - return getReferences(fileName, position); - } - function getReferences(fileName, position, options) { synchronizeHostData(); - // Exclude default library when renaming as commonly user don't want to change that file. - var sourceFiles = []; - if (options && options.isForRename) { - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - sourceFiles.push(sourceFile); - } - } + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (ts.isIdentifier(node) && ts.isJsxOpeningElement(node.parent) || ts.isJsxClosingElement(node.parent)) { + var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; + return [openingElement, closingElement].map(function (node) { return ({ fileName: sourceFile.fileName, textSpan: ts.createTextSpanFromNode(node.tagName, sourceFile) }); }); } else { - sourceFiles = program.getSourceFiles().slice(); + var refs = getReferences(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }); + return refs && refs.map(function (_a) { + var fileName = _a.fileName, textSpan = _a.textSpan; + return ({ fileName: fileName, textSpan: textSpan }); + }); } - return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, getValidSourceFile(fileName), position, options); + } + function getReferencesAtPosition(fileName, position) { + synchronizeHostData(); + return getReferences(ts.getTouchingPropertyName(getValidSourceFile(fileName), position), position); + } + function getReferences(node, position, options) { + synchronizeHostData(); + // Exclude default library when renaming as commonly user don't want to change that file. + var sourceFiles = options && options.isForRename + ? program.getSourceFiles().filter(function (sourceFile) { return !program.isSourceFileDefaultLibrary(sourceFile); }) + : program.getSourceFiles(); + return ts.FindAllReferences.findReferencedEntries(program, cancellationToken, sourceFiles, node, position, options); } function findReferences(fileName, position) { synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program, cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position); } - /// NavigateTo function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { + if (excludeDtsFiles === void 0) { excludeDtsFiles = false; } synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName, emitOnlyDtsFiles) { + if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); @@ -102855,40 +111356,38 @@ var ts; /** * This is a semantic operation. */ - function getSignatureHelpItems(fileName, position) { + function getSignatureHelpItems(fileName, position, _a) { + var triggerReason = (_a === void 0 ? ts.emptyOptions : _a).triggerReason; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); - return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, cancellationToken); + return ts.SignatureHelp.getSignatureHelpItems(program, sourceFile, position, triggerReason, cancellationToken); } /// Syntactic features function getNonBoundSourceFile(fileName) { return syntaxTreeCache.getCurrentSourceFile(fileName); } - function getSourceFile(fileName) { - return getNonBoundSourceFile(fileName); - } function getNameOrDottedNameSpan(fileName, startPos, _endPos) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); // Get node at the location - var node = ts.getTouchingPropertyName(sourceFile, startPos, /*includeJsDocComment*/ false); + var node = ts.getTouchingPropertyName(sourceFile, startPos); if (node === sourceFile) { - return; + return undefined; } switch (node.kind) { - case 183 /* PropertyAccessExpression */: - case 145 /* QualifiedName */: + case 187 /* PropertyAccessExpression */: + case 146 /* QualifiedName */: case 9 /* StringLiteral */: case 86 /* FalseKeyword */: case 101 /* TrueKeyword */: case 95 /* NullKeyword */: case 97 /* SuperKeyword */: case 99 /* ThisKeyword */: - case 173 /* ThisType */: + case 176 /* ThisType */: case 71 /* Identifier */: break; // Cant create the text span default: - return; + return undefined; } var nodeForStartPos = node; while (true) { @@ -102900,7 +111399,7 @@ var ts; // If this is name of a module declarations, check if this is right side of dotted module name // If parent of the module declaration which is parent of this node is module declaration and its body is the module declaration that this node is name of // Then this name is name from dotted module - if (nodeForStartPos.parent.parent.kind === 237 /* ModuleDeclaration */ && + if (nodeForStartPos.parent.parent.kind === 242 /* ModuleDeclaration */ && nodeForStartPos.parent.parent.body === nodeForStartPos.parent) { // Use parent module declarations name for start pos nodeForStartPos = nodeForStartPos.parent.parent.name; @@ -102970,7 +111469,7 @@ var ts; braceMatching.forEach(function (value, key) { return braceMatching.set(value.toString(), Number(key)); }); function getBraceMatchingAtPosition(fileName, position) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var token = ts.getTouchingToken(sourceFile, position, /*includeJsDocComment*/ false); + var token = ts.getTouchingToken(sourceFile, position); var matchKind = token.getStart(sourceFile) === position ? braceMatching.get(token.kind.toString()) : undefined; var match = matchKind && ts.findChildOfKind(token.parent, matchKind, sourceFile); // We want to order the braces when we return the result. @@ -103010,29 +111509,36 @@ var ts; } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); }); } - function getCombinedCodeFix(scope, fixId, formatOptions) { + function getCombinedCodeFix(scope, fixId, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext, preferences: preferences }); } - function organizeImports(scope, formatOptions) { + function organizeImports(scope, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program); + return ts.OrganizeImports.organizeImports(sourceFile, formatContext, host, program, preferences); + } + function getEditsForFileRename(oldFilePath, newFilePath, formatOptions, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } + return ts.getEditsForFileRename(getProgram(), oldFilePath, newFilePath, host, ts.formatting.getFormatContext(formatOptions), preferences, sourceMapper); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -103045,7 +111551,7 @@ var ts; ? host.installPackage({ fileName: ts.toPath(action.file, currentDirectory, getCanonicalFileName), packageName: action.packageName }) : Promise.reject("Host does not implement `installPackage`"); default: - ts.Debug.fail(); + return ts.Debug.fail(); // TODO: Debug.assertNever(action); will only work if there is more than one type. } } @@ -103081,10 +111587,26 @@ var ts; } return true; } + function getJsxClosingTagAtPosition(fileName, position) { + var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var token = ts.findPrecedingToken(position, sourceFile); + if (!token) + return undefined; + var element = token.kind === 29 /* GreaterThanToken */ && ts.isJsxOpeningElement(token.parent) ? token.parent.parent + : ts.isJsxText(token) ? token.parent : undefined; + if (element && isUnclosedTag(element)) { + return { newText: "" }; + } + } + function isUnclosedTag(_a) { + var openingElement = _a.openingElement, closingElement = _a.closingElement, parent = _a.parent; + return !ts.tagNamesAreEquivalent(openingElement.tagName, closingElement.tagName) || + ts.isJsxElement(parent) && ts.tagNamesAreEquivalent(openingElement.tagName, parent.openingElement.tagName) && isUnclosedTag(parent); + } function getSpanOfEnclosingComment(fileName, position, onlyMultiLine) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); - return range && ts.createTextSpanFromRange(range); + var range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position); + return range && (!onlyMultiLine || range.kind === 3 /* MultiLineCommentTrivia */) ? ts.createTextSpanFromRange(range) : undefined; } function getTodoComments(fileName, descriptors) { // Note: while getting todo comments seems like a syntactic operation, we actually @@ -103136,7 +111658,8 @@ var ts; descriptor = descriptors[i]; } } - ts.Debug.assert(descriptor !== undefined); + if (descriptor === undefined) + return ts.Debug.fail(); // We don't want to match something like 'TODOBY', so we make sure a non // letter/digit follows the match. if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { @@ -103211,10 +111734,9 @@ var ts; } function getRenameInfo(fileName, position) { synchronizeHostData(); - var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); - return ts.Rename.getRenameInfo(program.getTypeChecker(), defaultLibFileName, getCanonicalFileName, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); } - function getRefactorContext(file, positionOrRange, formatOptions) { + function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; return { file: file, @@ -103224,17 +111746,20 @@ var ts; host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, + preferences: preferences, }; } - function getApplicableRefactors(fileName, positionOrRange) { + function getApplicableRefactors(fileName, positionOrRange, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange)); + return ts.refactor.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences)); } - function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName) { + function getEditsForRefactor(fileName, formatOptions, positionOrRange, refactorName, actionName, preferences) { + if (preferences === void 0) { preferences = ts.emptyOptions; } synchronizeHostData(); var file = getValidSourceFile(fileName); - return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, formatOptions), refactorName, actionName); + return ts.refactor.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName, actionName); } return { dispose: dispose, @@ -103276,19 +111801,21 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getJsxClosingTagAtPosition: getJsxClosingTagAtPosition, getSpanOfEnclosingComment: getSpanOfEnclosingComment, getCodeFixesAtPosition: getCodeFixesAtPosition, getCombinedCodeFix: getCombinedCodeFix, applyCodeActionCommand: applyCodeActionCommand, organizeImports: organizeImports, + getEditsForFileRename: getEditsForFileRename, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, - getSourceFile: getSourceFile, getProgram: getProgram, getApplicableRefactors: getApplicableRefactors, getEditsForRefactor: getEditsForRefactor, + toLineColumnOffset: sourceMapper.toLineColumnOffset, + getSourceMapper: function () { return sourceMapper; }, }; - var _a; } ts.createLanguageService = createLanguageService; /* @internal */ @@ -103297,7 +111824,7 @@ var ts; if (!sourceFile.nameTable) { initializeNameTable(sourceFile); } - return sourceFile.nameTable; + return sourceFile.nameTable; // TODO: GH#18217 } ts.getNameTable = getNameTable; function initializeNameTable(sourceFile) { @@ -103324,7 +111851,7 @@ var ts; */ function literalIsName(node) { return ts.isDeclarationName(node) || - node.parent.kind === 252 /* ExternalModuleReference */ || + node.parent.kind === 257 /* ExternalModuleReference */ || isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } @@ -103336,13 +111863,13 @@ var ts; switch (node.kind) { case 9 /* StringLiteral */: case 8 /* NumericLiteral */: - if (node.parent.kind === 146 /* ComputedPropertyName */) { + if (node.parent.kind === 147 /* ComputedPropertyName */) { return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: return ts.isObjectLiteralElement(node.parent) && - (node.parent.parent.kind === 182 /* ObjectLiteralExpression */ || node.parent.parent.kind === 261 /* JsxAttributes */) && + (node.parent.parent.kind === 186 /* ObjectLiteralExpression */ || node.parent.parent.kind === 266 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } return undefined; @@ -103351,28 +111878,28 @@ var ts; /* @internal */ function getPropertySymbolsFromContextualType(typeChecker, node) { var objectLiteral = node.parent; - var contextualType = typeChecker.getContextualType(objectLiteral); - return getPropertySymbolsFromType(contextualType, node.name); + var contextualType = typeChecker.getContextualType(objectLiteral); // TODO: GH#18217 + return getPropertySymbolsFromType(contextualType, node.name); // TODO: GH#18217 } ts.getPropertySymbolsFromContextualType = getPropertySymbolsFromContextualType; /* @internal */ function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_6 = []; + var result_7 = []; var symbol = type.getProperty(name); - if (type.flags & 131072 /* Union */) { + if (type.flags & 262144 /* Union */) { ts.forEach(type.types, function (t) { var symbol = t.getProperty(name); if (symbol) { - result_6.push(symbol); + result_7.push(symbol); } }); - return result_6; + return result_7; } if (symbol) { - result_6.push(symbol); - return result_6; + result_7.push(symbol); + return result_7; } } return undefined; @@ -103381,7 +111908,7 @@ var ts; function isArgumentOfElementAccessExpression(node) { return node && node.parent && - node.parent.kind === 184 /* ElementAccessExpression */ && + node.parent.kind === 188 /* ElementAccessExpression */ && node.parent.argumentExpression === node; } /** @@ -103399,9 +111926,6 @@ var ts; ts.getDefaultLibFilePath = getDefaultLibFilePath; ts.objectAllocator = getServicesObjectAllocator(); })(ts || (ts = {})); -// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. -// See LICENSE.txt in the project root for complete license information. -/// /* @internal */ var ts; (function (ts) { @@ -103415,7 +111939,7 @@ var ts; if (sourceFile.isDeclarationFile) { return undefined; } - var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); + var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); var lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line; if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) { // Get previous token if the token is returned starts on new line @@ -103423,14 +111947,15 @@ var ts; // let y = 10; // token at position will return let keyword on second line as the token but we would like to use // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line - tokenAtLocation = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); + var preceding = ts.findPrecedingToken(tokenAtLocation.pos, sourceFile); // It's a blank line - if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) { + if (!preceding || sourceFile.getLineAndCharacterOfPosition(preceding.getEnd()).line !== lineOfPosition) { return undefined; } + tokenAtLocation = preceding; } // Cannot set breakpoint in ambient declarations - if (tokenAtLocation.flags & 2097152 /* Ambient */) { + if (tokenAtLocation.flags & 4194304 /* Ambient */) { return undefined; } // Get the span in the node based on its syntax @@ -103442,7 +111967,7 @@ var ts; return ts.createTextSpanFromBounds(start, (endNode || startNode).getEnd()); } function textSpanEndingAtNextToken(startNode, previousTokenToFindNextEndToken) { - return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent)); + return textSpan(startNode, ts.findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent, sourceFile)); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) { @@ -103457,119 +111982,120 @@ var ts; return spanInNode(ts.findPrecedingToken(node.pos, sourceFile)); } function spanInNextNode(node) { - return spanInNode(ts.findNextToken(node, node.parent)); + return spanInNode(ts.findNextToken(node, node.parent, sourceFile)); } function spanInNode(node) { if (node) { + var parent = node.parent; switch (node.kind) { - case 212 /* VariableStatement */: + case 217 /* VariableStatement */: // Span on first variable declaration return spanInVariableDeclaration(node.declarationList.declarations[0]); - case 230 /* VariableDeclaration */: - case 151 /* PropertyDeclaration */: - case 150 /* PropertySignature */: + case 235 /* VariableDeclaration */: + case 152 /* PropertyDeclaration */: + case 151 /* PropertySignature */: return spanInVariableDeclaration(node); - case 148 /* Parameter */: + case 149 /* Parameter */: return spanInParameterDeclaration(node); - case 232 /* FunctionDeclaration */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 190 /* FunctionExpression */: - case 191 /* ArrowFunction */: + case 237 /* FunctionDeclaration */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 194 /* FunctionExpression */: + case 195 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } // falls through - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: return spanInBlock(node); - case 267 /* CatchClause */: + case 272 /* CatchClause */: return spanInBlock(node.block); - case 214 /* ExpressionStatement */: + case 219 /* ExpressionStatement */: // span on the expression return textSpan(node.expression); - case 223 /* ReturnStatement */: + case 228 /* ReturnStatement */: // span on return keyword and expression if present return textSpan(node.getChildAt(0), node.expression); - case 217 /* WhileStatement */: + case 222 /* WhileStatement */: // Span on while(...) return textSpanEndingAtNextToken(node, node.expression); - case 216 /* DoStatement */: + case 221 /* DoStatement */: // span in statement of the do statement return spanInNode(node.statement); - case 229 /* DebuggerStatement */: + case 234 /* DebuggerStatement */: // span on debugger keyword return textSpan(node.getChildAt(0)); - case 215 /* IfStatement */: + case 220 /* IfStatement */: // set on if(..) span return textSpanEndingAtNextToken(node, node.expression); - case 226 /* LabeledStatement */: + case 231 /* LabeledStatement */: // span in statement return spanInNode(node.statement); - case 222 /* BreakStatement */: - case 221 /* ContinueStatement */: + case 227 /* BreakStatement */: + case 226 /* ContinueStatement */: // On break or continue keyword and label if present return textSpan(node.getChildAt(0), node.label); - case 218 /* ForStatement */: + case 223 /* ForStatement */: return spanInForStatement(node); - case 219 /* ForInStatement */: + case 224 /* ForInStatement */: // span of for (a in ...) return textSpanEndingAtNextToken(node, node.expression); - case 220 /* ForOfStatement */: + case 225 /* ForOfStatement */: // span in initializer return spanInInitializerOfForLike(node); - case 225 /* SwitchStatement */: + case 230 /* SwitchStatement */: // span on switch(...) return textSpanEndingAtNextToken(node, node.expression); - case 264 /* CaseClause */: - case 265 /* DefaultClause */: + case 269 /* CaseClause */: + case 270 /* DefaultClause */: // span in first statement of the clause return spanInNode(node.statements[0]); - case 228 /* TryStatement */: + case 233 /* TryStatement */: // span in try block return spanInBlock(node.tryBlock); - case 227 /* ThrowStatement */: + case 232 /* ThrowStatement */: // span in throw ... return textSpan(node, node.expression); - case 247 /* ExportAssignment */: + case 252 /* ExportAssignment */: // span on export = id return textSpan(node, node.expression); - case 241 /* ImportEqualsDeclaration */: + case 246 /* ImportEqualsDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleReference); - case 242 /* ImportDeclaration */: + case 247 /* ImportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 248 /* ExportDeclaration */: + case 253 /* ExportDeclaration */: // import statement without including semicolon return textSpan(node, node.moduleSpecifier); - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: // span on complete module if it is instantiated if (ts.getModuleInstanceState(node) !== 1 /* Instantiated */) { return undefined; } // falls through - case 233 /* ClassDeclaration */: - case 236 /* EnumDeclaration */: - case 271 /* EnumMember */: - case 180 /* BindingElement */: + case 238 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 276 /* EnumMember */: + case 184 /* BindingElement */: // span on complete node return textSpan(node); - case 224 /* WithStatement */: + case 229 /* WithStatement */: // span in statement return spanInNode(node.statement); - case 149 /* Decorator */: - return spanInNodeArray(node.parent.decorators); - case 178 /* ObjectBindingPattern */: - case 179 /* ArrayBindingPattern */: + case 150 /* Decorator */: + return spanInNodeArray(parent.decorators); + case 182 /* ObjectBindingPattern */: + case 183 /* ArrayBindingPattern */: return spanInBindingPattern(node); // No breakpoint in interface, type alias - case 234 /* InterfaceDeclaration */: - case 235 /* TypeAliasDeclaration */: + case 239 /* InterfaceDeclaration */: + case 240 /* TypeAliasDeclaration */: return undefined; // Tokens: case 25 /* SemicolonToken */: @@ -103599,7 +112125,7 @@ var ts; case 74 /* CatchKeyword */: case 87 /* FinallyKeyword */: return spanInNextNode(node); - case 144 /* OfKeyword */: + case 145 /* OfKeyword */: return spanInOfKeyword(node); default: // Destructuring pattern in destructuring assignment @@ -103612,13 +112138,13 @@ var ts; // `a` or `...c` or `d: x` from // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || - node.kind === 202 /* SpreadElement */ || - node.kind === 268 /* PropertyAssignment */ || - node.kind === 269 /* ShorthandPropertyAssignment */) && - ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) { + node.kind === 206 /* SpreadElement */ || + node.kind === 273 /* PropertyAssignment */ || + node.kind === 274 /* ShorthandPropertyAssignment */) && + ts.isArrayLiteralOrObjectLiteralDestructuringPattern(parent)) { return textSpan(node); } - if (node.kind === 198 /* BinaryExpression */) { + if (node.kind === 202 /* BinaryExpression */) { var _a = node, left = _a.left, operatorToken = _a.operatorToken; // Set breakpoint in destructuring pattern if its destructuring assignment // [a, b, c] or {a, b, c} of @@ -103639,23 +112165,23 @@ var ts; } } if (ts.isExpressionNode(node)) { - switch (node.parent.kind) { - case 216 /* DoStatement */: + switch (parent.kind) { + case 221 /* DoStatement */: // Set span as if on while keyword return spanInPreviousNode(node); - case 149 /* Decorator */: + case 150 /* Decorator */: // Set breakpoint on the decorator emit return spanInNode(node.parent); - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return textSpan(node); - case 198 /* BinaryExpression */: + case 202 /* BinaryExpression */: if (node.parent.operatorToken.kind === 26 /* CommaToken */) { // If this is a comma expression, the breakpoint is possible in this expression return textSpan(node); } break; - case 191 /* ArrowFunction */: + case 195 /* ArrowFunction */: if (node.parent.body === node) { // If this is body of arrow function, it is allowed to have the breakpoint return textSpan(node); @@ -103664,21 +112190,21 @@ var ts; } } switch (node.parent.kind) { - case 268 /* PropertyAssignment */: + case 273 /* PropertyAssignment */: // If this is name of property assignment, set breakpoint in the initializer if (node.parent.name === node && !ts.isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) { return spanInNode(node.parent.initializer); } break; - case 188 /* TypeAssertionExpression */: + case 192 /* TypeAssertionExpression */: // Breakpoint in type assertion goes to its operand if (node.parent.type === node) { return spanInNextNode(node.parent.type); } break; - case 230 /* VariableDeclaration */: - case 148 /* Parameter */: { + case 235 /* VariableDeclaration */: + case 149 /* Parameter */: { // initializer of variable/parameter declaration go to previous node var _b = node.parent, initializer = _b.initializer, type = _b.type; if (initializer === node || type === node || ts.isAssignmentOperator(node.kind)) { @@ -103686,7 +112212,7 @@ var ts; } break; } - case 198 /* BinaryExpression */: { + case 202 /* BinaryExpression */: { var left = node.parent.left; if (ts.isArrayLiteralOrObjectLiteralDestructuringPattern(left) && node !== left) { // If initializer of destructuring assignment move to previous token @@ -103716,9 +112242,10 @@ var ts; } function spanInVariableDeclaration(variableDeclaration) { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.parent.kind === 219 /* ForInStatement */) { + if (variableDeclaration.parent.parent.kind === 224 /* ForInStatement */) { return spanInNode(variableDeclaration.parent.parent); } + var parent = variableDeclaration.parent; // If this is a destructuring pattern, set breakpoint in binding pattern if (ts.isBindingPattern(variableDeclaration.name)) { return spanInBindingPattern(variableDeclaration.name); @@ -103727,7 +112254,7 @@ var ts; // or its declaration from 'for of' if (variableDeclaration.initializer || ts.hasModifier(variableDeclaration, 1 /* Export */) || - variableDeclaration.parent.parent.kind === 220 /* ForOfStatement */) { + parent.parent.kind === 225 /* ForOfStatement */) { return textSpanFromVariableDeclaration(variableDeclaration); } if (ts.isVariableDeclarationList(variableDeclaration.parent) && @@ -103768,7 +112295,7 @@ var ts; } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { return ts.hasModifier(functionDeclaration, 1 /* Export */) || - (functionDeclaration.parent.kind === 233 /* ClassDeclaration */ && functionDeclaration.kind !== 154 /* Constructor */); + (functionDeclaration.parent.kind === 238 /* ClassDeclaration */ && functionDeclaration.kind !== 155 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { // No breakpoints in the function signature @@ -103791,26 +112318,26 @@ var ts; } function spanInBlock(block) { switch (block.parent.kind) { - case 237 /* ModuleDeclaration */: + case 242 /* ModuleDeclaration */: if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } // falls through // Set on parent if on same line otherwise on first statement - case 217 /* WhileStatement */: - case 215 /* IfStatement */: - case 219 /* ForInStatement */: + case 222 /* WhileStatement */: + case 220 /* IfStatement */: + case 224 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); // Set span on previous token if it starts on same line otherwise on the first statement of the block - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } // Default action is to set on first statement return spanInNode(block.statements[0]); } function spanInInitializerOfForLike(forLikeStatement) { - if (forLikeStatement.initializer.kind === 231 /* VariableDeclarationList */) { + if (forLikeStatement.initializer.kind === 236 /* VariableDeclarationList */) { // Declaration list - set breakpoint in first declaration var variableDeclarationList = forLikeStatement.initializer; if (variableDeclarationList.declarations.length > 0) { @@ -103835,21 +112362,21 @@ var ts; } function spanInBindingPattern(bindingPattern) { // Set breakpoint in first binding element - var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 204 /* OmittedExpression */ ? element : undefined; }); + var firstBindingElement = ts.forEach(bindingPattern.elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } // Empty binding pattern of binding element, set breakpoint on binding element - if (bindingPattern.parent.kind === 180 /* BindingElement */) { + if (bindingPattern.parent.kind === 184 /* BindingElement */) { return textSpan(bindingPattern.parent); } // Variable declaration is used as the span return textSpanFromVariableDeclaration(bindingPattern.parent); } function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node) { - ts.Debug.assert(node.kind !== 179 /* ArrayBindingPattern */ && node.kind !== 178 /* ObjectBindingPattern */); - var elements = node.kind === 181 /* ArrayLiteralExpression */ ? node.elements : node.properties; - var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 204 /* OmittedExpression */ ? element : undefined; }); + ts.Debug.assert(node.kind !== 183 /* ArrayBindingPattern */ && node.kind !== 182 /* ObjectBindingPattern */); + var elements = node.kind === 185 /* ArrayLiteralExpression */ ? node.elements : node.properties; + var firstBindingElement = ts.forEach(elements, function (element) { return element.kind !== 208 /* OmittedExpression */ ? element : undefined; }); if (firstBindingElement) { return spanInNode(firstBindingElement); } @@ -103857,18 +112384,18 @@ var ts; // just nested element in another destructuring assignment // set breakpoint on assignment when parent is destructuring assignment // Otherwise set breakpoint for this element - return textSpan(node.parent.kind === 198 /* BinaryExpression */ ? node.parent : node); + return textSpan(node.parent.kind === 202 /* BinaryExpression */ ? node.parent : node); } // Tokens: function spanInOpenBraceToken(node) { switch (node.parent.kind) { - case 236 /* EnumDeclaration */: + case 241 /* EnumDeclaration */: var enumDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile)); - case 233 /* ClassDeclaration */: + case 238 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: return spanInNodeIfStartsOnSameLine(node.parent.parent, node.parent.clauses[0]); } // Default to parent node @@ -103876,25 +112403,25 @@ var ts; } function spanInCloseBraceToken(node) { switch (node.parent.kind) { - case 238 /* ModuleBlock */: + case 243 /* ModuleBlock */: // If this is not an instantiated module block, no bp span if (ts.getModuleInstanceState(node.parent.parent) !== 1 /* Instantiated */) { return undefined; } // falls through - case 236 /* EnumDeclaration */: - case 233 /* ClassDeclaration */: + case 241 /* EnumDeclaration */: + case 238 /* ClassDeclaration */: // Span on close brace token return textSpan(node); - case 211 /* Block */: + case 216 /* Block */: if (ts.isFunctionBlock(node.parent)) { // Span on close brace token return textSpan(node); } // falls through - case 267 /* CatchClause */: + case 272 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - case 239 /* CaseBlock */: + case 244 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -103902,7 +112429,7 @@ var ts; return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; - case 178 /* ObjectBindingPattern */: + case 182 /* ObjectBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return spanInNode(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -103918,7 +112445,7 @@ var ts; } function spanInCloseBracketToken(node) { switch (node.parent.kind) { - case 179 /* ArrayBindingPattern */: + case 183 /* ArrayBindingPattern */: // Breakpoint in last binding element or binding pattern if it contains no elements var bindingPattern = node.parent; return textSpan(ts.lastOrUndefined(bindingPattern.elements) || bindingPattern); @@ -103933,12 +112460,12 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 216 /* DoStatement */ || // Go to while keyword and do action instead - node.parent.kind === 185 /* CallExpression */ || - node.parent.kind === 186 /* NewExpression */) { + if (node.parent.kind === 221 /* DoStatement */ || // Go to while keyword and do action instead + node.parent.kind === 189 /* CallExpression */ || + node.parent.kind === 190 /* NewExpression */) { return spanInPreviousNode(node); } - if (node.parent.kind === 189 /* ParenthesizedExpression */) { + if (node.parent.kind === 193 /* ParenthesizedExpression */) { return spanInNextNode(node); } // Default to parent node @@ -103947,21 +112474,21 @@ var ts; function spanInCloseParenToken(node) { // Is this close paren token of parameter list, set span in previous token switch (node.parent.kind) { - case 190 /* FunctionExpression */: - case 232 /* FunctionDeclaration */: - case 191 /* ArrowFunction */: - case 153 /* MethodDeclaration */: - case 152 /* MethodSignature */: - case 155 /* GetAccessor */: - case 156 /* SetAccessor */: - case 154 /* Constructor */: - case 217 /* WhileStatement */: - case 216 /* DoStatement */: - case 218 /* ForStatement */: - case 220 /* ForOfStatement */: - case 185 /* CallExpression */: - case 186 /* NewExpression */: - case 189 /* ParenthesizedExpression */: + case 194 /* FunctionExpression */: + case 237 /* FunctionDeclaration */: + case 195 /* ArrowFunction */: + case 154 /* MethodDeclaration */: + case 153 /* MethodSignature */: + case 156 /* GetAccessor */: + case 157 /* SetAccessor */: + case 155 /* Constructor */: + case 222 /* WhileStatement */: + case 221 /* DoStatement */: + case 223 /* ForStatement */: + case 225 /* ForOfStatement */: + case 189 /* CallExpression */: + case 190 /* NewExpression */: + case 193 /* ParenthesizedExpression */: return spanInPreviousNode(node); // Default to parent node default: @@ -103971,20 +112498,20 @@ var ts; function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration if (ts.isFunctionLike(node.parent) || - node.parent.kind === 268 /* PropertyAssignment */ || - node.parent.kind === 148 /* Parameter */) { + node.parent.kind === 273 /* PropertyAssignment */ || + node.parent.kind === 149 /* Parameter */) { return spanInPreviousNode(node); } return spanInNode(node.parent); } function spanInGreaterThanOrLessThanToken(node) { - if (node.parent.kind === 188 /* TypeAssertionExpression */) { + if (node.parent.kind === 192 /* TypeAssertionExpression */) { return spanInNextNode(node); } return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 216 /* DoStatement */) { + if (node.parent.kind === 221 /* DoStatement */) { // Set span on while expression return textSpanEndingAtNextToken(node, node.parent.expression); } @@ -103992,7 +112519,7 @@ var ts; return spanInNode(node.parent); } function spanInOfKeyword(node) { - if (node.parent.kind === 220 /* ForOfStatement */) { + if (node.parent.kind === 225 /* ForOfStatement */) { // Set using next token return spanInNextNode(node); } @@ -104004,8 +112531,6 @@ var ts; BreakpointResolver.spanInSourceFileAtLocation = spanInSourceFileAtLocation; })(BreakpointResolver = ts.BreakpointResolver || (ts.BreakpointResolver = {})); })(ts || (ts = {})); -/// -/// var ts; (function (ts) { /** @@ -104016,7 +112541,7 @@ var ts; */ function transform(source, transformers, compilerOptions) { var diagnostics = []; - compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); + compilerOptions = ts.fixupCompilerOptions(compilerOptions, diagnostics); // TODO: GH#18217 var nodes = ts.isArray(source) ? source : [source]; var result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); @@ -104038,7 +112563,6 @@ var ts; // See the License for the specific language governing permissions and // limitations under the License. // -/// /* @internal */ var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. @@ -104066,16 +112590,16 @@ var ts; var oldSnapshotShim = oldSnapshot; var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); if (encoded === null) { - return null; + return null; // TODO: GH#18217 } - var decoded = JSON.parse(encoded); + var decoded = JSON.parse(encoded); // TODO: GH#18217 return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; ScriptSnapshotShimAdapter.prototype.dispose = function () { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { - this.scriptSnapshotShim.dispose(); + this.scriptSnapshotShim.dispose(); // TODO: GH#18217 Can we just use `if (this.scriptSnapshotShim.dispose)`? } }; return ScriptSnapshotShimAdapter; @@ -104090,10 +112614,10 @@ var ts; // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = function (moduleNames, containingFile) { - var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); + var resolutionsInFile = JSON.parse(_this.shimHost.getModuleResolutionsForFile(containingFile)); // TODO: GH#18217 return ts.map(moduleNames, function (name) { var result = ts.getProperty(resolutionsInFile, name); - return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; + return result ? { resolvedFileName: result, extension: ts.extensionFromPath(result), isExternalLibraryImport: false } : undefined; // TODO: GH#18217 }); }; } @@ -104102,8 +112626,8 @@ var ts; } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); - return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); + var typeDirectivesForFile = JSON.parse(_this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); // TODO: GH#18217 + return ts.map(typeDirectiveNames, function (name) { return ts.getProperty(typeDirectivesForFile, name); }); // TODO: GH#18217 }; } } @@ -104123,7 +112647,7 @@ var ts; LanguageServiceShimHostAdapter.prototype.getProjectVersion = function () { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion - return undefined; + return undefined; // TODO: GH#18217 } return this.shimHost.getProjectVersion(); }; @@ -104156,7 +112680,7 @@ var ts; }; LanguageServiceShimHostAdapter.prototype.getScriptKind = function (fileName) { if ("getScriptKind" in this.shimHost) { - return this.shimHost.getScriptKind(fileName); + return this.shimHost.getScriptKind(fileName); // TODO: GH#18217 } else { return 0 /* Unknown */; @@ -104192,7 +112716,7 @@ var ts; return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); }; LanguageServiceShimHostAdapter.prototype.readDirectory = function (path, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; LanguageServiceShimHostAdapter.prototype.readFile = function (path, encoding) { @@ -104213,11 +112737,11 @@ var ts; this.directoryExists = function (directoryName) { return _this.shimHost.directoryExists(directoryName); }; } if ("realpath" in this.shimHost) { - this.realpath = function (path) { return _this.shimHost.realpath(path); }; + this.realpath = function (path) { return _this.shimHost.realpath(path); }; // TODO: GH#18217 } } CoreServicesShimHostAdapter.prototype.readDirectory = function (rootDir, extensions, exclude, include, depth) { - var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); + var pattern = ts.getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); // TODO: GH#18217 return JSON.parse(this.shimHost.readDirectory(rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth)); }; CoreServicesShimHostAdapter.prototype.fileExists = function (fileName) { @@ -104289,7 +112813,8 @@ var ts; start: diagnostic.start, length: diagnostic.length, category: ts.diagnosticCategoryName(diagnostic), - code: diagnostic.code + code: diagnostic.code, + reportsUnnecessary: diagnostic.reportsUnnecessary, }; } var LanguageServiceShimObject = /** @class */ (function (_super) { @@ -104414,9 +112939,9 @@ var ts; return this.forwardJSONCall("getBreakpointStatementAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getBreakpointStatementAtPosition(fileName, position); }); }; /// SIGNATUREHELP - LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position) { + LanguageServiceShimObject.prototype.getSignatureHelpItems = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position); }); + return this.forwardJSONCall("getSignatureHelpItems('" + fileName + "', " + position + ")", function () { return _this.languageService.getSignatureHelpItems(fileName, position, options); }); }; /// GOTO DEFINITION /** @@ -104510,16 +113035,16 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, options) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); + return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + preferences + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); }; /** Get a string based representation of a completion list entry details */ - LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { + LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { - var localOptions = options === undefined ? undefined : JSON.parse(options); - return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); + var localOptions = formatOptions === undefined ? undefined : JSON.parse(formatOptions); + return _this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source, preferences); }); }; LanguageServiceShimObject.prototype.getFormattingEditsForRange = function (fileName, start, end, options /*Services.FormatCodeOptions*/) { @@ -104595,10 +113120,12 @@ var ts; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; + if (syntacticClassifierAbsent === void 0) { syntacticClassifierAbsent = false; } return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", function () { return convertClassifications(_this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)); }, this.logPerformance); }; /// COLORIZATION ClassifierShimObject.prototype.getClassificationsForLine = function (text, lexState, classifyKeywordsInGenerics) { + if (classifyKeywordsInGenerics === void 0) { classifyKeywordsInGenerics = false; } var classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); var result = ""; for (var _i = 0, _a = classification.entries; _i < _a.length; _i++) { @@ -104660,7 +113187,8 @@ var ts; importedFiles: _this.convertFileReferences(result.importedFiles), ambientExternalModules: result.ambientExternalModules, isLibFile: result.isLibFile, - typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives) + typeReferenceDirectives: _this.convertFileReferences(result.typeReferenceDirectives), + libReferenceDirectives: _this.convertFileReferences(result.libReferenceDirectives) }; }); }; @@ -104733,7 +113261,7 @@ var ts; this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var hostAdapter = new LanguageServiceShimHostAdapter(host); - var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry); + var languageService = ts.createLanguageService(hostAdapter, this.documentRegistry, /*syntaxOnly*/ false); return new LanguageServiceShimObject(this, host, languageService); } catch (err) { @@ -104799,7 +113327,7 @@ var TypeScript; // TODO: it should be moved into a namespace though. /* @internal */ var toolsVersion = ts.versionMajorMinor; - +//# sourceMappingURL=typescriptServices.out.js.map // MONACOCHANGE export const createClassifier = ts.createClassifier; export const createLanguageService = ts.createLanguageService; diff --git a/src/tsWorker.ts b/src/tsWorker.ts index 89cc3689..3faf8f38 100644 --- a/src/tsWorker.ts +++ b/src/tsWorker.ts @@ -144,11 +144,11 @@ export class TypeScriptWorker implements ts.LanguageServiceHost { } getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise { - return Promise.as(this._languageService.getCompletionEntryDetails(fileName, position, entry, undefined, undefined)); + return Promise.as(this._languageService.getCompletionEntryDetails(fileName, position, entry, undefined, undefined, undefined)); } getSignatureHelpItems(fileName: string, position: number): Promise { - return Promise.as(this._languageService.getSignatureHelpItems(fileName, position)); + return Promise.as(this._languageService.getSignatureHelpItems(fileName, position, undefined)); } getQuickInfoAtPosition(fileName: string, position: number): Promise {